content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dict_from_graph_attr(graph, attr, array_values=False):
"""
Parameters
----------
graph : networkx.Graph
attr : str, iterable, or dict
If str, then it specifies the an attribute of the graph's nodes.
If iterable of strings, then multiple attributes of the graph's nodes
ar... | 3d097842d92670d8c0217a8ec179cf5e61c83780 | 3,630,815 |
from scipy.signal import freqz
def _filter_attenuation(h, frequencies, gains):
""" Compute minimum attenuation at stop frequency.
Args:
h (array): Filter coefficients.
frequencies (list): Transition frequencies normalized.
gains (array): Filter gain at frequency sampling points.
... | e412d987ae83e5f6ae4bae5f550d1cb22590bd41 | 3,630,816 |
def about1():
"""
Name : about1 function
Module : routes
Description : This function loads about1.html page.
Parameters: None
Returns : This function returns the About-us tab of the Web app.
Written By : Abhishek Mestry ,Ninad Kadam ,Viresh Dhuri
Version : 1.0.0
... | 0e4ab7ea15e0f54c35eb746b41944fba065c8d2e | 3,630,817 |
from operator import and_
from operator import lt
from operator import ge
from operator import eq
from typing import cast
def local_adv_sub1_adv_inc_sub1(fgraph, node):
"""Optimize the possible AdvSub1(AdvSetSub1(...), ...).
AdvancedSubtensor1(AdvancedSetSubtensor1(x, y, idx), idx) -> y
Notes
-----
... | f69b7be639457b0147dcb5836a86028277bfa939 | 3,630,819 |
import asyncio
def mock_coro(return_value=None, exception=None):
"""Return a coro that returns a value or raise an exception."""
fut = asyncio.Future()
if exception is not None:
fut.set_exception(exception)
else:
fut.set_result(return_value)
return fut | d06d037bab143e288534e3e7e98da259f7c1cefc | 3,630,820 |
from typing import Tuple
def convert_to_classes(data: MoleculeDataset, num_bins: int = 20) -> Tuple[MoleculeDataset,
np.ndarray,
MoleculeDataset]:
"""
Converts ... | f8ff21234c94315387fc2669e0ff02d3c3d68fb6 | 3,630,821 |
def construct_lambda_schedule(num_windows):
"""Generate a length-num_windows list of lambda values from 0.0 up to 1.0
Notes
-----
manually optimized by YTZ
"""
A = int(.35 * num_windows)
B = int(.30 * num_windows)
C = num_windows - A - B
# Empirically, we see the largest variance ... | af9104ad7c5f8a529a3098d495c3fbfb38ca5df2 | 3,630,822 |
import torch
def compute_face_normals_and_areas(vertices: torch.Tensor, faces: torch.Tensor):
"""
:params
vertices (B,N,3)
faces (B,F,3)
:return
face_normals (B,F,3)
face_areas (B,F)
"""
ndim = vertices.ndimension()
if vertices.ndimension() == 2... | c586b621d8621aedd4a19d0da11d97e705fe2a06 | 3,630,823 |
def der_Cquat_by_v(q,v):
"""
Being C=C(quat) the rotational matrix depending on the quaternion q and
defined as C=quat2rotation(q), the function returns the derivative, w.r.t. the
quanternion components, of the vector dot(C,v), where v is a constant
vector.
The elements of the resulting derivat... | a4ade85551921a96bc371fc2d99793490637a561 | 3,630,824 |
def calc_BMDs(Tcpl,BMR=dict(E=[10,20,30],Z=[1,2,3]),
ret='dict',add_info=False,
dbg=False):
"""
Calculate benchmark doses corresponding to bmrs:-
E: fractional efficacy (top)
Z: number of standard deviations (assumes response is in units of Z)
"""
BF = Tcpl['bes... | 478f7b5a811ef0996a3f7db847fe8c9a8aa1b23b | 3,630,825 |
import requests
import json
def request_records(request_params):
"""
Download utility rate records from USURDB given a set of request
parameters.
:param request_params: dictionary with request parameter names as
keys and the parameter values
:return:
"""
records = requests.get(
... | 7323657186cc87a291e47c3a71cd2e81b4ec8a73 | 3,630,826 |
def _handle_sort_key(model_name, sort_key=None):
"""Generate sort keys according to the passed in sort key from user.
:param model_name: Database model name be query.(alarm, meter, etc.)
:param sort_key: sort key passed from user.
return: sort keys list
"""
sort_keys_extra = {'alarm': ['name', ... | aef2d996d9d18593ec129c4a37bf8150b3e9c0fe | 3,630,827 |
def view_clear_pages_cache(self, request, form):
""" Clears the pages cache. """
layout = DefaultLayout(self, request)
if form.submitted(request):
request.app.pages_cache.flush()
request.message(_("Cache cleared."), 'success')
return redirect(layout.manage_link)
return {
... | 3cad0b2ab565b558c575131e38530c6f548a9f25 | 3,630,828 |
def cyan_on_red(string, *funcs, **additional):
"""Text color - cyan on background color - red. (see sgr_combiner())."""
return sgr_combiner(string, ansi.CYAN, *funcs, attributes=(ansi.BG_RED,)) | 80072a9df6e8f0c13154d8f563c04d36cfdbc6e1 | 3,630,829 |
def calc_glass_constants(nd, nF, nC, *partials):
"""Given central, blue and red refractive indices, calculate Vd and PFd.
Args:
nd, nF, nC: refractive indices at central, short and long wavelengths
partials (tuple): if present, 2 ref indxs, n4 and n5, wl4 < wl5
Returns:
... | f347b6caf167c19451bb2f03e88b5846c6873250 | 3,630,830 |
def light_rgb_schema(gateway, child, value_type_name):
"""Return a validation schema for V_RGB."""
schema = {"V_RGB": cv.string, "V_STATUS": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) | da6b262b8e0c0cc8461e0184e67c6b2bc6c9bee4 | 3,630,832 |
from datetime import datetime
def macro_timedelta(start_date, years=0, months=0, days=0):
"""Since datetime doesn't provide timedeltas at the year or month level,
this function generates timedeltas of the appropriate sizes.
"""
delta = datetime.timedelta(days=days)
new_month = start_date.month + ... | ee2df42abc74d14951a03827d9c5de67f10cac38 | 3,630,833 |
import re
def chomp_keep_single_spaces(string):
"""This chomp cleans up all white-space, not just at the ends"""
string = str(string)
result = string.replace("\n", " ") # Convert line ends to spaces
result = re.sub(" [ ]*", " ", result) # Truncate multiple spaces to single space
result = result.... | e72a3e416dbbeb97d3984f7f3883a91b0ab13877 | 3,630,834 |
def index():
"""Displays the main page"""
user = get_user()
# XXX
return redirect('/login')
# Render template
render = render_template('main.html', lang=lang, user=user)
return make_response(render) | 0548c072d7eb0def56e444beab39937933fa12c6 | 3,630,835 |
import re
def _unhumanize(human_time_interval):
"""Converts human_time_interval (e.g. 'an hour ago') into a
datetime.timedelta.
"""
munged = human_time_interval.strip()
for needle in _SINGULARS:
munged = munged.replace(needle, '1 ')
interval_re = '|'.join(_DELTAS.keys())
sre = re.... | c70ba342cfb7721517365fed0596a312d35179a1 | 3,630,837 |
import re
def parase_pbs_script(filename = "emtojob.pbs"):
"""
Parse the exe part of pbs file
Parameter
filename: str (filename-like)
The filename of the pbs script
Return
param_dict: dict
The dict of parameters.
"""
s = {"-q": "queue", "-A": "account",... | 7c1aed9c08a21b123d70e1697d3cf72fcd418a5e | 3,630,838 |
async def handle_errors(request: Request, exception: Exception):
"""
Handles exceptions raised by the API.
Parameters
----------
exception : Exception
Returns
-------
str
"""
return JSONResponse(
status_code=exception.code,
content={"message": exception.message}... | 13a5240d5790f5edbd359c24a990c7adada8a3cc | 3,630,839 |
def immortal():
""" Make target (if 400+) or self (if 399-) immortal. """
av = spellbook.getTarget() if spellbook.getInvokerAccess() >= 400 else spellbook.getInvoker()
av.setImmortalMode(not av.immortalMode)
return 'Toggled immortal mode %s for %s' % ('ON' if av.immortalMode else 'OFF', av.getName()) | ad10c3ff62e583e55ba55bc09c4214a2f670d3aa | 3,630,840 |
import math
def read_command_line_branch(input_path=None, output_path=None):
"""
Read arguments from commandline and return all values in a dictionary.
If input_path and output_path are not None, then do not parse command line, but
only return default values.
Args:
input_path (str): Input... | b838e60a78cd6840d2802a879d6d64cf29bf4e6c | 3,630,841 |
def predict_fr(dst_path, ref_path):
"""
用于FR的预测函数
:param dst_path:
:param ref_path:
:return:
"""
assert ref_path is not None
if utils.is_img(dst_path):
img_dst = cv2.imread(dst_path)
img_dst = utils.transform(img_dst, config.input_process)[np.newaxis, ...]
img_ref... | 2eeb4e123d09136d5da037b2955cf5f331ed8e6c | 3,630,842 |
def disk_example():
"""Create an example of disk element.
This function returns an instance of a simple disk. The purpose is to make available
a simple model so that doctest can be written using it.
Returns
-------
disk : ross.DiskElement
An instance of a disk object.
Examples
... | b02c25a59f52ca47c84c5fffa29414fc622555c1 | 3,630,843 |
def build_optim(
model,
optim="adam",
lr=0.002,
max_grad_norm=0,
beta1=0.9,
beta2=0.999,
decay_method="noam",
warmup_steps=8000,
):
""" Build optimizer """
optim = Optimizer(
optim,
lr,
max_grad_norm,
beta1=beta1,
beta2=beta2,
decay... | eaa1b32098d7eb8f58d0c1ac41906badb56a37c6 | 3,630,844 |
def bst(height=4):
"""Generate a random binary search tree and return its root.
:param height: the height of the tree (default: 4)
:return: the root of the generated binary search tree
"""
values = _generate_values(height)
root = _new_node(values[0])
for index in range(1, len(values)):
... | 301f0776f67bbcd3ce90fa1109bcee80180a6fd1 | 3,630,845 |
from typing import Optional
def get_model_info(model: str, repo: str = "onnx/models:master", opset: Optional[int] = None) -> ModelInfo:
"""
Get the model info matching the given name and opset.
@param model: The name of the onnx model in the manifest. This field is case-sensitive
@param repo: The loc... | 63e94ff122066d26fcf173f49c6f63662443acc0 | 3,630,846 |
def byprotocolobj(protocolobj):
""" Returns the Session for an instance of :class:`Protocol` given
as *protocolobj*. Keys will match when *protocolobj* is an
instance of the respective key class. """
for key in sessions.keys():
if isinstance(protocolobj, key):
return sessions[key]
... | 9d683caec6da167b815fdcc60d02ad1fef002647 | 3,630,847 |
from typing import Callable
from typing import Dict
def trace_numpy_function(
function_to_trace: Callable, function_parameters: Dict[str, BaseValue]
) -> OPGraph:
"""Trace a numpy function.
Args:
function_to_trace (Callable): The function you want to trace
function_parameters (Dict[str, B... | 38454e0251bcc3bde4b9d49c86fd76bf6b4cd278 | 3,630,848 |
def random_crop(arr, new_h=224, new_w=224):
"""Crop an image of shape (dim, dim, channels) to (new_h, new_w, channels)."""
height = len(arr)
width = len(arr[0])
assert height >= new_h
assert width >= new_w
if height > new_h or width > new_w:
height_sample_pt = np.random.randint(height-ne... | 55984b293e66064a919d38a203270134dd5d6b0d | 3,630,849 |
def bilingual(obj, field, attr=None):
""" This is a quick and dirty way to define bilingual content in a single field. """
field_locale = '%s_%s' % (field, get_language())
value = None
try:
value = getattr(obj, field_locale)
except AttributeError:
pass
if not value:
tr... | 1c4c7b5b3ec650f9e30749d6188b99f3b858fc5c | 3,630,850 |
def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
"""Return available quantity for given product in given country."""
try:
stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
except Stock.DoesNotExist:
return 0
return stock.quantity_a... | f3cac101a2079564e35c07542b63c2217c4c9aae | 3,630,851 |
def in_range(x, a1, a2):
"""Check if (modulo 360) x is in the range a1...a2. a1 must be < a2."""
a1 %= 360.
a2 %= 360.
if a1 <= a2: # "normal" range (not including 0)
return a1 <= x <= a2
# "jumping" range (around 0)
return a1 <= x or x <= a2 | 8855ea29e44c546d55122c7c6e4878b44a3bc272 | 3,630,852 |
def _dark_parse_accept_lang_header(accept):
"""
The use of 'zh-cn' for 'Simplified Chinese' and 'zh-tw' for 'Traditional Chinese'
are now deprecated, as discussed here: https://code.djangoproject.com/ticket/18419.
The new language codes 'zh-hans' and 'zh-hant' are now used since django 1.7.
Although... | 03f4b15dba30f569eb4bb853426e5ceeafa6f2a5 | 3,630,853 |
def trip_direction(trip_original_stops, direction_stops):
"""
Guess the trip direction_id based on trip_original_stops, and
a direction_stops which should be a dictionary with 2 keys: "0" and "1" -
corresponding values should be sets of stops encountered in given dir
"""
# Stops for each directi... | a418c90775039b1d52b09cb2057d71f97361e0d9 | 3,630,854 |
def unf_pb_Valko_MPaa(rsb_m3m3, gamma_oil=0.86, gamma_gas=0.6, t_K=350):
"""
bubble point pressure calculation according to Valko McCain (2002) correlation
:param rsb_m3m3: solution ration at bubble point, must be given, m3/m3
:param gamma_oil: specific oil density (by water)
:param gamma_gas: ... | 3879fe70af6116251cc08dfc14934f623e23b57f | 3,630,855 |
def disasm(file, objdump_or_gdb, symbol, start, finish):
"""
Disassemble binary file.
"""
if objdump_or_gdb:
out = _run(['objdump', '-d', file])
elif symbol is not None:
out = _run(['gdb', '-batch', '-ex', f'disassemble {symbol}', file])
else:
out = _run(['gdb', '-batch',... | ec5af11fa6d73698907e48fae58b041027a94160 | 3,630,856 |
def gaussian_on_simplex(mu, sigma, npoints):
"""
This function provides npoints i.i.d. points on the simplex, normally
distributed according to sigma around :math:`mu`.
Parameters
----------
mu : 1D-numpy-array
expectation value on the simplex
sigma : 2D-numpy-array
covarian... | d7b0ef0d897cd3493b8333d528128a2fc68bd359 | 3,630,857 |
def add_common_arguments(parser):
"""Populate the given argparse.ArgumentParser with arguments.
This function can be used to make the definition these argparse arguments
reusable in other modules and avoid the duplication of these definitions
among the executable scripts.
The following arguments a... | c8e3eba16c33f0fcf12caf3a31b281dcee858648 | 3,630,858 |
def circuit(params, a, m1, m2, cutoff):
"""Runs the constrained variational circuit with specified parameters,
returning the output fidelity to the requested ON state, as well as
the post-selection probability.
Args:
params (list): list of gate parameters for the constrained
variati... | fb210648ab05aa99c3644ecce74a175951eb1cb3 | 3,630,860 |
def attr_names(obj):
"""
Determine the names of user-defined attributes of the given SimpleNamespace object.
Source: https://stackoverflow.com/a/27532110
:return: A list of strings.
"""
return sorted(obj.__dict__) | ecbc0321d0796925341731df303c48ea911fcf57 | 3,630,861 |
def treetable(childreds, parents, arg3=None, nodename_colname=None):
""" 输入childres子结点id列表,和parents父结点id列表
两个列表长度必须相等
文档:http://note.youdao.com/noteshare?id=126200f45d301fcb4364d06a0cae8376
有两种调用形式
>> treetable(childreds, parents) --> DataFrame (新建df)
>> treetable(df, child_colname, parent_c... | e5daaa2839a6fdc0cefa444872a38a99e31ce6cb | 3,630,863 |
def plot_drawdown_periods(returns, top=10, k=None, ax=None, **kwargs):
"""
Plots cumulative returns highlighting top drawdown periods.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
... | 258a12f3bb96b727e2486f5ca2c67bec06649e6c | 3,630,864 |
def redirect_back(endpoint='index', **values):
"""
跳转(优先next, 其次endpoint)
:param endpoint:
:param values:
:return:
"""
target = request.args.get('next')
if not target or not is_safe_url(target):
target = url_for(endpoint, **values)
return redirect(target) | 3fd0185d1f0af70f59d6d7b75343ff759cb8f979 | 3,630,865 |
import joblib
def load(
tag: t.Union[str, Tag],
model_store: "ModelStore" = Provide[BentoMLContainer.model_store],
) -> t.Union["BaseEstimator", "Pipeline"]:
"""
Load a model from BentoML local modelstore with given name.
Args:
tag (:code:`Union[str, Tag]`):
Tag of a saved mod... | 892f7c280f097732f97af7054b7e41be9552fdf2 | 3,630,866 |
def tag_to_python(tag):
""" Convert a stream tag to a Python-readable object """
newtag = PythonTag()
newtag.offset = tag.offset
newtag.key = pmt.to_python(tag.key)
newtag.value = pmt.to_python(tag.value)
newtag.srcid = pmt.to_python(tag.srcid)
return newtag | 29687b1322709b953e69089d2f398ba83235dc22 | 3,630,867 |
def corrections(word_in, dictionary, keyboard_cm, ed=2):
"""
@input: word_in - input word
dictionary - dictionary/lexicon
keyboard_cm - confusion matrix for keyboard in question
"""
assert isinstance(dictionary, Dictionary)
candidates = oridam_generate_patterns(word_in, keyboard_cm... | ac6031edef0ef03af6b871425eb9ed60a914fbf2 | 3,630,868 |
def read_polyglot_embeddings(filename):
"""
Read vocabulary and embeddings from a file from polyglot.
"""
with open(filename, 'rb') as f:
data = cPickle.load(f)
# first four words are UNK, <s>, </s> and padding
# we discard <s> and </s>
words = data[0]
matrix = data[1].astyp... | 1351e2f3f50df6b192e06201f1989ffb30b0d6fd | 3,630,869 |
def exp_by_squaring(x, n):
"""Assumes n>=0
See: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
"""
if n == 0:
return 1
if n % 2 == 0:
return exp_by_squaring(x * x, n // 2)
else:
return x * exp_by_squaring(x * x, (n - 1) / 2) | 57eab07b123c72dbeeaa6f5f08d18b4abad5c497 | 3,630,870 |
from dagster.config.field import resolve_to_config_type
def dagster_type_materializer(config_schema, required_resource_keys=None):
"""Create an output materialization hydration config that configurably materializes a runtime
value.
The decorated function should take the execution context, the parsed conf... | feb39a8b745ebc81a761903b76c13edd1670b1da | 3,630,871 |
from typing import Union
from typing import List
def get_models(deploy_cfg: Union[str, mmcv.Config],
model_cfg: Union[str, mmcv.Config], work_dir: str) -> List:
"""Get the output model informantion for deploy.json.
Args:
deploy_cfg (mmcv.Config): Deploy config dict.
model_cfg (... | a8259f52918f41d5142a892f445c1ae30829ce66 | 3,630,872 |
import random
def weighted_choice(choices):
"""
Pick a weighted value off
:param list choices: Each item is a tuple of choice and weight
:return:
"""
total = sum(weight for choice, weight in choices)
selection = random.uniform(0, total)
counter = 0
for choice, weight in choices:
... | c32ff27b9892bb88db2928ec22c4ede644f6792c | 3,630,873 |
def css_s(property, value):
"""Creates a stringified CSSString proto with the given values"""
return proto_to_str(make_cssstyle_proto(property, value)) | 212abbe578d337b39a9ea109f2a7910e1ad3be09 | 3,630,874 |
from datetime import datetime
import json
async def get_expired_members(request):
"""
Returns a list of all members that should have finished their degree, calculated by current semester and normed time
for each members associated study programme.
:param request:
:return: List of all expired memb... | 7de1cbf72b30e8dba7548c4ceb17b8c53efe7f7e | 3,630,876 |
def sim_hawkes(dims, adjacency, decays, baseline, kernel_support, max_points, run_time, phi_inv, plot=False, seed=None, track_intensity=False):
"""Simulate point process using Ogata razor.
Input
- S: Settings dictionary
- plot: Indication of whether to plot events and intensities
- seed: Seed for r... | 9c412324b24426239a152336777cccdcb2b02204 | 3,630,877 |
def ADD(sum, augend, addend):
"""
args:
sum: the register where the addition result is stored.
augend: the left operand of the addition.
addend: the right operand of the addition.
function:
Performs basic addition.
"""
return TacInstruction(instructions.ADD, sum, aug... | c51b6d98c88f6d6d8bb2bde8b20fddb531409f10 | 3,630,878 |
import io
def __convert__(filename):
"""Convert a python script so that it can be called by slave.
The converted file is named by appending '_converted' to the filename."""
with open(filename,'r') as f:
script = f.read()
if '#main' not in script:
raise SlaveError('Could not find #main ... | dc98d0c4046daed743c6b99673e1c39414707e64 | 3,630,879 |
import json
def parse_value(str_val, type):
""" Parse the string representation of a value (e.g., for use with an attribute of an XML object)
Args:
str_val (:obj:`str`): string representation of the value
type (:obj:`ValueType`): type
Returns:
:obj:`object`: Python representation... | 61a96db11d8bccfb05bf85f2ab022f3ba441092e | 3,630,880 |
def _ls_emr_step_logs(fs, log_dir_stream, step_id=None):
"""Yield matching step logs, optionally filtering by *step_id*.
Yields dicts with the keys:
path: path/URI of step file
step_id: step_id in *path* (must match *step_id* if set)
"""
matches = _ls_logs(fs, log_dir_stream, _match_emr_step_lo... | 95162a0a24d3d9e7bb58224ee6f636636aa0a26f | 3,630,881 |
def propeller_icon(icon, **kwargs):
"""
Render an icon
**Tag name**:
propeller_icon
**Parameters**:
icon
Icon name. See the `Propeller docs <http://propeller.in/style/icons.php>`_ for all icons.
size
Size of the icon. Must be one of 'xs', 'sm', 'md', ... | 2e043741ca1cbd1a4feab0c59eb4a31b4c2314fd | 3,630,882 |
def sbasis(i, n):
"""Standard basis vector e_i of dimension n."""
arr = np.zeros(n)
arr[i] = 1.0
return arr | 9afd8f56c52e13ba59baf8f9c458fe3428e8826b | 3,630,883 |
import struct
def decrypt(text):
"""
:param str text:
:rtype: str
"""
plain = []
for i in range(0, len(text), 2):
num, = struct.unpack('!B', text[i])
plain.append(decrypt_bets.get(num))
return ''.join(plain) | e3379909732ff0bb6dbed771cd859d460e6b2964 | 3,630,885 |
def LF_warning_signs_hypothetical(c):
"""
Check if candidate is in a list of warning signs e.g.
preceded by 'Warning Signs:'
:param c: pain-anatomy candidate
:return: -1 if True, 0 otherwise
"""
sent_spans = get_sent_candidate_spans(c)
sent = ''
for span in sent_spans:
word... | 3c03548e66ebb6c8146ec43ee9f63d3337f093d8 | 3,630,886 |
def render_upcoming_events(event_amount=5, category=None):
"""Template tag to render a list of upcoming events."""
return {
'occurrences': _get_upcoming_events(
amount=event_amount, category=category),
} | 015454a6c4a97c1a964eb540892ef1b37ff4dd68 | 3,630,887 |
from typing import List
from typing import Dict
def aggregate_collate_fn(insts: List) -> Dict[str, List[str]]:
"""aggragate the instance to the max seq length in batch.
Args:
insts: list of sample
Returns:
"""
snts, golds = [], []
for inst in insts:
snts.append(inst['snt'])
... | 8d986d508fd2e5a5c91947563aec2b862ab13361 | 3,630,888 |
def isBetween(p1, p2, p, epsilon=1e-5):
""" test if p is between p1 and p2
Parameters
----------
p1 : np.array
p2 : np.array
p : np.array
epsilon : float
tolerance default 1e-5
Returns
-------
boolean
Examples
--------
>>> p1 = np.array([0,0])
>>> p2... | 5a19f6903dfefa7340895a622c8a2a8c7d33b2f4 | 3,630,889 |
import functools
def load_val_data(batch_size, dataset_name):
"""Load Patch Camelyon val data"""
val_dataset = tfds.load(
name=dataset_name, split='validation', as_supervised=True)
val_dataset = val_dataset.map(
functools.partial(preprocess_data, is_training=False))
val_dataset = val_dataset.batch... | 5df6916721f588db3553c7bc05e7b40f0edf6b19 | 3,630,890 |
def dictfetchall(cursor):
"""
Return all rows from a cursor as a dict.
:param cursor: a database cursor.
:return: the results from the cursor as a dictionary.
"""
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row))
for row in cursor.fetchall()] | e8c4d3d53a4d204d2f7ac95fefb08c5a77fa5e5f | 3,630,891 |
def dev_login(request):
"""docstring"""
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request,... | b0f4d2b1b3eb2bdefc361d85b62cadc802a15b54 | 3,630,892 |
def CheckBackwardsCompatibility(new_universe, old_universe):
"""Checks that non-abstract types are not removed or changed in new configs.
Method expects types in passed universe to have inherited_fields_expanded.
Method has the side effect of setting is_changed field on everything in this
universe that has cha... | a1ec6de3062926c0e08789d4d937c3b132b9aacc | 3,630,893 |
def pgram(N, years, fname):
"""
Calculate periodograms of LSST light curves.
"""
ps = np.linspace(2, 100, 1000) # the period array (in days)
print("Computing periodograms")
# Now compute LS pgrams for a set of LSST light curves & save highest peak
ids = np.arange(N)
periods = np.zeros_... | cfbaef2650f025a50b3735d3db39d638242a6175 | 3,630,894 |
def get_layout(data, width_limit):
"""A row of a chart can be dissected as four components below:
1. Label region ('label1'): fixed length (set to max label length + 1)
2. Intermediate region (' | '): 3 characters
3. Bar region ('▇ or '): variable length
This function first calculates the width of... | dbb8bfa2c537f3b05713bf3abdc106ec74bc7ac9 | 3,630,896 |
def add_stats(all_data, yesterday_date_str, rows, key):
""" Given the entire registration report, augment a particular slice
of the data with male/female/total counts and label for each row.
The input rows are dictionaries with entries containing male and
female registrations by date, and total registr... | b49154bce300a601d27e2f7d9fa54899da858472 | 3,630,898 |
import nose
import re
def assert_raises_regex(exception_class, expected_regexp,
callable_obj=None, *args, **kwargs):
"""
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and ke... | f61a5145c62b10d17db3fe4dc380935fb2c1395e | 3,630,899 |
import json
def get_tiff_param(tiff_file):
"""Obtain relevant parameters of TiffFile object"""
xy_dim, description = lookup_page(tiff_file.pages[0])
shape = tiff_file.asarray().shape
if tiff_file.is_fluoview:
return get_fluoview_param(description, xy_dim, shape)
elif tiff_file.is_imagej... | d161f142780e86e19cb2a8e7e9440c4768509119 | 3,630,900 |
def get_number_of_classes(model_config):
"""Returns the number of classes for a detection model.
Args:
model_config: A model_pb2.DetectionModel.
Returns:
Number of classes.
Raises:
ValueError: If the model type is not recognized.
"""
meta_architecture = model_config.WhichOneof("model")
meta... | d87605b6025e1bc78c7436affe740f7591a99f68 | 3,630,901 |
from typing import Optional
def to_xy0(
xyz: npt.ArrayLike, radius: Optional[float] = 1.0, stacked: Optional[bool] = True
) -> np.ndarray:
"""
Convert geocentric xyz coordinates to longitude (φ) and latitude (λ)
xy0 (i.e., φλ0) coordinates.
Parameters
----------
xyz : ArrayLike
A ... | 9f3e94def7f7fa5d34a791fcd054068874f5621b | 3,630,902 |
def getDataset(filepath = ""):
"""
Reads a comma separated variables (csv) file and creates a dataset.
A dataset has the following components: Variables, Data, Types, Groups, Sorts
To call each componenet of a dataset, do the following.
Say you have a dataset named: somedata
somedata['VARIABLES'... | cb3ae7b9b392a702729078df009452cff0a965b6 | 3,630,903 |
def draw_matches(img0, img1, kpts0, kpts1, match_idx,
downscale_ratio=1, color=(0, 255, 0), radius=4, thickness=2):
"""
Args:
img: color image.
kpts: Nx2 numpy array.
match_idx: Mx2 numpy array indicating the matching index.
Returns:
display: image with drawn... | 17b118bf175bef066292b370a7f0571425900fc3 | 3,630,904 |
def shorten_build_target(build_target: str) -> str:
"""Returns a shortened version of the build target."""
if build_target == '//chrome/android:chrome_java':
return 'chrome_java'
return build_target.replace('//chrome/browser/', '//c/b/') | 03af53f1fcacae9a4e0309053075806d65275ce9 | 3,630,905 |
from datetime import datetime
import copy
def store_initial_role_data(dynamo_table, arn, create_date, role_id, role_name, account_number, current_policy, tags):
"""
Store the initial version of a role in Dynamo
Args:
role (Role)
current_policy (dict)
Returns:
None
"""
... | 2c6a54a3b6fc414e638e3ba2870201c73b37a2b1 | 3,630,906 |
def apply_shift(x, shift, out):
"""
Translates elements of `x` along axis=0 by `shift`, using linear
interpolation for non-integer shifts.
Parameters
----------
x : ndarray
Array with ndim >= 1, holding data.
shift : float
Shift magnitude.
out : ndarray
Array wit... | 86e58c536cbc2fb43bb049aab6d0d4d733308bbd | 3,630,907 |
import platform
def get_socket(dname, protocol, host, dno):
"""socket = get_socket(dname, protocol, host, dno)
Connect to the display specified by DNAME, PROTOCOL, HOST and DNO, which
are the corresponding values from a previous call to get_display().
Return SOCKET, a new socket object connected to ... | d2703d7747ffac8d142f170dd153169f111f8b5d | 3,630,908 |
def azureblobstorage_folder_list(node_addon, **kwargs):
""" Returns all the subsequent folders under the folder id passed.
"""
return node_addon.get_folders() | d6934946a428e592ab2644ffbfb0a28ebb2ad9c8 | 3,630,909 |
def summary_statistics(is_significant, time_interp, n_records_at_t, n_window):
"""Compute summary statistics."""
# Initialize
significant_number = np.zeros(len(time_interp))
significant_relative = np.zeros(len(time_interp))
max_records_around_t = np.zeros(len(time_interp))
for j in xrange(len(... | e970e78a1dfe96220f8ff49a85deccc5dc00f673 | 3,630,910 |
from typing import Tuple
import random
def draw_two(max_n: int) -> Tuple[int, int]:
"""Draw two different ints given max (mod max)."""
i = random.randint(0, max_n)
j = (i + random.randint(1, max_n - 1)) % max_n
return i, j | 9ebb09158c296998c39a2c4e8fc7a18456428fc6 | 3,630,911 |
def compareFloats(a, b, rtol=1.0e-5, atol=opscore.RO.SysConst.FAccuracy):
"""Compares values a and b
Returns 0 if the values are approximately equals, i.e.:
- |a - b| < atol + (rtol * |a + b|)
Else 1 if a > b, -1 if a < b
Inputs:
- a, b: scalars to be compared (int or float)
- atol: absolut... | 6ff9e55040bfbefea11ef6f10cdc88b5e2fa7a77 | 3,630,912 |
def net_import_share_constraint_rule(backend_model, constraint_group, carrier, what):
"""
Enforces demand shares of net imports from transmission technologies for groups of locations,
on average over the entire model period. Transmission within the group are ignored. The share
is relative to ``demand`` ... | 30add5ca89d2b995742e52eec759ca9504029e57 | 3,630,913 |
def loss_gaussian(X):
"""
encode X by CNML
"""
Xmat = np.matrix(X)
n, m = Xmat.shape
if n == 1:
Xmat = Xmat.T
n, m = Xmat.shape
else:
pass
if n <= 0:
return np.nan
Xc = Xmat - np.mean(Xmat, 0)
S = np.dot(Xc.T, Xc / n)
detS = sl.det(S)
l... | b9e7db0b25f8b9b6104d653561b3e13a154a742b | 3,630,914 |
def integrand(x, n):
"""
Bessel function of first kind and order n.
"""
return jn(n, x) | 6b5dce69f94285518cc6e23b4ae23f22e0e981fc | 3,630,915 |
def get_forms_tuple(*args):
"""
Converts a string of grammemes to a tuple of two sets:
- set of tags for declension
- set of tags for refining the word form
"""
forms = list()
specs = list()
for arg in args:
for key in force_str(arg).split(','):
if key in INFL... | 9f8264b29e0828ffa01af6da1704d7f9c889e167 | 3,630,916 |
def truncate(inputs, channels, data_format):
"""Slice the inputs to channels if necessary."""
if data_format == 'channels_last':
input_channels = inputs.get_shape()[3].value
else:
assert data_format == 'channels_first'
input_channels = inputs.get_shape()[1].value
if input_channe... | 965574da9af5e85c80ce66ed13b36d13b5cffbef | 3,630,917 |
def do_rating_by_user(parser, token):
"""
Returns a User's Rating of a Snippet, if any.
Example::
{% get_rating_by_user user.id object.id as rating %}
"""
bits = token.contents.split()
if len(bits) != 5:
raise template.TemplateSyntaxError("'%s' tag takes exactly four ar... | 761e3414bc3c292e315c25d79e1c7417e6f894c7 | 3,630,918 |
def get_label_funcs_threshold(bin_count=10, lower=1e-9, upper=1e-3, bin_func=bin_func_sum):
"""
:param bin_count: Number of different thresholds to encode the goes flux into.
:param lower: Lower limit for valid goes flux values.
:param upper: Upper limit for valid goes flux values.
:param bin_func: ... | 561dbc5b468b2b657908403ef39e630fe66649d9 | 3,630,920 |
def modify_layer(layer, name, norm = None, dropout = None):
"""Add BatchNorm and/or Dropout on top of `layer`"""
if dropout is not None:
name = "%s-dropout" % (name)
layer = Dropout(dropout, name = name)(layer)
if norm is not None:
name = "%s-%snorm" % (name, norm)
layer =... | 169905b19fe29d1beee2b4a3b5a5e97cb9ca9e93 | 3,630,921 |
def create_access(terms_to_check, new_term):
"""
Breaks a new_term up into separate constituent parts so that they can be
compared in a check_access test.
Returns a list of terms that should be inserted.
"""
protos = new_term.match.get('protocol', ['any'])
sources = new_term.m... | 61a3a6b786f61b56698e360a6b6acaf393d0fa15 | 3,630,922 |
def versionPropertiesDictionary(sql_row_list):
"""
versionPropertiesDictionary(sql_row_list)
transforms a row gotten via SQL request (list), to a dictionary
"""
properties_dictionary = \
{
"id": sql_row_list[0],
"model_id": sql_row_list[1],
"version": sql_row_list[2]... | ab8cdd166bf8a187945c44fd416c3a4cf4634d02 | 3,630,923 |
import logging
def verify_received_aes_key(key: dict, rsa_public_key) -> bool:
"""
Verifies the AES key received as a dict and passed here is valid.
:param dict key: An AES key, as a dictionary.
:param rsa_public_key: The RSA public key of the author.
:return bool: True if the information is a va... | 53d0578d8761a06be260b7a63dff97e123a4e010 | 3,630,925 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.