content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def recdropfields(rec, names):
"""
Return a new numpy record array with fields in *names* dropped.
From http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.rec_drop_fields
:param rec: :class:`numpy.recarray` containing a number of fields.
:param list names: List of names to drop from the record... | 5004f332467b969642fc5b382a8f08eb05696ef5 | 74,711 |
def to_log_returns(prices):
"""
计算价格的对数收益率,ln(p1/p0)
参数:
prices: price series
"""
return np.log(prices / prices.shift(1)) | 1b8ff88b560f6cb1a1e34d00f1819f357e4703b2 | 74,712 |
def fit(
X,
y,
X_test=None,
y_test=None,
partitions=None,
clazzes=[Kriging, RBF],
defaults={},
models=None,
return_benchmark=False,
return_selection=False,
**kwargs):
"""
Find the best out of a variety of surrogates regardi... | 7b8d0457d7faf2c028585da5445633c35ae55700 | 74,713 |
def decode_unicode(message):
"""
Decodes a unicode encoded message
Raises a ValueError if the message can't be decoded
"""
result = u''
for index in range(0, len(message), 4):
word = message[index:index+4]
match = pat.match(word)
if match is None:
raise Value... | 3aa3216616c48c9f218c5d25413f2cdfc79cc1b4 | 74,714 |
def get_tri_from_course(course, courses):
"""
Given a courses dict, return the trimester of the :param course
"""
for tri in courses:
for _course in courses[tri]:
if course == _course:
return tri.capitalize() | 7923884dc84d363544d38330e8124ff6afe16231 | 74,716 |
def process_movie(m):
"""
gets the imdb id for the given movie
:param m: tunefind movie object
:return: omdb movie object with imdbid
"""
print m["title"]
re_match = re.search("^(.*?)(\s\(\d{4}\))?$", m["title"])
if len(re_match.groups()) < 2:
title = m["title"]
else:
... | b8aea28c95322d3b5d2a7a8d8ecc28fa5d485d76 | 74,719 |
import random
def test_Space_NO1_basis_functions_mapping_test():
"""
Unittests for the mesh.
"""
if rAnk == mAster_rank:
print("sss {test_Space_NO1_basis_functions_mapping_test} ...... ", flush=True)
if rAnk == mAster_rank:
el1 = random.randint(1,3)
el2 = random.randint(1,... | 847fc8c8f861ed33f17ecee980fac9b67936fd0b | 74,720 |
import torch
def caption_image_beam_search(encoder, decoder, image, word_map, beam_size=3):
"""
Reads an image and captions it with beam search.
:param encoder: encoder model
:param decoder: decoder model
:param image: PIL Image
:param word_map: word map
:param beam_size: number of sequenc... | 79e8eefcd95b6d613028a1875c464387b2b619a8 | 74,721 |
def cell_vertices_mask(im, vertex_dilation_factor, mask=None, periphery_excluded=True):
"""
Make a bool mask of all vertex regions of segmented cells.
Parameters
----------
im : 2D ndarray
Regions labeled with unique values. 0 regions are treated as
background, masked out.
verte... | 822f7c1620bff8b2fbdcfd1ce5403380c14ed0c6 | 74,722 |
def _register_api_entry(f, _entry_name):
"""
注册api入口
:param f: 入口函数
:param _entry_name: entry路径
:return:
"""
entry_path = _to_entry_path(_entry_name)
_do_register_api_entry(ApiEntry(f), entry_path)
return entry_path | a749d6a9f6e01d0cb02d361248479a66e8076129 | 74,723 |
def downsample(arr, factors):
"""
Downsample image `arr` by factors in each dimension
Parameters
----------
arr : Zarr Array
factors : tuple
Returns
-------
output : ndarray
"""
if not isinstance(arr, np.ndarray):
# Load image
data = arr[:]
else:
... | a2a986c1bd7b8db56d70fe9e0e282a0e0b765cf4 | 74,724 |
def build_parser_for(hook_type):
"""Build an argument parser for the given hook string.
:param str hook_type: The hook type string to generate an argument parser from.
:rtype: argparse.ArgumentParser
"""
cli_flags = HookFlagDefinitions()[hook_type]
return _generate_parser(**cli_flags) | 1df1a37837224fdc068aef799ca164ff85dde1dc | 74,725 |
def PV_BenefitMat(t):
"""Present value of matuirty benefits"""
if t > last_t():
return 0
else:
return (-BenefitMat(t) + PV_BenefitMat(t+1)) / (1 + DiscRate(t)) | ce7f600180ea84fbb230e67431493081c19c6ef0 | 74,726 |
from typing import Union
from typing import Dict
def _resource_dict(mem: Union[str, int], cpu: Union[str, int]) -> Dict[str, str]:
"""
Private helper function to create a resource dictionary for deployments. Currently only supports the creation
of the requests/limits directory that is needed for a V1Resor... | dc00bcba7442f655e0f56e6390b1675078ca9e4f | 74,727 |
def is_hexstring(string):
"""
Determines if a string is a hexstring.
:param Union[ByteString, str] string: A string.
:return: Whether the string's length is even and all of its characters
are in [0-9a-fA-f].
"""
if isinstance(string, str):
string = string.encode()
return not ... | 7263cbbb464d805b6e5f0142a2ff6772894c4837 | 74,728 |
def notas(*n, sit=False):
"""
-> Funcao para analisar notas e situacoes de alunos
:param n: uma ou mais notas de alunos
:param sit: valor opcional, indicando se deve ou nao adicionar a situacao
:return: dicionario com varias informacoes sobre a situacao da turma
"""
r = dict()
r['total']... | 9b6ef88d0008709ba034dbe496d153f0f51dcb1d | 74,729 |
def train_step(gen_model, disc_model, x, y):
"""Single train step function for the SRGAN.
Args:
gen_model: A compiled generator model.
disc_model: A compiled discriminator model.
x: The low resolution input image.
y: The desired high resolution output image.
Returns:
... | bd1dd6f989b7fc3c26de368af1a4b73e1fb9565e | 74,731 |
def vonMises(sigma, tau, principle_stress = False):
"""
Computes the von Mises equivalent stress
:param sigma:
:param tau:
:param principle_stress:
:return:
"""
size = len(sigma)
if size == 1:
s_x = sigma[0]
s_y = 0.0
tau = tau[0]
s_vm = (s_x ** 2 -... | 3240edaaa971ca19cc5f1df4bfe9ac12c80fabc5 | 74,732 |
def norm_hamming(string1,string2):
"""Custom Normalized Hamming Distance"""
return distance.hamming(list(string1), list(string2)) | 535f6abd944f7b82530ab891ea88c7b5cf3ac838 | 74,733 |
import copy
def merge_schema_dicts(inputschema_dict, outputschema_dict):
"""
Merge the information from the input schema into the outputschema
This combines the type information and adjusts the paths from the inputschema
to be valid in the out.xml file, i.e. `/fleurInput/cell` becomes `/fleurOutput/fl... | 11d9888cb733d27e6e9a80bceae0133b690a05db | 74,734 |
def min_ind_of_anch(anchor_info):
""" Finds the index of min ID. """
anch_id = list(anchor_info.keys())
min_id_ind = anch_id.index(min(anch_id))
return min_id_ind | 89e77679a21f36016174cf8a52ec4b210e1ad295 | 74,735 |
import hashlib
def lfs_get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
N... | b88c82080ed38d03ae73378602754c3215274783 | 74,736 |
def initialize_velocity(parameters):
"""
Initializes the velocity as a python dictionary with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Arguments:
parameters -- python dictionary ... | 9894295d95932b7955d69dc2fd0958399b58736e | 74,737 |
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understan... | dadc56a5f6b482721f99ba700d81be50bb332687 | 74,738 |
def CreationInfo_ConstCast(*args):
"""
ConstCast(BaseObject o) -> CreationInfo
CreationInfo_ConstCast(Seiscomp::Core::BaseObjectCPtr o) -> CreationInfo
"""
return _DataModel.CreationInfo_ConstCast(*args) | 06f9414cbcc27331077744798101060cb49111bc | 74,739 |
def pkcs5_pad(data, block_size):
"""使用 RFC 2898 描述的 PKCS #5 算法补齐。
许多对称加密算法会要求要加密的信息长度需要是多少字节(例如 8
字节)的整倍数,因此需要有某种算法对不符合要求的信息进行补齐。
Args:
data (bytes): 需要补齐的报文。
block_size (int): 块长度。
Returns:
bytes: 补齐后的信息。
"""
if not isinstance(data, bytes):
raise ValueErro... | 3d4e941e844bf4be2bcc9b9318a3472c4b8bbe8e | 74,741 |
def get_source_result(Source, num=32):
"""
returns the result for a given source
Parameters
----------
source : cls
source class that is tested.
num : int, optional
number of samples to return. The default is 32.
Returns
-------
array
first block returned by... | bf51f0d3e378d3926ff82fede810b12afd142770 | 74,743 |
def _make_marray(ts, mmodes=None, mmax=None, dtype=None):
"""Make an m-mode array from a sidereal stream.
This will loop over the first axis of `ts` to avoid needing a lot of memory for
intermediate arrays.
It can also write the m-mode output directly into a passed `mmodes` array.
"""
if dtyp... | 0ab3eec1c997bd9a78626460c848c8b6ec7926b3 | 74,744 |
def apply_kernel(x: np.ndarray, kernel: np.ndarray) -> np.ndarray:
"""
Convolves a 2d kernel over the input image
Parameters
----------
x : np.ndarray
input image
kernel : np.ndarray
the kernel to use
Returns
-------
np.ndarray
the convolved image
... | 03713b2319534c564279244c1d09ceec814bba64 | 74,745 |
import math
def gravityVector(a, b):
"""computes the force of gravity exerted ON 'a' BY 'b'"""
gravVector = (math.cos(angle(a,b))*gravityForce(a,b), math.sin(angle(a,b))*gravityForce(a,b))
if a.position[0] > b.position[0]:
gravVector = (-gravVector[0], -gravVector[1])
return gravVector | 0ff39300718c3588c8045a59c0ae36fc7adb9d6f | 74,746 |
def name_from_id(id):
"""Hash the id into a run name
Construct the name of the run from the id dictionary
Args:
id (dict): id associated to the run
Returns:
str: name of the run associated to the dictionary ``id``
"""
keys = list(id.keys())
keys.sort()
name = ''
for ... | ad8eeed94e7f22e96c197753ed59652dcbfcda8e | 74,747 |
from typing import AnyStr
def update_tenant(tenant: AnyStr, password: AnyStr) -> int:
"""
Update a tenant in database.
:tenant (AnyStr) A string representing the name of the tenant
:password (AnyStr) A string to use as password
Return the number of row updated, 0 in case of fail, 1 otherwise
... | 1e0111776b1c9e9a3c826e7b4d0a108e6fa6532d | 74,748 |
def dbfun(i, n, u, p, U):
"""Evaluates derivatives up to :math:`n` th order of a single
bspline basis function :math:`\\frac{\partial^n}{\partial u^n} B_{i,p}(u)`
at the coordinate :math:`u`
Parameters:
i (int) : basis function index
n (in) : highest derivative order
u (float) :... | ad91e78bdf5ae65652ff6ce0918d57b66f24aea5 | 74,749 |
async def fetch_language(id: int):
"""Fetch a weekly challenge language by its id."""
query = """
SELECT *,
l.id::TEXT
FROM challengelanguages l
WHERE l.id = $1
"""
record = await ChallengeLanguage.pool.fetchrow(query, id)
if not record:
raise HTTP... | 6420f98870693fb970554266220a81f19267b6f4 | 74,750 |
def memoize(timeout, jitter=0):
"""
Decorator to cache a function by name/args
:param timeout: How long to keep the result
:param jitter: Randomize the timeout by this many seconds
"""
if isinstance(timeout, timedelta):
timeout = timeout.seconds
timeout += randint(-jitter/2, jitter... | dbff6a0fc05f7c36b25f040ad81dd141176911cd | 74,751 |
def calculate_clinker(annual_production, clinker_cement_ratio):
"""
Calculate annual clinker production based on given cement/clinker ratio
:param annual_production: Reported annual production
:param clinker_cement_ratio: Amount of clinker produced per cement output
:return: Clinker per year
"""... | f08f4757ee27c2f4e54fd7acbbdaea398bee1a6e | 74,752 |
def polygon_to_lines(geometry):
"""Return a list of shapely lines given higher order shapely geometry."""
line_list = []
last_point = geometry.exterior.coords[0]
for point in geometry.exterior.coords[1::]:
if point == last_point:
continue
line_list.append(shapely.geometry.Lin... | 061aba3fa4019f331353d5e83ecf1aaba309b9dd | 74,753 |
def GetDepsByNames(names):
"""Gets the deps string by names."""
result = ''
temp_code = ''
for name in names:
method = GetMethodByName(name)
if method:
temp_code = method.code.text
if method.dependency:
temp_code = method.dependency.code.text + temp_code
result += temp_code
... | 9743364b3321edee65bdbfef0d75b611f0868bb1 | 74,754 |
def fixtures():
"""
Fetch fixture data for the given date range.
Params
------
Request with the following URL params:
start_date (string of form 'yyyy-mm-dd', required): Start of date range
(inclusive) for which you want data.
end_date (string of form 'yyyy-mm-dd', requi... | 903e5a001a9f69ec7191a63c0e79fc78fe206ecc | 74,755 |
import warnings
def _instantiate_input_states(owner, input_states=None, reference_value=None, context=None):
"""Call State._instantiate_state_list() to instantiate ContentAddressableList of InputState(s)
Create ContentAddressableList of InputState(s) specified in paramsCurrent[INPUT_STATES]
If input_sta... | 3316067d26b4054578e9d81b9aff8681480dd34e | 74,756 |
def make_generator_instance(int_model_def):
"""Returns instance of a <Model>Run.
"""
return int_model_def.RunClass(int_model_def) | 7acd0def22a92b6ea5a997a5f0d90e1ab06218af | 74,757 |
def get_deprecated_map():
"""
Get the mapping of deprecated names with some metadata.
"""
# Import everything there is to import, so the map is fully populated
import_all_submodules(lisa)
return DEPRECATED_MAP | cd133f9fe91dada5fcd622d70bb5a31a83fe5704 | 74,758 |
import torch
def loss_task(encoded, prototypes, target, criterion='dist'):
"""Calculate loss.
criterion: NNLoss - assign to closest prototype and calculate NNLoss
dist - loss is distance to prototype that example needs to be assigned to
and -distance to prototypes from other class
... | 9d1dd9f413f43a91c755f3fe3e87cfeea2095c6c | 74,759 |
from typing import Union
from typing import Callable
def plot_heatmaps(heatmap: pd.Series,
agg: Union[str, Callable] = 'max',
*,
ncols: int = 3,
plot_width: int = 1200,
filename: str = '',
open_browser: bool = ... | 517e318e105add66cda8528594873f20907d0e93 | 74,760 |
def accuracy(task_preds, task_targets):
"""Computes the accuracy of a given task.
:param task_preds: Predicted labels.
:param task_targets: Ground-truth targets.
:return: a float metric between 0 and 1.
"""
assert task_preds.size > 0
assert task_targets.size > 0
assert task_targets.siz... | ed8bdef02253c952213b87ee39a86505315e4077 | 74,761 |
def parse_url(url, options=None):
"""
:param url: String
:param options: ConfigParseOptions
:return: Config
"""
if options is None:
options = ConfigParseOptions.defaults()
return impl.Parseable.new_url(url, options).parse().to_config() | afb9e518943edf1fce7f2545c4a31e12c6560bd1 | 74,762 |
from .dataset import Dataset
from typing import OrderedDict
def _dataset_concat(
datasets,
dim,
data_vars,
coords,
compat,
positions,
fill_value=dtypes.NA,
join="outer",
):
"""
Concatenate a sequence of datasets along a new or existing dimension
"""
if compat not in ["... | 5047bf6ab0f59d58b871bac6e10b3bdf65a263fd | 74,763 |
from operator import concat
def _cart_product(input, _flatten):
"""Cartesian product: P = A * B * ..."""
def _is_leaf(input):
"""True if element does not have children."""
if isinstance(input, list) or isinstance(input, tuple):
return False
if tf.is_tensor(input) or isinst... | 5845b910fd99b1a667348d144a2645a939185ce1 | 74,764 |
from typing import Union
def bars_to_milimeter_mercury(bar: float, unit: str) -> Union[float, str]:
"""
This function converts bar to mmHg
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre_of_mercury
>>> bars_to_milimeter_m... | 67ebe4bdc98d03f50e2f2909416e5a05385600e8 | 74,766 |
def get_ligand_filetype(ligand_filename):
"""Returns the filetype of ligand."""
if ".mol2" in ligand_filename:
return ".mol2"
elif ".sdf" in ligand_filename:
return "sdf"
elif ".pdbqt" in ligand_filename:
return ".pdbqt"
elif ".pdb" in ligand_filename:
return ".pdb"
else:
raise ValueErro... | 3f908ab34752be38e51293dc8a81168776aa4e31 | 74,768 |
import struct
def b2f(b):
"""
32bit int to float
"""
return struct.unpack('f', struct.pack('I', b))[0] | d14dbc6182edb9947e4a5416114906a9c09a5751 | 74,769 |
def import_huawei_2g_parsed_csv(parent_dag_name, child_dag_name, start_date, schedule_interval):
"""
Parse huawei 2g cm files.
:param parent_dag_name:
:param child_dag_name:
:param start_date:
:param schedule_interval:
:return:
"""
dag = DAG(
'%s.%s' % (parent_dag_name, child_da... | 84ae733ba7212b4cbc4139981cfb6dcfa9ea0486 | 74,770 |
def start_survey():
"""clearing session"""
session["responses"] = []
return redirect("/questions/0") | 97255d98078f21fd0161b2232d92e2c6708be450 | 74,771 |
def onnx_maxpool(x, kernel_shape, pads=None, strides=None):
"""Numpy-backed implementation of ONNX MaxPool op."""
prefix = (1,) * (x.ndim - len(kernel_shape))
dims = prefix + tuple(kernel_shape)
pads = tuple(pads) if pads else [0] * len(kernel_shape)
strides = (prefix + tuple(strides)) if strides else [1] * l... | 8c384ff6d10de87083d941d60cabd45c258d7d7d | 74,772 |
from scipy import ndimage
import warnings
def _filter_data(data, kernel, mode='constant', fill_value=0.0,
check_normalization=False):
"""
Convolve a 2D image with a 2D kernel.
The kernel may either be a 2D `~numpy.ndarray` or a
`~astropy.convolution.Kernel2D` object.
Parameters
... | fdc520df86ac02324860426bfe10ae50dd95f361 | 74,774 |
def solver_auto_param(u_init, target_photon_matrix, S, StS, lambda_smoothing, smoothing_ratio, T, H, alpha, gamma, B, D, C,\
eta_step = 0.5, ftol = 1e-3, max_iter = 300, eta_0 = None, eta = None, verbose = 0,\
proton_only = False, normalize = False, lambda_step = 10.0, enforce_smooth_u = False, max_iter_warm_s... | b1edf10fc5d943b5380307773acc6b10c26c7f79 | 74,775 |
from typing import Union
def binarr(num: int, width: int = None, dtype: Union[int, str] = None) -> np.ndarray:
"""Returns the bits of an integer as a binary array.
Parameters
----------
num : int or Spinstate
The number representing the binary state.
width : int, optional
Minimum ... | c1485b6a3c443a516915ebb710448bd13dc5078a | 74,776 |
def strip(table, col):
"""Removes column col from the given table
Preconditions: table is a (non-ragged) 2d List,
col valid column"""
n_row = len(table)
n_col = len(table[0])
assert col < n_col, repr(col) + "要删除的列大于总列数!"
for row in range(n_row):
table[row] = table[row][:col]+table[ro... | 09171295b7ed46d12188eb8c882a60f5fce80647 | 74,777 |
def getfdbFuzzyset(csr, id):
"""
根据事实id获取事实对应的模糊集
:param csr:
:param id:事实id
:return:事实对应的模糊集,行向量
"""
csr.execute("select linguistic_variable,fuzzy_set from fdb where id = {}".format(id))
ling_var, setid = csr.fetchone()
csr.execute("select set{} from fdb_{}".format(setid, ling_var))... | c82edcc01479bfa525910a085f80fd95e37a043f | 74,779 |
def situation(df):
"""Gets situational rates"""
tmp1 = plays(df.loc[df.score_differential.abs() <= 6, :])
tmp1['situation_type'] = 'Neutral'
tmp2 = plays(df.loc[df.score_differential > 6, :])
tmp2['situation_type'] = 'Ahead'
tmp3 = plays(df.loc[df.score_differential < -6, :])
tmp3['situation... | 119112aee30f714860171dd54314adc16e0b4645 | 74,780 |
def parse_book_line(line):
"""Parse a line from the book CSV file.
A line is a list of strings as follows:
line = [
book,
title,
author,
year,
publisher,
small_cover_url,
medium_cover_url,
large_cover_url,
... | 91541649c38943bd9fde633c3465bc9f12e37c35 | 74,781 |
from typing import List
from typing import Tuple
def single_qubit_matrix_to_pauli_rotations(
mat: np.ndarray, atol: float = 0
) -> List[Tuple[ops.Pauli, float]]:
"""Implements a single-qubit operation with few rotations.
Args:
mat: The 2x2 unitary matrix of the operation to implement.
ato... | 9a44d300ab6f785ab4413a84512e4525b927256a | 74,782 |
def _predict_tree(model, X, joint_contribution=False):
"""Predict.
For a given DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, or ExtraTreeClassifier,
returns a triple of [prediction, bias and feature_contributions], such
that prediction approx bias + feature_contributions.
"... | 9957de9f136f8f40445c8efcb49fa00b79dad7d2 | 74,783 |
def x_correlation_id():
"""
Parser for generic X-Correlation-ID header
:rtype: str|None
"""
return generic_http_header_parser_for('X-Correlation-ID')() | 072a3c1d5fe52b708926d0692c864829b628efe3 | 74,784 |
import click
from datetime import datetime
import time
def cmd(ctx, url, wait, sleep, max_wait):
"""Get the status of the Axonius instance."""
def get_status():
"""Get the system status safely."""
try:
data = entry.system_status
message = data.msg
status_co... | 53d0d0cac39fb5a482904c6525d5d41faedd0b9d | 74,785 |
def logout(request):
"""Logout route config function."""
headers = forget(request)
return HTTPFound(request.route_url('list_view'), headers=headers) | 425595117fcd201bd57f42440829ccf056c248f3 | 74,786 |
import fastapi
from typing import Dict
from typing import List
async def predict(
request: fastapi.Request) -> Dict[str, List[Dict[str, List[int]]]]:
"""Handles prediction requests.
Unpacks observations in prediction requests and queries the trained policy for
predicted actions.
Args:
request: Incom... | 7861f5a5b23ba7e955a6e97bd2b67d926452c1a5 | 74,787 |
def _parse_aggregation_feat(aggregating_in, features):
"""Parse aggregation information and format in a correct standard way.
Parameters
----------
aggregating_in: tuple
the information for aggregating features
features: pst.BaseFeatures
the features we want to aggregate.
Retur... | e909cb032d97f5598ceb4321b44a8ecb4f0463fd | 74,788 |
def string_to_bool(value):
"""
This will convert a string to a bool if it is a str, return the bool if it was a bool, and raise a TypeError
otherwise
"""
if isinstance(value, bool):
return value
elif isinstance(value, str):
return bool(strtobool(value))
else:
raise I... | 490e548b4d5ceff48c5f08457bb88e1e4956fe88 | 74,789 |
def cross_spectra_cF(trl_dat,
samplerate=1,
nSamples=None,
foi=None,
taper="hann",
taper_opt=None,
demean_taper=False,
polyremoval=False,
timeAxis=0,
... | 210de548f35aac78263bda23fb60a032d724bf2a | 74,790 |
def get_image():
"""Returns the image used by the GCE VM."""
# Format is projects/<id>/global/images/<image>
metadata = get_metadata()
return metadata['instance']['image'].rsplit('/', 1)[-1] | 3d26c6804061abf099606556920c4cf35a6a790f | 74,791 |
def get_init_signature(cls):
""" Gets the signature of an init function of a class.
:param cls: Class to get init signature of.
:type cls: type
:rtype: signature.Signature
"""
# get the init method
init_method = get_method("__init__", cls.__dict__, cls.__bases__,
... | a57f29d3a19aa1ff6a8903075a128786b83f4dcb | 74,792 |
import random
def forestFire_mod(n, p):
"""
Generates a graph based on a modified Forest Fire model.
This is a modified version of the Forest Fire model
that creates undirected edges in the edge creation process.[1]
Input:
n = number of nodes in the graph (integer)
p = "burn" rat... | 7cd0383ee3f90f5206fdb91f79190a9fb91ab8f0 | 74,793 |
def loss(hypes, decoded_logits, labels):
"""Calculate the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float.
"""
logits = decoded_logits['logit... | a10db3c147c198d218522209a99d23bdec4e1733 | 74,794 |
def decimals() -> int:
"""
Gets the amount of decimals used by the token.
:return: the number of decimals used by the token.
"""
return TOKEN_DECIMALS | d5dbb990d26d9afcc079c2821f0110bdca8bf35c | 74,795 |
import requests
from bs4 import BeautifulSoup
import fnmatch
def get_wsa_entry():
"""Returns a tuple containing the Windows Subsystem for Android link and its file name (used to check for
updates) """
store_id = "9p3395vx91nr"
api_url = "https://store.rg-adguard.net/api/GetFiles"
data = {
... | 2430a15dc8f9172b005ab548b15f9b57d9a3ddfb | 74,796 |
import torch
def apply_exponential_kernel_batch(input_images, mu, sigma_sq):
""" apply an exponential kernel to an input image
:param input_images: image to apply the kernel to
:param mu: the center of the kernel
:param sigma_sq: the (half) width of the kernel, squared
:return output_image: the i... | d4741010d0ee7f8336f91636c0e287f9c1490cec | 74,797 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This chart shows the number of VTEC phenomena and
significance combinations issued by a NWS Forecast Office for a given year.
Plea... | 0aa6fe9db51641479006e2bd31a5df926bb43d06 | 74,798 |
def my_hook(t):
"""Wraps tqdm instance.
https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py
Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
-------
"""
last_b = [0]
def update_to(b=1, bsize=1, tsize=None):
... | 918f7a6211f6d5c3d2271c9d39ada652b8ac2b17 | 74,800 |
def serialize_list(value, explicit_type=None):
"""Serializes list data into an json serializable object.
:param list value: instance to serialize
:param string explicit_type: explicit serialization type for value
:return: serialized object
"""
value_type = data_type(value, explicit_type)
tr... | 32e0c933300b3bea3e9c8b9950488c9a45fbe93c | 74,801 |
from .math import reduce_sum
def mean_normalize(f_min, f_max, f_mean, sample_num):
"""
Mean normalization is a method used to normalize the range of independent
variables or features of data.
Refer to:
https://en.wikipedia.org/wiki/Feature_scaling#Mean_normalization
Args:
f_min (Varia... | d2d4da2514c57145f1fa7d7eefaf0489ead9024a | 74,802 |
def vgg16_bn():
"""VGG 16-layer model (configuration "D") with batch normalization"""
return VGG(make_layers(cfg['D'], batch_norm=True)) | 1bafe54c6d2c3c73b25ba41c5673688cbda86573 | 74,803 |
def keras_optimizer_for_idx(idx,
training_steps):
"""Get a nadamw optimizer for the given configuration and training_steps."""
cfg = common.get_optimizer_config(idx)
decay = CustomCosineDecay(
training_steps=training_steps,
learning_rate=cfg["learning_rate"],
min_lea... | 53b0a131c49aa073d055d80cc80aaf369dd5b19f | 74,804 |
def reinterpret_latin1_as_utf8(wrongtext):
""" :see:recode_unicode """
newbytes = wrongtext.encode('latin-1', 'replace')
return newbytes.decode('utf-8', 'replace') | e17e709dba7dacd4ae38c0787dafaef278610074 | 74,805 |
def objective(input_values, spec):
"""
Objective function producing finite horizon welfare estimate from
model specification and inputs
"""
# prepare input for simulation
init_state, policies = prepare_input(input_values, spec)
for state in simulate(policies, init_state, spec): final_state ... | b069a10e8cae5262276fbe49dc347e442f1548d3 | 74,806 |
def generate_edge_image(image, edge_width=1):
"""Generates an edge mask from the image."""
if edge_width < 3:
result_image = Image.new('L', image.size)
"""
for x_offset, y_offset in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
offset_image = ImageChops.offset(image, x_offset, y_offset... | 032e833d665e26323de4a1d9d96c81ea2682b188 | 74,807 |
def generator_dcgan(hparams, y, z, scope_name, train, reuse):
"""
The architecture is from
https://github.com/carpedm20/DCGAN-tensorflow
License: https://github.com/carpedm20/DCGAN-tensorflow/blob/master/LICENSE
"""
s = 28
gf_dim = 64 # dimension of generator filters in first conv layer
... | 9285a25bfe9f04e6ef6284b1fd2be31a1ecc607c | 74,809 |
import ctypes
def ekbseg(handle, tabnam, cnames, decls):
"""
Start a new segment in an E-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekbseg_c.html
:param handle: File handle.
:type handle: int
:param tabnam: Table name.
:type tabnam: str
:param cnames: Names of co... | 5c20c16ca87dc1846645d8f9b240c36505a45a36 | 74,810 |
def parser():
"""Add and parse a TOSCA file.
Add and parses a TOSCA file and make accesible the result
from DB.
Args:
tosca_file: A XML Tosca file to parse.
Returns:
A JSON response showing the results. For
example:
{
'response': 'OK',
'_... | 132d5f7f3cf30293520b480b5163ef7bcb02bf9a | 74,811 |
def parameter_docstring(cls: object):
"""
A function to extract the parameters section of a docstring. Can be used to
add these parameters to an inheriting class without all the effort of
copying and pasting. This assumes docstrings following the `numpy convention <https://numpydoc.readthedocs.io/en/lat... | 28f77499a2776652f2e84f853e19e75d06beb992 | 74,812 |
def css(data):
""" CSSをミニファイ """
data = _cre.css_comment .sub("" , data)
data = _common(data, False)
data = _cre.css_colon .sub(":", data)
data = _cre.css_semicolon.sub("}", data)
return data | a24ff7596991142b24d77d1bf614faf7d9b9509e | 74,813 |
def decrypt_file(session_key, in_path=ENCRYPTED_FILE_PATH, out_path=DECRYPTED_FILE_PATH):
"""
Расшифровывает и сохраняет файл симметричным алгоритмом AES
:param session_key: сессионный ключ симметричного алгоритма
:param in_path: путь к зашифрованному файлу
:param out_path: путь к расшифрованному фа... | 1ced7dc29e3d12d4106e93f93b49daffceed5fa0 | 74,814 |
import json
def get_top_three_titles_json(search_term):
"""
Return a json array of the top three titles from duckduckgo.
Args:
search_term: the term to be searched on duckduckgo
Returns:
A json array containing the top three titles from duckduckgo.
"""
return json.dumps(get_... | b758e4a41ab6195a6ccfb5565ae1d1ae90892016 | 74,815 |
def log_mean_and_std(w):
"""
Given a vector w, returns -log2(mean((1/2)^w)) and
-log2(std((1/2)^w)), uses log_sum_exp to avoid underflow
"""
m = len(w)
mu = np.log2(m) - log_sum_exp(w)
v = np.hstack((2 * w, 2 * mu * np.ones(m), w + mu - 1))
c = np.hstack((np.ones(2 * m), -np.ones(m)))
... | d4d7cccafbc82b748d0dfd80ae43e2af87b3184f | 74,816 |
def get_ST_Efficiency(demand_sector):
"""ST_Efficiency loader function
"""
return get_demand_sector_parameter("ST_Efficiency",
demand_sector) | 2a901ef5a0efda614f3b98b531e033dfd545047b | 74,817 |
def compute_RG(snapshot, atom='CA'):
"""
Radius of gyration...
"""
coords, resis = read_PDB(snapshot, atom)
R_cm = np.mean(coords, axis=0)
dR = coords - R_cm
mag_R = np.sum(dR*dR, axis=1)
RG = np.sqrt(np.mean(mag_R))
return RG | a4d9a8bbda2596517293d00d94ecf7503c6c19bb | 74,820 |
def generate_elevation_profile(line):
"""
Follow the given line along our raster data (which contains the
height), and return an elevation profile based on this data.
This "line following" can be done using the following SQL Common Table
Expression:
.. code-block:: sql
WITH line AS (
... | edd25eb99627b91acf76e14b39e4d525262235ae | 74,821 |
def _get_updated_display_names(attr_name, new_val, old_val):
"""Get difference between old and new display names data"""
new_links = set()
old_links = set()
for val in new_val:
new_links.add(val.get("display_name", ""))
for val in old_val:
old_links.add(val.get("display_name", ""))
return (
at... | 4dc2c6502758822f4ff9d416c13fcf9f925dfd23 | 74,822 |
import yaml
def read_yaml(file_name):
""" Reads a YAML file and returns its content """
try:
with open(file_name, 'r') as fin:
data = yaml.safe_load(fin)
except Exception as e:
app.logger.error("reading file '{}' - {}".format(file_name, str(e)))
raise
else:
... | 34e67b642d06db3a642c5dbb6cd7bd493232f63c | 74,823 |
def get_dnas_analysis(db: Session, skip: int = 0, limit: int = 100):
"""Get all DnaAnalysis stored in the database."""
return db.query(models.DnaAnalysis).offset(skip).limit(limit).all() | 1b317a214f4ba89cb78866cf1781bde7acaa07af | 74,824 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.