content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
def get_lambda_decay(schedule_type: str, decay: float, decay_step: Optional[int] = None):
"""Create learning rate scheduler (different strategies)."""
if schedule_type in ['exponential', 'smooth']:
assert 1.0 >= decay >= 0.9, \
f"A decay factor >1 or <0.9 is no... | cc8fdeb81f4cb0263fe1b84753a4d5e72bfa08b7 | 3,599,541 |
def get_default_permissions(opts):
"""Get default add/change/delete permissions given model._meta.
Args:
opts: model ._meta attribute.
Returns:
tuple of tuples (codename, verbose_name)
for each default permission.
"""
return ((get_permission_codename(action, opts),
... | 906e9b79be3ba4ac6c27105a7351fc979d620590 | 3,599,542 |
def _execute_c2(state, context):
"""REP: Reset status bits.
When used, it will set the bits specified by the 1 byte immediate
value. This is the only means of setting the M and X status
register bits.
"""
state.flags &= ~state.current_operand
return context, None | d9ae38f7b9c3c8caf14e578b29693417f04b8234 | 3,599,543 |
def fetchsoil(mukey):
"""
https://wepp.cloud/webservices/weppsoilbuilder/fetchsoil/100000/
"""
fn = '%s.sol' % mukey
fn_cache = _join(soil_dir, 'cache', fn[:3], fn)
fn_invalid = _join(soil_dir, 'invalid', fn[:3], mukey)
if _exists(fn_cache):
result = open(fn_cache).read()
... | 2ee277d4366c7344ade6bcf3201f706f0fc1488b | 3,599,544 |
def bytes_int(b: bytes) -> int:
"""convert bytes to int"""
return int.from_bytes(bytes=b, byteorder=ENDIAN, signed=SIGNED) | 8740fc90886d812f16a5aff1831d181a6a619a83 | 3,599,545 |
import json
def cognitive_states():
"""
Returns json in format
{
'affect': <predicted affect score>,
'drives': <predicted drives score>,
'load': <predicted cognitive load score>
'percept': <predicted percept score>,
'social': <predicted s... | 672b2c2e04e431626033b6035acf76b19449d8c8 | 3,599,546 |
def loss_function_E_wlco(params, params_const, ts, E_exp,
bins=np.arange(0, 1.1, 0.03), cache=True):
"""Loss function for E histograms and WLC distance distribution with offset
"""
bph = recolor_burstsph_wlco(params, params_const, ts, cache=cache)
return iloss_loglike_E(bph, E_e... | 647ccfe96ae84c7187c1e392a43181515ab4c44e | 3,599,547 |
import requests
def delete_video_summary(self, summaryId):
"""Delete a video summary"""
(endpoint, method) = self.endpoints['delete_video_summary']
endpoint = endpoint.replace(':summaryId', summaryId)
try:
headers = {'Authorization': self.token.authorization_header()}
return requests.request(method,... | 891e9c77b43b0efcbcd60066cff12cc1fda777d8 | 3,599,549 |
import json
def task_update(request, task_id):
"""
update task info
:param request: request object
:param task_id: task id
:return: json
"""
if request.method == 'POST':
task = Task.objects.filter(id=task_id)
data = json.loads(request.body)
data['clients'] = json.du... | a6cff6942c3a443d4f0bd65c7163ad2c6d51e5f8 | 3,599,550 |
def rowcol_to_xy(rows, cols, raster):
"""non-uri version of rowcol_to_xy_uri"""
gt = raster.GetGeoTransform()
X = gt[0] + cols * gt[1] + rows * gt[2]
Y = gt[3] + cols * gt[4] + rows * gt[5]
return (X, Y) | 26ccf8da771387fffdcfc4d5b188aa562fd7be7e | 3,599,551 |
import copy
def validate(spec, data):
"""Validates the data and creates the config objects"""
data = copy.deepcopy(data)
validated_data = {}
def add_validated_section(section, config):
if data.get(section):
validated_data[section] = config.from_dict(data[section])
add_validat... | a39e98c110036c30dafc07a1341972f41aa53aec | 3,599,552 |
from typing import Callable
from typing import Iterable
from typing import Tuple
from typing import List
def solve_eval(
fenics_function: Callable,
fenics_templates: Iterable[FenicsVariable],
*args: np.array,
) -> Tuple[np.array, ufl.Form, Tuple[FenicsVariable], List[fenics.DirichletBC]]:
"""Computes ... | d215df785420a3701d37fad19e7d60633a30ffe4 | 3,599,555 |
def test_call_fuzz():
"""Fuzz some functions."""
return """
fn main() {
{dest} = takes_args(fuzz(), fuzz(), fuzz());
}
fn takes_args(a: u8, b: u1, c: u4) -> u4 {
write_value(&b, 10);
return a + b + c;
}
fn write_value(ptr: *u1, val: u1) {
*ptr = val;
}... | 4291bc625b51715c286ef61ce910fae0257c4852 | 3,599,556 |
def woe_apply(S_data, DF_groups):
"""
Применение группировки и WoE-преобразования
Parameters---------------
S_data : pandas.Series
Значения предиктора
DF_groups : pandas.DataFrame
Данные о группировке предиктора
Returns
---------------
X_woe ... | fdc1ea58c8fbefb7c5b4576a8cf94396943be6dc | 3,599,557 |
def prepare_sonar_gid_data():
"""Prepare GID Sonar data."""
potholes_file = prod_file_base + "pothole_" + prod_file_end
# Read CSV
gid = pd.read_csv(potholes_file)
# Set accepted fields
fields = ['service_request_id', 'date_requested', 'date_updated',
'case_origin', 'service_name... | e2b3d07d1d2b8922125ba6a3f1dac9b9779effd8 | 3,599,558 |
def property_cached(fun=None, pytree_node=False):
"""Decorator to make the method behave as a property but cache the resulting value and
clears it upon replace.
Args:
pytree_node: a leaf node in the pytree representation of this dataclass.
If False this must be hashable
"""
if f... | 90b01dc30c9b53c96349d3ad4521a27f9129ccb3 | 3,599,559 |
def show_vocabulary(word_id: int) -> str:
"""指定したものを表示する"""
slack_msg = "該当する番号は見つからなかったっぽ!"
with VocabularyDatabase() as v_d:
result = v_d.get_word_list()
cnt = 1
for row in result:
_, text = row
if cnt == word_id:
slack_msg = text
cnt += 1
return... | 33206b0fb307d75ffb89c1eaa5b128b9350498c7 | 3,599,560 |
def index():
"""Video streaming home page."""
#FRmodel = faceRecoModel(input_shape=(3, 96, 96))
#FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy'])
#load_weights_from_FaceNet(FRmodel)
return render_template('index.html') | 76c8718b16f62bf1a9a0c5823d4ff704119a579d | 3,599,561 |
import logging
def file_read_auth( gateway, volume ):
"""
Verify whether or not the given gateway (which can be None) is allowed
to read (GET) file metadata from the given volume.
"""
# gateway authentication required?
if volume.need_gateway_auth() and gateway is None:
logging.error( "no ... | 3063525b8c009c85d281e92ef448963bc402b88a | 3,599,562 |
def remove_redundant_characters(str, char1, char2):
"""
remove substrings before and after two characters
exmaple:
input: '12@[123]57'. '[',']'
output: '[123]'
"""
left_index = str.find(char1)
right_index = str.find(char2)
result = str[left_index: (right_index +1)]
return result | 7e7dc284cd1ee4b8709bdc76b6ac864fb0dead8f | 3,599,563 |
def process_fov(field_num: int, experiment_str: str):
"""Process a single field of view of ISS data
Parameters
----------
field_num : int
the field of view to process
experiment_str : int
path of experiment json file
Returns
-------
DecodedSpots :
tabular object ... | eae8c774ba9410c9c1ec0ccf0a9c787b0c484aa9 | 3,599,564 |
def state_changes_during_period(start_time, end_time=None, entity_id=None):
"""
Return states changes during UTC period start_time - end_time.
"""
where = "last_changed=last_updated AND last_changed > ? "
data = [start_time]
if end_time is not None:
where += "AND last_changed < ? "
... | f1086d5cca74fc2f44049ee1dc9d1250f5f047e7 | 3,599,565 |
def double(number):
"""
This function returns twice the value of a given number
"""
return number * 2 | 65a4bb13ecb45b37f0349f4be2f834f2fd23f813 | 3,599,566 |
def fund_nav_df_fillna(fund_nav_df):
"""
为 fund_nav_df 补充nav数据并记录错误日志
:param fund_nav_df:
:return:
"""
fund_nav_df.dropna(subset=['nav'], inplace=True)
fund_nav_df['nav_acc'] = fund_nav_df[['nav', 'nav_acc']].fillna(method='ffill', axis=1)['nav_acc']
return fund_nav_df | b61fdf7986c782a831bb9c97c190e161210ff925 | 3,599,567 |
def run_test_c1_start(server):
"""Tests that a subscriber C1 starts correctly."""
return start_and_check_client(server, "1") | 5e19b3a668826a955ee3398fa586d3b31fdd1111 | 3,599,568 |
def librarianIDExists(accID):
"""
Da li postoji bibliotekar sa datim ID-jem
"""
for _, v in _users.items():
loopAccLevel = v.GetAccessLevel()
if loopAccLevel == 1 and v.getID() == accID:
return True
return False | eb2934cda0b3abafb4202e213c243ecef40eaedc | 3,599,569 |
def find_holes(x):
"""find the beginning and end of continuous None in the given iterator
Args:
x (iterator): the input sequence
Returns:
list of (int, int) indicating the beginning and the end of a continuous None sub-sequence
"""
holes = []
in_hole = False
for idx, val in... | 4d4c91fa28965501018c8c5ea24e2feef6530c1e | 3,599,570 |
def getAllPathsInfo(demands, d_links, g, wt="weight"):
""" Gets info on all the solution paths from the demand-link solution variables
Parameters
----------
demands : dictionary
dictionary of original problem demands. Note that the demand volumes are not used just
the demand pairs.
... | 4c0b6915b05a2996803001c7a91c53dfd90acb18 | 3,599,571 |
def eliminate_duplicates(duplicated_iterable):
"""
对于包含重复元素且基于数组(可以通过下标访问)的可迭代对象,清除其重复元素并保持原顺序不变
@日期: 过去的某个时刻
@作者: 徐嘉辉
Args:
duplicated_iterable: 包含重复元素且基于数组(可以通过下标访问)的可迭代对象
Returns:
返回一个保持了原来元素顺序且去重完毕的列表
"""
return sorted(set(duplicated_iterable), key=duplicated_iterab... | ca86f37050ed6b1830c952bd76f5ac57a76eb149 | 3,599,572 |
def permutate_and_concat_batch_patches(batch_patch_embeddings, perms):
"""Permutates patches from a mini batch according to permutations.
Args:
batch_patch_embeddings: input tensor with shape [n*PATCH_COUNT, h, w, c] or
[n*PATCH_COUNT, c], where PATCH_COUNT is the patch number per image
and n is th... | 5ba1de02791b4dc3cf9c54e55c69d90d6882ddad | 3,599,573 |
def unique_dict_in_list(array):
"""Returns the unique dictionaries in the input list,
preserving the original order. Replaces ``unique_elements_in_list``
because `dict` is not hashable.
Parameters
----------
array: `List` [`dict`]
List of dictionaries.
Returns
-------
uniqu... | ef18d64c4a896321d57f984c0ede3e0e897c59f5 | 3,599,574 |
def update_weights_2(x_sample,
y_target_sample,
F_weights,F_weights_2,
G_weights,G_weights_2,
omega,omega_2,
thresholds,thresholds_2,
buffer_bins,
dt,
leak,
... | 0172287ad3b30ddf24c783d52bdfb55ee7a496a7 | 3,599,575 |
def zangle_to_quat(zangle):
"""
:param zangle in rad
:return: quaternion
"""
return quat_mul(quat_create(np.array([0, 1., 0]), np.pi/2),
quat_create(np.array([-1., 0, 0]), zangle)) | bb2c6cfd8bc2f68d4355079370fcf943aff9b26e | 3,599,576 |
def merge(prevArtifacts, nextArtifacts):
"""Merge artifact lists with nextArtifacts masking prevArtifacts"""
artifactList = list(nextArtifacts.copy())
artifactList.extend(prevArtifacts)
merged = []
excludedNames = set()
for artifact in artifactList:
if artifact.name not in excludedName... | 089aaf140111b08a98e64118fde8f8a4fd413982 | 3,599,578 |
def update(isamAppliance, name, description=None, authenticateCallbacks=None, signInCallbacks=None,
localIdCallbacks=None, signOutCallbacks=None, authnPolicyCallbacks=None, check_mode=False, force=False):
"""
Update a specific point of contact profile
"""
update_required, poc_id = _check(isam... | c802a182218bdd6bb3d9ef13084e5318cdad5d51 | 3,599,579 |
def handler403(request):
"""
custom 403 view
:param request:
:return:
"""
return permission_denied(request, Exception(), template_name='base/403.html') | c540c03f18d20ab5b516aa8d8f569a124ca53f93 | 3,599,580 |
def get_random_state(random_state=None):
"""Return a Mersenne Twister pseudo-random number generator.
Parameters
----------
seed : integer or ``numpy.random.RandomState``, optional, default ``None``
Returns
-------
random_state : mtrand.RandomState object
"""
if not random_state:
... | b73333a4e95e105d3c118556822a232a155feddb | 3,599,582 |
def fill_gaps(current_time: int, lookback: int, resolution: str) -> set:
"""
This function will fill time-series gaps. For example, if a second
resolution metric has no data values for three seconds during a
period of time, the value will be filled zero.
This helps make the data more palatable ... | 2546ff71525a9e00eac921c20a4d535a3f6353d3 | 3,599,583 |
def stencil_residual(pp_image, hp_nn, y):
"""Objective function."""
avg_weight = 0.5 ** 0.5 * 1 / len(y.reshape(-1)) ** 0.5
r1 = pp_image[None,:,:,:] - y[None,:,:,:]
r2 = net_apply(hp_nn,pp_image[None,:,:,:])
out = jnp.concatenate((r1.reshape(-1),r2.reshape(-1)),axis=0)
return avg_weight * out | bbfbf992c3e5349fff05d91983b4b818dd502809 | 3,599,585 |
def is_datetime(val: str, tzone=None):
"""Check if a string is datetime, return the datetime if yes"""
try:
# default time zone
if tzone is None:
tzone = UTC
else:
tzone = gettz(tzone)
dt = parse_dt(val)
dt = dt.replace(tzinfo=tzone)
ret... | be4fc5f337b4eb41be80091b9bb449f653fe067d | 3,599,587 |
def get_city_lat_long(request):
"""
City code based on ISO 3166-1 (http://en.wikipedia.org/wiki/ISO_3166-1)
:param request: Request Object
:return: ISO Code of the City
"""
if 'X-AppEngine-City' in request.headers:
return request.headers['X-AppEngine-CityLatLong']
return None | 35310e397489b9a80a90eeb2cff952566ba22f91 | 3,599,588 |
def compare_events(df, wf=1):
"""
compare_events compares anomalous events that are technician labeled and machine detected.
Labeled and detected data may have been widened to increase the window of overlap.
Arguments:
wf: integer widening factor used when generating events
df: data fram... | 50646e80426487678b0d04461306f8704b945ac7 | 3,599,589 |
def get_signature_genes(input_path, sig_genes_complete, var_cutoff=0.1):
"""
Get overlap between signature genes and available genes
:param input_path:
:param sig_genes_complete:
:return: new sig_genes
"""
data = pd.read_table(input_path, index_col=0)
keep = data.var(axis=1) > var_cutoff... | d8de309a122944e55bcf3ea9c4a39fc8af0eef34 | 3,599,590 |
def create_quart_app(name, static_url_path="", static_folder=""):
"""创建 quart app,并注入 middleware"""
global PASSTHROUGH_HTTP_ERROR
PASSTHROUGH_HTTP_ERROR = Global.config.get("common.http.passthrough_http_error")
app = Quart(name, static_folder=static_folder, static_url_path=static_url_path)
app.regi... | fa7062df48f43260baabf340751c03f5018d19b9 | 3,599,591 |
from bcbio.structural import cnvkit
def run(vrn_info, cnvs_by_name, somatic_info):
"""Run THetA analysis given output from CNV caller on a tumor/normal pair.
"""
cmd = _get_cmd("RunTHeTA.py")
if not cmd:
logger.info("THetA scripts not found in current PATH. Skipping.")
else:
work_d... | 56976654b04ca5ea28ef1c1b9d225fcfe9419f7b | 3,599,592 |
import math
def gen_new_patches(swatches_XYZ_old, metric='L*VAC'):
"""
colors match the l*VAC instead or l*
"""
targets = {}
steps = {}
abs_tols = {}
functions = {}
targets['L*VAC'] = 47
steps['L*VAC'] = 0.0001
abs_tols['L*VAC'] = 0.01
functions['L*VAC'] = c.lightness_hk_xy... | 487b775919e30d1aed778a2b2a7b58d0b0844904 | 3,599,594 |
from typing import Any
import sympy
import numbers
def is_parameterized(val: Any) -> bool:
"""Returns whether the object is parameterized with any Symbols.
A value is parameterized when it has an `_is_parameterized_` method and
that method returns a truthy value, or if the value is an instance of
sym... | 4c8764bab58473a9d66c7dd47fad000449d4a14c | 3,599,595 |
from typing import Any
def resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
"""
ResNet-18 model from "Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>_.
Args:
pretrained: If True, returns a model pre-trained on ImageNet
... | 0616f01454a3734d5e3889cab08cc548c8760304 | 3,599,596 |
from datetime import datetime
def get_trials_meta(filename):
""" Take a filename and extract time_iso and block information from it.
:param filename: file name of trials table of form trials-[time_iso]-Block_[n].csv
:type filename: str
:return: time_iso and block as namedtuple
:rtype: tuple
... | 64f4cf93650440b5e7ed4826a1f72b8ccfc8cd98 | 3,599,597 |
def parse_checksum(header: str) -> str:
"""
Parse the Checksum header (eg. from the email epilogue)
"""
# Epilogue example:
# "Checksum: e231f8e724890aca477ca5efdfc7bc9c31e1da124510b4f420ebcf9c2d1fbe74\r\n"
msg = HeaderParser().parsestr(header)
return msg["Checksum"] | 81c62822f0e0e3e30b24daf8b33f86cfab3dec28 | 3,599,599 |
def Bool(name, ctx=None):
"""Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
>>> p = Bool('p')
>>> q = Bool('q')
>>> And(p, q)
And(p, q)
"""
ctx = _get_ctx(ctx)
return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) | 8da9cf5376be9ba7250ffc10cd030bb57e0006a2 | 3,599,600 |
def partial_dMF(x, mf_definition, partial_parameter, func):
"""Calculates the partial derivative of a membership function at a point x."""
mf_name = func.__name__
if mf_name == 'gaussmf':
sigma = mf_definition['sigma']
mean = mf_definition['mean']
if partial_parameter == 'sigma':... | a72dbc2e3a56f647e7c2ee8ac9b23238793a13a1 | 3,599,602 |
def get_event_list_current_file(df, fname):
"""
Get list of events for a given filename
:param df: pd.DataFrame, the dataframe to search on
:param fname: the filename to extract the value from the dataframe
:return: list of events (dictionaries) for the given filename
"""
event_file = df[df[... | 98ba12dcff1854a1cf333cbcf40f6cbd2d273146 | 3,599,603 |
def build(package, version_query=None, namespace="default", variables={}, shards=None,
endpoint=DEFAULT_ENDPOINT):
"""
A build is the construction/expansion of a package.
The result are the expanded/ready to use resources, including every dependencies.
Args:
package (:obj:`str`): packag... | 551d21186af16edde22333ff8039d9f740baf74b | 3,599,604 |
def circularArrayLoop( nums):
"""
:type nums: List[int]
:rtype: bool
"""
def move(i):
res = (i+nums[i])%len(nums)
return res
slow = move(0)
fast = move(slow)
while slow != fast:
slow = move(slow)
fast = move(move(fast))
fast = move(slow)
if fast ==... | bb25883c698abd0b7d9183799e9c4c866d342409 | 3,599,606 |
def _clean_str(value, strip_whitespace=True):
"""
Remove null values and whitespace, return a str
This fn is used in two places: in SACTrace.read, to sanitize strings for
SACTrace, and in sac_to_obspy_header, to sanitize strings for making a
Trace that the user may have manually added.
"""
... | 41b9f0a1388045b86d019464512a0253eb5d6523 | 3,599,608 |
def status():
"""获取所有通道流状态"""
lst = []
for k in _ff2rtmp:
dic = {'id': k, 'status': _ff2rtmp[k].getMediaStatus()}
lst.append(dic)
return response.make_response_success_data(lst) | 04124b6c6698f73ab1e6087addb764e346c87d09 | 3,599,609 |
import random
def createRandomGraph():
"""Creates a digraph with 7 randomly chosen integer nodes from 0 to 9 and
randomly chosen directed edges (between 10 and 20 edges)
"""
g = {}
n = random.sample([0,1,2,3,4,5,6,7,8,9], 7)
for i in n:
g[i] = []
edges = random.randint(10,20)
c... | e2ca213a594ad03c5df7a3231e7d246fe7fcb416 | 3,599,610 |
def gaussAve(t,y,std=.01):
"""
Does an average in y with weights based on distances to all other points in t.
"""
assert len(y) == len(t)
n = len(t)
dists = (t.reshape(n,1) - t.reshape(1,n))
dists[dists> .5] -= 1
dists[dists<-.5] += 1
w = np.exp(-.5*dists**2/std**2)
return np.sum... | efa75dc342b2c5e1fa2f797f87e12eaf2c080c74 | 3,599,611 |
import ctypes
def task_2_1(id_object, id_nodes, filename_graph=FILENAME_GRAPH):
""" Searching tree shortest distances with minimal weight to selected nodes
from selected object of infrastructure
Arguments
:param id_object: int
* Id object of infrastructure - SELECTED
... | 7f657c5c6e12320dabb0c2570c2d1dcc00c4be49 | 3,599,612 |
import json
def read_json(filepath, intkeys=True, intvalues=True):
""" read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads()
>>> js = read_json('wsj_pugnlp.detector_morse.Detector.json.gz', intvalues=False)
>>> list(js.keys())
['py/object', 'classifier', 'nocase']
... | 2c0cc3a18a41b55007f232727c2c9ceacaee87eb | 3,599,613 |
import math
def displace_on_a_sphere(point, radius=0.0):
"""
Masked points are placed on a random location on a sphere around the
original location. Masked points are not placed inside the sphere itself.
If we define a coordinate like ...
>>> coordinate = Point(0.0, 0.0, 0.0)
... and c... | e5245176299782203024afdaadf6f7d87e667adf | 3,599,614 |
def ini_elec_levels(spc_dct_i, spc_info):
""" get initial elec levels
"""
if 'elec_levels' in spc_dct_i:
elec_levels = spc_dct_i['elec_levels']
else:
elec_levels = [[0., spc_info[2]]]
return elec_levels | 95a55a90c95466b2288799e4e24b3250c3afdd84 | 3,599,615 |
def check_for_factor(base, factor):
"""
This function should test if the
factor is a factor of base.
Factors are numbers you can multiply
together to get another number.
Return true if it is a factor or
false if it is not.
:param base:
:param factor:
:return:
"""
retur... | 6d20a7d2e2ec459e8307007adb332507d0078118 | 3,599,616 |
def has_user_run_commands() -> bool:
"""has_user_run_commands() -> bool
(internal)
"""
return bool() | ed564eafe9c004ed8e524aaf34b108a2994fab11 | 3,599,617 |
def IntersectionMatrixColorMap(matrix_data):
"""
Function to plot and save a colormap for visualisation of intersection
matrix
Parameter
--------
matrix_data: list of lists, a square matrix of interstions
Returns: None
"""
# set figure size
fig = plt.figure(figsize=(12, 12))
... | 7fa2277c10ade79af22b2fa8b482962b13a93ce7 | 3,599,618 |
def has_access(user, users):
"""A list of users should look as follows: ['!deny', 'user1',
'user2'] This means that user1 and user2 have deny access. If we
have something longer such as ['!deny', 'user1', '!allow',
'user2'] then user2 has access but user1 does not have access. If
no keywords are fou... | 07d3f47cf3725002023d8c9e487e14280dabc2bf | 3,599,619 |
def log_suppress_or_reraise(*exceptions, logger=None, prelog=None, **kwargs):
"""Context manager or decorator - logs, raises and can suppress exceptions.
Convenince function to support older implementation.
"""
return LogSuppressOrReraise(*exceptions, logger=logger, prelog=prelog, **kwargs) | f9ac1c021ccf1d6e9807b8faae4a19b3dac4c1d2 | 3,599,620 |
def foo_endpoint():
""" just some endpoint """
logger = getLogger("foo_endpoint")
logger.extra["some_extra"] = "1"
logger.info("some message logged in foo_endpoint")
return flask.jsonify({'bar': "BAR"}) | 44c8f33dadc4640b205ed39b9228da0a4698b6de | 3,599,622 |
def check_absolute_continuity_policies_strict(P: np.ndarray, pi: np.ndarray, phi: np.ndarray) -> bool:
""" Strict check of absolute continuity of two policies given an environment
Used when computing bar I. Assume pi is deterministic, of dimension SxA
"""
dim_state, dim_action = P.shape[0], P.shape[... | 2022c9d899fc9411c799e9bfa3bc6fdbc543070e | 3,599,623 |
def calc_M_by_M0(t, t0, M0, period):
"""
Computes the mean anomaly as a function of a t, a mean anomaly (M0) at time t0
and the period.
Args:
t : time of the computation
t0: a point in time where Mean anomaly is knwon
M0: the mean anomaly in radians at t0
period : peri... | 980dbcf9fa9cdb6e52904884aca2e5f39e8b166b | 3,599,624 |
from datetime import datetime
def timekeeper_prop(dt: datetime = None, state: str = 'init', enabled: int = 1, round_counter: int = 1, test_mode: bool = True, view_score_mode: bool = True, log_to_datastore: bool = False) -> dict:
"""
property of timekeeper (kind: 'clock')
Parameters
----------
... | 6b5b132404686809f5601f2a84eb46ad6f94e774 | 3,599,625 |
def _default_initializer(name, shape, dtype):
"""The default initializer for variables."""
# pylint: disable=protected-access
store = variable_scope._get_default_variable_store()
initializer = store._get_default_initializer(name, shape=shape, dtype=dtype)
# pylint: enable=protected-access
return initializer... | e2530ab30ac2419e333e49de7c9a1ef2af93d6b9 | 3,599,626 |
def batchnorm_backward_alt(dout, cache):
"""
可选的BN反向传播
"""
dx, dgamma, dbeta = None, None, None
mu, xmu, carre, var, sqrtvar, invvar, va2, va3, gamma, beta, x, bn_param = cache
eps = bn_param.get('eps', 1e-5)
N, D = dout.shape
dbeta = np.sum(dout, axis=0)
dgamma = np.sum((x - mu) * (... | 8844619f87f2237b0b3e796cdf2041b86de67fa1 | 3,599,627 |
def midpnt(img):
""" compute the midpoint pixel of an image
The pixel coordinates in dimension (``dim``) are computed as
:if ``dim`` is odd: ``(dim - 1)/2``
:if ``dim`` is even: ``dim/2``
:param img: pattern
:return: midpoint pixel in image coordinates
"""
shape = np.asarray(i... | 4c4bcf046fbb6a20c07a3dfde647088fe6424382 | 3,599,628 |
def simulate_ens(setup,N=1,desc='Simul',squeeze=True):
"""Generate a simulation on a ensemble (default=1)
if squeeze is True and N==1, the output is squeeze on the ens dim"""
f,h,chrono,X0 = setup.f, setup.h, setup.t, setup.X0
# Init
xx = zeros((chrono.K+1,N,f.m))
xx[0] = X0.sample(N)
#Loop
for k,k... | 5c3a75fe47588d362d18fd7f8863e119121b257d | 3,599,629 |
def run_and_verify_svnlook2(expected_stdout, expected_stderr,
expected_exit, *varargs):
"""Run svnlook command and check its output and exit code."""
exit_code, out, err = main.run_svnlook(*varargs)
verify.verify_outputs("Unexpected output", out, err,
expected_... | e7d66edf5afea9e652aea462f50616c578a3e8a1 | 3,599,630 |
from typing import List
def compute_binned_conditional_probability(joint_distribution: np.array,
target_idx: int,
non_bin_idx: List,
bin_idx: List,
... | 16dbe8e645307440a395f7219aafc5d3e140d07c | 3,599,631 |
import re
def _get_variant_num(file_path):
# type: (str) -> int
"""Returns the number of variants for a file.
It assumes the file name suffix has the count.
Raises:
ValueError: if the file name is not formatted as `count_[COUNT]`.
"""
_, file_name = filesystems.FileSystems.split(file_path)
if not ... | caf77160bc96ae7c31b683953bfc92d6028f58a1 | 3,599,632 |
from keras.models import Sequential
from keras.layers import Dense
def tail_model(nb_feature):
"""
tail model has the structure 600,300,150,60 nodes
:param nb_feature:
:return:
"""
# construct the model
model = Sequential()
model.add(Dense(600, input_dim=nb_feature, activation='relu'... | 51e5a15dcf3a704a3c3b5a037f0d467b32a6c7c3 | 3,599,633 |
def return_json_response():
"""Return json response sample"""
return jsonify({'this is': 'sample'}) | 761599587948de2907b9cf2eff0496b7800101ae | 3,599,634 |
def is_user_in_group(user, group):
"""
Check whether the user belongs to the group
Args:
user(str): user name/id
group(class:Group): group to check user membership against
Returns:
- True if user is in the group, False otherwise
"""
if isinstance(group, Group) == Fals... | 2015739c8bdb53509258f936a7a96ae9e511ad29 | 3,599,635 |
def _generate_variable_state(batch_size_tensor, state_size, dtype):
"""Generate a variable tensor with shape [batch_size, state_size]."""
def create_variable(unnested_state_size):
flat_dims = tensor_shape.as_shape(unnested_state_size).as_list()
init_state_size = [batch_size_tensor] + flat_dims
return tf... | 0cbae443fdc7220c7a80e14614315f7b43b8e080 | 3,599,636 |
def by_cities(sdat):
"""
this function determines from how often people fly from every city
:return: int[from moscow; from st pet.]
"""
borm = sdat.groupby(["Город вылета"]).size()
cities = []
for i in borm:
cities.append(i)
return cities | d5e438ea7f9d298ff879df479f250342cc02eff1 | 3,599,637 |
def base() -> str:
""" Handles redirection to other pages.
:return: A redirect to the upload page.
"""
return redirect("upload") | 54a58ba00ff10143cb25e93975e9804956a1554e | 3,599,638 |
def drop_points(surf, array, low=-np.inf, upp=np.inf):
"""Remove surface points whose values fall within the threshold.
Cells corresponding to these points are also removed.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
array : str or 1D ndarray
Array us... | 06ae20616ef8a4c0c5072c90ce70be98f83e3c9d | 3,599,639 |
def isVowel(letter):
"""
isVowel checks whether a given letter is a vowel. For purposes of this
function, treat y as always a vowel, w never as a vowel.
letter should be a string containing a single letter
return "error" if the value of the parameter is not a single letter string,
return True, if the... | 5ba6917c80c4679a59580b8f3a05513d0904cd63 | 3,599,641 |
def d_xi(beta, K):
"""
First derivative of xi(beta).
xi(beta) is the entropy of the system when no data has been observed.
d_xi is the prior for the nsb estimator
"""
return K * mp.psi(1, K * beta + 1.) - mp.psi(1, beta + 1.) | 13cdd16d55536eeeaa03e060c70b27636d7fd08d | 3,599,642 |
def fn_winkler(weight_jaro, pre_matches, pre_scale):
"""
Scale the standard Jaro metric by 'pre_scale' units per 'pre_matches'.
Note the warning in the docstring of jaro_winkler() regarding the scale.
"""
weight_jaro += pre_matches * pre_scale * (1.0 - weight_jaro)
assert weight_jaro <= 1.0
... | c938b932038e5344c19847555b70545d239cbb5a | 3,599,643 |
from typing import Dict
from typing import Tuple
from typing import Set
from textwrap import dedent
def get_reactome(*, client: Neo4jClient) -> Dict[Tuple[str, str], Set[str]]:
"""Get Reactome gene sets.
Parameters
----------
client :
The Neo4j client.
Returns
-------
:
A... | d517ac558d274dec5b4583bfd6f75ce3420fb7e5 | 3,599,644 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | e33117eb687077b4fd5970a7d007838e0b0fc58f | 3,599,645 |
def as_rest_table(data, full=False):
"""
Originally from ActiveState recipes, copy/pasted from GitHub
where it is listed with an MIT license.
https://github.com/ActiveState/code/tree/master/recipes/Python/579054_Generate_Sphinx_table
"""
data = data if data else [["No Data"]]
table = []
... | 587bfb75d241baa41662e130535828834fb7d62c | 3,599,646 |
def isCCW(ring):
"""
Determines if a LinearRing is oriented counter-clockwise or not
"""
area = 0.0
for i in range(0,len(ring)-1):
p1 = ring[i]
p2 = ring[i+1]
area += (p1[1] * p2[0]) - (p1[0] * p2[1])
if area > 0:
return False
else:
return True | ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f | 3,599,647 |
from typing import Callable
def check(predicate: Callable) -> Callable:
"""A decorator to add a check to a server command
Args:
predicate: The check that should be run
Returns:
A decorator function that will add the check to the command
"""
def decorator(cmd: ServerCommand):
... | 3201bc9da236be87ecfa0cb40fdc400973a4dda0 | 3,599,648 |
def visualization_grid(subplot_function, pass_ax_or_grid="ax", *args, **kwargs):
"""Decorator to create a grid for graphs and plot on it.
Graphs will be printed by the subplot function to which the decorator is applied.
Parameters
----------
pass_ax_or_grid: str
Either 'ax' or 'grid'.
... | 5f5398146bb2acbb15a6c1221fd8989366a42c8e | 3,599,649 |
import socket
import pickle
def recv_frame(sock, timeout=None):
"""
Receive a frame from the socket.
Reads the size of frame first followed by the actual data.
frame is then de-serialized and returned as an instance
of class frame.
Arguments
----------
sock :- The socket to read fr... | 407a68abcab300ce98fe51502d2e4ce7f5199286 | 3,599,650 |
def draw_framelinered(frame,height,width): #Better to pass Color parameter
"""
Draw alert red frame on video
"""
# Draw line top left and right
cv2.line(frame, (0, 0), (0,int(height/10)), (0,0,255),10)
cv2.line(frame, (0, 0), (int(height/10),0), (0,0,255),10)
cv2.line(frame, (width, 0), (wid... | c153561adf6f8e8497d27846cecca3aac9624a19 | 3,599,651 |
def get_grant_key(grant_statement):
"""
Create the key from the grant statement.
The key will be used as the dictionnary key.
:param grant_statement: The grant statement
:return: The key
"""
splitted_statement = grant_statement.split()
grant_privilege = splitted_statement[1]
if "."... | 200b77d0988090628e013463bba5fe395dd76c00 | 3,599,652 |
def get_scenes_from_cuts(cut_list, base_timecode, num_frames, start_frame=0):
# type: List[FrameTimecode], FrameTimecode, Union[int, FrameTimecode],
# Optional[Union[int, FrameTimecode]] -> List[Tuple[FrameTimecode, FrameTimecode]]
""" Returns a list of tuples of start/end FrameTimecodes for each scen... | cacb394cc5061e60891d6f50948ca8a8c16fc427 | 3,599,653 |
def openfield_pv_merra_ryberg2019(placements, merra_path, global_solar_atlas_ghi_path, module="WINAICO WSx-240P6", elev=300, tracking="fixed", inverter=None, inverter_kwargs={}, tracking_args={}, output_netcdf_path=None, output_variables=None):
"""
openfield_pv_merra_ryberg2019(placements, merra_path, global_s... | 18ac4ea1a1da8dc6632cacacfb17345b26e837f7 | 3,599,654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.