content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
blue (int... | f86466a13cd028380d3c8bf8aee4b877a1284c59 | 3,602,000 |
async def filter_repositories(
client, headers, account_id, date_from, date_to, exclude_inactive, repos, timezone,
):
"""Filter repositories according to the provided filter paramaters."""
url = "https://api.athenian.co/v1/filter/repositories"
params = {
"account": int(account_id),
"date... | 1d53a6ab36007b90adf3f1bf583b422994cfaf6f | 3,602,001 |
import os
def sc_build():
"""Initialize a sc_build dataframe."""
datadir = os.path.join(os.path.dirname(__file__), 'data/')
fn = os.path.join(
datadir,
'reV_sc/wtk_coe_2017_cem_v3_wind_conus_multiyear_colorado.csv')
rev_sc = pd.read_csv(fn)
fn = os.path.join(
datadir,
... | ef8d5061dc7cea7b4ff88b51c4cf1e0ac39ff1ed | 3,602,002 |
def latest_posts(count=10):
"""
A way to get latest posts from inside a template
"""
return Post.objects.all()[:count] | f0eef0b303b665de4297dc5c6583e56b68798017 | 3,602,003 |
def DispersionBulge(**kwargs):
"""
Create a model of a dispersion-dominated bulge.
This will create a dispersion-dominated bulge model from the stored
parameters specified in kwargs. The bulge model is described in detail
in the online documentation and uses and limitations to this model are
di... | 72cb6899a664904ecd90ec9b3d88864e3b6c1baa | 3,602,004 |
def powerlaw_cl(p, x):
"""
p are parameters of the model
"""
norm_corr = x * (x + 1.) /2./np.pi *1.e12
res = np.zeros(len(x))
res[x!=0.] = powerlaw_dl(p, x[x!=0.]) / norm_corr[x!=0.]
return res | c3a87774f9c23228b4fbfd9ad479639090058b63 | 3,602,005 |
def get_dataset_location(bq):
"""Parse payload for dataset location"""
# Default BQ location to EU, as that's where we prefer our datasets
location = "EU"
# ... but the payload knows best
if "location" in bq:
location = bq["location"]
return location | 071a5258a72b3a3a248c6e44b99b7ccc2890d3f5 | 3,602,006 |
def show_window(window, **kwargs):
"""Create a Qt window in Python, or interactively in IPython with Qt GUI
event loop integration:
# in ~/.ipython/ipython_config.py
c.TerminalIPythonApp.gui = 'qt'
c.TerminalIPythonApp.pylab = 'qt'
See also:
http://ipython.org/ipyth... | 49407e3b1e0f3aa1911f9c2f5bf9ebfc82cf912e | 3,602,007 |
import google
def create_google_blueprint():
"""
Google use default config variables
GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET
https://developers.google.com/identity/protocols/oauth2/scopes#google-sign-in
https://flask-dance.readthedocs.io/en/latest/providers.html#module-flask_dance.co... | 440da490014f3955f68e10b67e19cb8a1d669190 | 3,602,008 |
def state(c:Config)->State:
""" State constructor """
return (c,Program()) | b6482deb2d1a1d2955b00ba9900fa9ea9292c1b9 | 3,602,009 |
def analyze(x: np.ndarray, param: np.ndarray = [1, 1], m: int = 8):
"""预测第1到第m-1经络的结果,也就是C1-Cm-1,暂时先无视C0
流程:filter滤波原始数据 -> findTroughs找谷底索引 -> compute根据谷底索引对每单个周期计算平均幅值等统计量
-> selectRatio根据测试者参数选择标准幅值比例 -> match根据标准幅值比例进行拟合
-> 对比拟合后的数据幅值比例和标准幅值比例
参数:
x:数据
... | e495d6e1699ae5543b227c94780e99bbf1dde7b3 | 3,602,010 |
def get_fws_and_tasks(workflow, fw_name_constraint=None, task_name_constraint=None):
"""
Helper method: given a workflow, returns back the fw_ids and task_ids that match name
constraints. Used in developing multiple powerups.
Args:
workflow (Workflow): Workflow
fw_name_constraint (str):... | 28f4f2cdcc58b942ee3e0631c21bf2a3a052db35 | 3,602,011 |
def undistort_image(config, image, cam_name):
"""copied from https://www.a2d2.audi/a2d2/en/tutorial.html"""
if cam_name in ['front_left', 'front_center',
'front_right', 'side_left',
'side_right', 'rear_center']:
# get parameters from config file
intr_mat_u... | 04f181164415f76251dbc640cba68e2707315e13 | 3,602,012 |
def get_fields_limit(request):
"""
returns possible all fields.
'limit=5000' will limit the number of
field for enumerations to the 5000 first.
"""
try:
limit = int(request.matchdict['limit'])
except Exception as e:
us.JSONResponse(errors = ["limit must be a valid integer"])
... | abfcf6d7c17a4f2c9b19e5929fb9d43e5edda7c6 | 3,602,013 |
def _get_tags(ws_info):
"""Get the tags relevant to search from the ws_info metadata"""
metadata = ws_info[-1]
if metadata.get('searchtags'):
if isinstance(metadata['searchtags'], list):
return metadata['searchtags']
else:
return [metadata['searchtags']]
else:
... | f6922f92913446284545aa73cb2b8cd7139749e8 | 3,602,014 |
import sys
def ArgParse(argparser):
"""Prep argument parser."""
logger.debug(lineno() + ': ArgParse()')
# -a ACTION
argparser.add_argument(
'-a', '--action', default='list',
help='''delete, rename, export, list, locate
-a rename: requires a TSV input file with OLDNAME\\tNEWNAME
-a list... | 77e385efb57f1348d34ed4e878b7730fd7164fcb | 3,602,015 |
import os
def get_google_sheet():
""" BOT AUTHENTICATION AND AUTHORIZATION NEEDED:
for gspread api: https://gspread.readthedocs.io/en/latest/
API DOCUMENTATIONS AND RESTRICTIONS LIMITS:
restrictions:
Sheets API v4 introduced Usage Limits as of this writing:
... | b256a944a72d355615ce27b9ef6201d6398e952b | 3,602,016 |
def benchmark_prices(all_prices, benchmark_path='../docs/benchmarks.csv'):
"""
Function to create a column with benchmark close price
"""
# Create list of benchmark symbols
benchmarks = pd.read_csv('../docs/benchmarks.csv')
benchmarks = benchmarks[['symbol', 'description']]
benchmarks_list =... | a38e7c7e13dfcc3dada9568118bc099ab5d18854 | 3,602,017 |
def parse_hexblob(blob: str) -> bytes:
"""
Binary conversions from hexstring are handled by bytes(hstr2bin()).
:param blob:
:return:
"""
return bytes(hstr2bin(blob)) | 9113ff240bb2f896f18448c11fc04ee8dd226a73 | 3,602,018 |
def regex_select(env=None, app=None, request=None):
"""
Selects a set of regex rewrite params for the current request
"""
if app:
THREAD_LOCAL.routes = params_apps.get(app, params)
elif env and params.routes_app:
if routers:
map_url_in(request, env, app=True)
else... | 095f4f0755ae78161262254ea2444f2cddd91832 | 3,602,019 |
import inspect
import sys
def get_module_classes(module_name):
""" Get all the classes from a module """
clsmembers = inspect.getmembers(sys.modules[module_name], inspect.isclass)
return clsmembers | 8049c8a5c0277c86e8c334c4e158eaa90aaa0992 | 3,602,020 |
def load_pandas():
"""
Load the strikes data and return a Dataset class instance.
Returns
-------
Dataset
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
return du.process_pandas(data, endog_idx=0) | d42b28d9eaf50a0ddc093635fc979876d91a635f | 3,602,021 |
def mockingjay_100hr(refresh=False, *args, **kwargs):
"""
The mockingjay base model on 100hr
refresh (bool): whether to download ckpt/config again if existed
"""
return mockingjay_logMelBase_T_AdamW_b32_200k_100hr(refresh=refresh, *args, **kwargs) | 0f912523a5b794d1ffe75d59c8d32a442d8c6a7e | 3,602,022 |
import logging
def show_metadata_probe(pad, info, user_data):
"""Buffer probe to show metadata in a buffer"""
gst_buffer = info.get_buffer()
if gst_buffer:
logging.info("show_metadata_probe: %20s:%-8s: pts=%23s, dts=%23s, duration=%23s, size=%8d" % (
pad.get_parent_element().name,
... | d64b1dc89f0a9a50a7d576100ca4a2b060ce7e04 | 3,602,023 |
def read_structure_annotation(fn_ann, fn_ann_color='', Fs=1, remove_digits=False, index=False):
"""Read and convert structure annotation and colors
Notebook: C4/C4S1_MusicStructureGeneral.ipynb
Args:
fn_ann: path and filename for structure annotions
fn_ann_color: filename used to identify ... | 100c41e33d497cf028492c2d69ddf5b701deff07 | 3,602,024 |
import json
def getCoordinates():
"""Get geometry data from JavaScript and proccess it
"""
# get the data send by JavaScript
jsdata = request.form['boundingbox']
# check if retrieved data is from viweport button or from draw button
if "type" in json.loads(jsdata).keys():
jsonData = js... | e5d027bac8824ff81acd3ddce7fa49af77a8d42a | 3,602,025 |
def retrieve_player_list(gameWindow, gameBoard, gameDebugger=None):
"""
:param gameWindow:
:param gameBoard:
:return:
"""
players = []
while not players or len(players) != 8:
img = gameWindow.captureWindow()
players = parser.parse_players(board.crop_players(img, gameBoard), ... | d4f5d479cc4a09154951151e4eb5b59a3ce3182e | 3,602,026 |
def _str_bool(v):
"""convert a string rep of yes or true to a boolean True, all else to False"""
if (type(v) is str and v.lower() in ['yes', 'true']) or \
(type(v) is bool and bool(v)):
return True
return False | ba4663c402b94b00edb4b1a97a4ba4ed755caf85 | 3,602,027 |
from sys import implementation
def aiida_from_backend_entity(backend_entity):
"""Convert from a backend entity type to an AiiDA frontend entity"""
if isinstance(backend_entity, implementation.BackendComputer):
return Computer.from_backend_entity(backend_entity)
if isinstance(backend_entity, implem... | 05032851b4b7029a6585bc05654596c0d9d89d8a | 3,602,028 |
import json
import base64
def json_safe(string, content_type='application/octet-stream'):
"""Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Bas... | c47c3faf0aeb95902f4a72732c8fb861950c2af0 | 3,602,029 |
def show_main(path=MAIN_CF):
"""
Return a dict of active config values. This does not include comments,
spacing or order. Bear in mind that order is functionally important in the
main.cf file, since keys can be referred to as variables. This means that
the data returned from this function should not... | a70b7800fd406a98acf93294ea902cb583cf6cec | 3,602,030 |
def get_fixed_params():
""" Parameters that currently cannot be searched during HPO """
fixed_params = {'batch_size': 512, # The size of example chunks to predict on.
'n_cont_embeddings': 0, # How many continuous feature embeddings to use.
'norm_class_name': 'LayerNorm', ... | 186e786f96f2a81c88423fdcd27bf28aef97b511 | 3,602,031 |
def _checkpoint_is_greater(a, b):
# type: (Checkpoint, Checkpoint) -> bool
"""Ensure elements of checkpoint 'a' are all greater than or equal to those in
checkpoint 'b'."""
return a.checkpoint >= b.checkpoint and a.checkpoint_time >= b.checkpoint_time | dca9c83e1cf8d2e22e6d763fd02b526bcbaed414 | 3,602,032 |
def to_env_dict(config):
"""Convert configuration object to a flat dictionary."""
entries = {}
if config.has_value():
return {config.__to_env_var__(): config.node['value']}
if config.has_default():
return {config.__to_env_var__(): config.node['default']}
for k in config.node:
... | 4c46f365e7b53d79d25dea7d062f9d985d30877d | 3,602,033 |
def ensure_pil(im):
"""Lazily force image type to PIL.Image
"""
return np2pil(im) if is_np(im) else im | 0e1a58e6e320819044444af71d355dfda639a670 | 3,602,034 |
import os
import msgpack
def get_or_build(path, build_fn, *args, **kwargs):
"""
从序列化的形式加载或建立一个对象,保存内置的目的。
剩余的参数被提供给`build_fn`。
"""
save = False
obj = None
if path is not None and os.path.isfile(path):
with open(path, 'rb') as obj_f:
obj = msgpack.load(obj_f, use_list=... | f68fd0149b917a08fb9e9ddde78e78f1ac8f1055 | 3,602,035 |
import base64
import json
def encode_base64_json(data):
"""
Encode dict-like data into a base64 encoded JSON string.
This can be used to get dict-like data into HTTP headers / envvar.
"""
return base64.b64encode(bytes(json.dumps(data), 'utf-8')) | 08b9d8568a59717173adf00658aad03bddb8df14 | 3,602,036 |
def conjugate_row(row, K):
"""
Returns the conjugate of a row element-wise
Examples
========
>>> from sympy.matrices.densetools import conjugate_row
>>> from sympy import ZZ
>>> a = [ZZ(3), ZZ(2), ZZ(6)]
>>> conjugate_row(a, ZZ)
[3, 2, 6]
"""
result = []
for r in row:
... | c4c5ccb03513c32e3bc9866ef6c3a370e70d01d6 | 3,602,037 |
def load_small_dataset(dataset_dir='./dataset/', batch_size=2, split=('train', 'validation')):
"""加载coco2017子数据集.
Args:
dataset_dir: str, default='./dataset/',
请提前下载coco2017子数据集, 并建立对应路径保存.
[coco2017子数据集](https://github.com/srihari-humbarwadi/datasets/releases/download/v0.1.0/da... | a1e6298fec9154efff70b1b5f116cb7e5f254d38 | 3,602,038 |
import os
import sys
def get_proj_incdirs(proj_dir):
"""
This function finds the include directories
"""
proj_incdir = os.environ.get("PROJ_INCDIR")
incdirs = []
if proj_incdir is None:
if os.path.exists(os.path.join(proj_dir, "include")):
incdirs.append(os.path.join(proj_d... | f39728b8454efeef1e6729d05f4e6dd03110a90d | 3,602,039 |
import os
def find_file(unix_time_sec, top_directory_name, raise_error_if_missing=True,new_version=True):
"""Finds GridRad file on local machine.
Each GridRad file contains all fields at all heights for one valid time.
:param unix_time_sec: Valid time.
:param top_directory_name: Name of top-level di... | 5e3a503bebc54fadb7d787b53a51826d517d06a5 | 3,602,040 |
import re
def linux_ver_normalize(vstr):
"""Normalize a Linux compiler version number.
Intel changed from "80" to "9.0" in 2005, so we assume if the number
is greater than 60 it's an old-style number and otherwise new-style.
Always returns an old-style float like 80 or 90 for compatibility with Window... | fe59ec6bf45a3a93213aa4a9317f0b1e4a12494c | 3,602,041 |
import os
def make_absolute_path(files, root):
"""Make paths absolute."""
for role, path in files.items():
files[role] = os.path.join(root, path)
return files | 49970ca1c7d6eb4d2480fbe73093c40aec1400d6 | 3,602,042 |
import numpy
def gain_cal_bs_lin(vis_pol_src):
"""
Apply stefcal to XX and YY visibilities
Parameters
----------
vis_pol_obs : (2, 2, N, N) array
Observsered (measured) polarized visibilities
Returns
-------
g_bs_lin : (2, N) array
Gain solutions for X and Y chann... | 229a79c27e63917c6ece5240cc243f776eed7db1 | 3,602,043 |
def _get_fischer_burmeister_scalar(a, b):
"""Get the value of the Fischer-Burmeister function for two scalar inputs.
This method was suggested by Bob Vanderbei. Since the Fischer-Burmeister
is symmetric, the order of the scalar inputs does not matter.
Args:
a (float): First input.
b (f... | 4f43169b73c9160ada64ff216fa0a25fdda75cca | 3,602,044 |
import json
from datetime import datetime
import os
import random
def post_task(id):
"""Add a new task to the queue.
TODO: Respect distinction between POST and PUT.
"""
id_string = str(id)
if not Task.query.filter_by(id=id_string).one_or_none():
# Create the task.
app.logger.info... | 5cc455870f5b30dc5689fa40d7638e3d44242c47 | 3,602,045 |
def test_phone_login_or_register():
"""
用户验证码登录或注册
:return:
"""
res = ResMsg()
obj = request.get_json(force=True)
phone = obj.get('account', None)
code = obj.get('code', None)
if phone is None or code is None:
res.update(code=ResponseCode.InvalidParameter)
return res... | 492ce0e90fe0dbd0b3bcba6616a55eef78909953 | 3,602,046 |
import torch
def random_mask_tokens(args, inputs, tokenizer):
""" Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """
if len(inputs.shape) == 1:
inputs = inputs.unsqueeze(0)
labels = inputs.clone()
input_mask = (~inputs.eq(0)).to(torch.fl... | 5522b3aeedad605eb2645a3c8938315ff59b0b7c | 3,602,047 |
def manage_alerts():
"""Manage alerts page."""
alerts = Alert.query.filter(Alert.user_id == current_user.id).all()
form = ManageAlertForm(request.form, alerts)
if request.method == 'POST':
if request.form['submit'] == 'Delete' and form.alert_id.validate(form):
current_alert = None
... | 627617cee3e52f1e801fa81e4b24372426682b2b | 3,602,048 |
def stagnant_operator(
tj=None,
tpulse=10,
tspan=None,
j_el=-1,
L=100e-6,
A=0.196e-4,
q0=1.5e15 / Chem.NA,
p_m=1e5,
mol="H2",
p_gas=0,
normalize=False,
D=None,
kH=None,
n_el=None,
Temp=None,
unit="pmol/s",
flux_direction="out",
verbose=True,
ax... | c28b546288fb52309249e4ea113b3594801f5811 | 3,602,049 |
def default_sv1_sciencemask():
"""Returns default mask of bits for science targets in SV1 survey.
"""
sciencemask = 0
sciencemask |= sv1_mask["LRG"].mask
sciencemask |= sv1_mask["ELG"].mask
sciencemask |= sv1_mask["QSO"].mask
sciencemask |= sv1_mask["BGS_ANY"].mask
sciencemask |= sv1_mas... | 36ae9641b4df0d9877c6ae5310ebe610d352c727 | 3,602,050 |
def EventStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 7a56b1dddd41223435bb51bea1b6fef5e6d027de | 3,602,051 |
import requests
def post(*args, **kwargs):
"""A wrapper for requests.POST method"""
response = requests.post(*args, **kwargs)
if response.status_code == 200:
return response
raise APIError(API_ERROR_MESSAGE.format('POST', response.status_code)) | a07c3999bc2940103a4f3233b074ee4d019faade | 3,602,052 |
def ispyschema(schema):
""" Is object PySchema instance?
Returns true for PySchema Record *classes*
i.e. NOT when schema is a *Record* instance
>>> class FooRecord(Record):
... pass
>>> ispyschema(FooRecord)
True
>>> ispyschema(FooRecord())
False
"""
return isinstance(s... | 1c482e50b6cd531da42e1eee94b7364cda3a7b9e | 3,602,053 |
def video_to_laplace_pyramid_seq(vid, max_layer):
""" Creates a list containing Laplacian pyramids of all video frames. """
pyramid_seq = list()
for frame in vid:
pyramid = build_gauss_pyramid(frame, max_layer=max_layer)
pyramid = build_laplace_pyramid(pyramid)
pyramid_seq.append(py... | bb5d036375814930990e4c0702d790e900708efc | 3,602,054 |
def expand_stereo(ich):
""" Obtain all possible stereoisomers compatible with an InChI string.
:param ich: InChI string
:type ich: str
:rtype: list[str]
"""
gra = graph(ich)
sgrs = automol.graph.stereomers(gra)
ste_ichs = [automol.graph.stereo_inchi(sgr) for sgr in sgrs]
... | 9954e86c44e10eb1b32610942b32cfb67710e4c1 | 3,602,055 |
import math
def edgeweight_properties(graph, weight_label="weight"):
"""
Calculates properties of edge weights.
Parameters
----------
graph: nx.Graph
Graph to calculate the properties from
weight_label:
Returns
-------
max_weight: number
Maximum weights of an edg... | a22857d844c2235859c004bfac897b3b5c80feee | 3,602,056 |
import getopt
import sys
def init(argv):
"""
This procedure uses the getopt class to pull options and their
values out of the commandline argument vector.
"""
config = None
# Parse commandline options
try:
opts, args = getopt.getopt(argv, "c:h", ["config=", "help"])
except geto... | 2ee02ef2666757d892e58145544153c0c9c344da | 3,602,057 |
def timedelta_to_seconds(td):
"""
Converts a timedelta to total seconds.
(This is built-in in Python 2.7)
"""
# we ignore microseconds for this
if not td:
return None
return td.seconds + td.days * 24 * 3600 | ef4ebd88581d8a2a1f64b9f940afbe22da8f55bc | 3,602,058 |
def get_matching(files: dict,
var_order: str,
out_var: dict = None,
**kwargs):
""" Get filenames that have defined variable values
This gets all filenames that match a set of variable values. Variables must
be one of :attr:`VARIABLES`, and the inputs must ... | b3f5532d2bafdd06771ae26c6b640a5699143bc0 | 3,602,059 |
import torch
def _safe_mean(losses, num_present):
"""Computes a safe mean of the losses.
Args:
losses: `Tensor` whose elements contain individual loss measurements.
num_present: The number of measurable elements in `losses`.
Returns:
A scalar representing the mean of `losses`. If `num_present`... | 4174dead8e2fc582633589713e076871a0631de1 | 3,602,060 |
import json
def get_property_value(dcid, prop):
"""Returns the property values for a given node dcid and property label."""
response = dc.fetch_data('/node/property-values', {
'dcids': [dcid],
'property': prop,
},
compress=False,
po... | 9901f5217b9eac8bb042c02136c9f7aa57954e3d | 3,602,061 |
import json
def trip_to_geojson(feed, trip_id, *, include_stops=False):
"""
Return a GeoJSON representation of the given trip, optionally with
its stops.
Parameters
----------
feed : Feed
trip_id : string
ID of trip in ``feed.trips``
include_stops : boolean
Returns
--... | 899981c4945229e5938eae86b88eb91b3ea9b070 | 3,602,062 |
def balance_loss(x, y, y_pred, criterion):
"""
Args:
x: model input
y: labels
y_pred: predictions
criterion: loss function
Returns: balanced loss, torch.tensor
"""
_, _, _, _, _, speaker_ids, emotion_ids = x
batch_size = speaker_ids.shape[0]
loss_balanced = ... | 28ad887934ff60283bde3200b4017374ac6b2bfa | 3,602,063 |
import torch
def custom_op(inputs, name, domain, domain_version, example_outputs):
"""Applies a custom operation, implemented within PopART, to the inputs.
:param tuple inputs: A tuple of input tensors, for example, (x, y).
:param str name: unique name of the PopART custom
:param str domain: domain f... | 02eef53237890a6d6c76b10957b88845fe8f4ce0 | 3,602,064 |
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
"""
Unicode output handler for oracle connections
Source: http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html
"""
if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
return cursor.var(... | 8d8788d141d974da8a19cffa7ed08e0eb3376f0e | 3,602,065 |
def _feet_to_alt_units(alt_units: str) -> float:
"""helper method"""
if alt_units == 'm':
factor = 0.3048
elif alt_units == 'ft':
factor = 1.
else:
raise RuntimeError(f'alt_units={alt_units} is not valid; use [ft, m]')
return factor | 95d5208741fdff275211b9c33a901dedaa65186e | 3,602,066 |
def encrypt_aes_cbc(text, key, iv):
"""
encrypt_aes_cbc
"""
aes = AES.new(key.encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"))
encrypt_text = aes.encrypt(pad(text.encode("utf-8"), AES.block_size, style="pkcs7"))
return encrypt_text.hex() | b5d85930afd0c92c5b7a3f5e07bfb866a92e4bfd | 3,602,067 |
from datetime import datetime
def edit_machine():
"""The page to edit a machine (also used for creating a new machine)
This page will allow an ID to be specified for new machines being created, but will not allow the ID
to be changed for existing machines."""
form = MachineForm()
ids = []
# G... | f135c0008543770fa569c44ecaf8973b542b7e32 | 3,602,068 |
def condition_adjoint( physical_adjoint ):
"""
application: apply pre-conditioning to PhysicalAdjointData, get vector gradient
input: PhysicalAdjointData
output: UnknownData
notes: this function must apply the prior error covariance
"""
return phys_to_unk( physical_adjoint, True ) | 616fdce0399b83bb484d52d9e0213d707a2ca368 | 3,602,069 |
import re
def ParseTraceDump(msg):
"""Parse a full backtrace. Returns a list of strings split by the location lines (File ..., line ..., in ...).
These lines are included in the output.
"""
return re.split(kTraceCodeLine, msg) | 6a9067327fc5e245f18d601bec2706eef77f39a3 | 3,602,070 |
def get_proper_state(job, state):
"""
Return a proper job state to send to server.
This function should only return 'starting', 'running', 'finished', 'holding' or 'failed'.
If the internal job.serverstate is not yet set, it means it is the first server update, ie 'starting' should be
sent.
:pa... | ba54c1f4eee99055e73099bc381ccbb69da4b183 | 3,602,071 |
def solve(task: str) -> str:
"""Find Knot Hash of the given input."""
rope = Rope()
lengths = process_data(task) + [17, 31, 73, 47, 23]
for _ in range(64):
for length in lengths:
rope.reverse(length)
rope.move(length)
sparse_hash = rope.nodes
dense_hash = compress... | 5e9399639512eea078ac7ee1bd9e6fa567369ea3 | 3,602,072 |
def get_first_import(node, context, name, base, level):
"""return the node where [base.]<name> is imported or None if not found
"""
fullname = '%s.%s' % (base, name) if base else name
first = None
found = False
for first in context.body:
if first is node:
continue
if... | 52b278d0eadf6337743d2395d4a829c9f5c318c2 | 3,602,073 |
def are_collinear(p1, p2, p3, tolerance=0.5):
"""return True if 3 points are collinear.
tolerance value will decide whether lines are collinear; may need
to adjust it based on the XY tolerance value used for feature class"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
r... | 337065b80e1cc1810be263bccd9c8ae66c258ed3 | 3,602,074 |
def transformResults(threadCounts, values, function):
"""Apply the function to all of the measurements"""
res = {}
for bm in list(values.keys()):
res[bm] = []
for (nThreads, v) in zip(threadCounts, values[bm]):
res[bm].append(None if v == None else function(v, nThreads))
retu... | 1fe7944479b045bebd403eeb888fe0c00b012291 | 3,602,075 |
import math
def coriolis_freq(lat):
"""Compute coriolis frequency.
https://en.wikipedia.org/wiki/Earth%27s_rotation#Angular_speed
omega = 7.2921150 ± 0.0000001×10−5 radians per second
:param theta: Latitude in degrees.
"""
omega = 7.2921150e-5
theta = math.radians(lat)
f = 2 * omega... | a5f40ef6b3862746905ab8e3cd4e77f1fdc1d484 | 3,602,076 |
def history_ping_stats(filename, parse_samples, verbose=False):
"""Fetch, parse, and compute the packet loss stats.
Args:
filename (str): Filename from which to read JSON data, or "-" to read
from standard input.
parse_samples (int): Number of samples to process, or -1 to parse all
... | bb717176ce99413be37b5844a7b33a8671b64711 | 3,602,077 |
def _find_cut_ranges(spark_context, tsuid, criteria, md_list, chunk_size=75000):
"""
Find the start and end dates in reference tsuid to be used later for cutting other TS depending on criteria.
Return example with 3 ranges found:
[
[ start_date_of_1st_range, end_date_of_1st_range],
[ star... | bc96d3c02b68715b4b8a0b750aa053a8ed9e301d | 3,602,078 |
def concat_channels(l_inputs, data_format='NHWC', scope=None):
"""Concat a list of tensors on the channel axis.
Args:
inputs: List Tensors;
data_format: NHWC or NCHW.
"""
with tf.name_scope(scope, 'concat_channels', l_inputs):
if data_format == 'NHWC':
net = tf.concat(l_... | 2a80a58ba261afc3a38527b9d5e5b8a2e730a066 | 3,602,079 |
def _msearch_success(response):
"""Return true if all requests in a multi search request succeeded
Parameters
----------
response : requests.models.Response
Returns
-------
bool
"""
parsed = response.json()
if 'responses' not in parsed:
return False
for result in pa... | acdac4408464120fdeb7f20a06f07aac6ca3809f | 3,602,080 |
import requests
def create_oauth_client():
"""
Create a new OAuth client in fidesops.
Returns the response JSON if successful, or throws an error otherwise.
See http://localhost:8000/docs#/OAuth/acquire_access_token_api_v1_oauth_token_post
See http://localhost:8000/docs#/OAuth/acquire_access_token... | 30aa8cbadb7f852184d507af1bf35510cb5e8bef | 3,602,081 |
def _get_named_patterns():
"""Returns list of (pattern-name, pattern) tuples"""
resolver = urlresolvers.get_resolver(None)
patterns = sorted([(key, value[0][0][0])
for key, value in resolver.reverse_dict.items()
if isinstance(key, string_types)
... | 26ffa4485bc5c2c7525f110c3c817b97167c419e | 3,602,082 |
def get_embeddings(sess, GNN, batch, time_steps):
"""
Givan an input batch, return a list of lists of n-dimensional vertex
embeddings produced by the GNN in 'time_steps' timesteps
"""
# Build the feed_dict
feed_dict = {}
feed_dict[ GNN["gnn"].matrix_placeholders["M"] ] = sparse_to_d... | 78dd209e5ad0c244834cfbef57933118e5fbee8c | 3,602,083 |
def name(func):
"""Decorator for name conversion.
Decorated function takes two arguments 'root' and 'filename' and returns
new filename.
Args:
func name conversion.
"""
_Funcs.instance().add_name(func)
return func | 6257562ed828cd1f2e1d38742ff005ad1ecb8f77 | 3,602,084 |
def np_to_tfrecords(X, Y, file_path_prefix, verbose=True):
"""
Converts a Numpy array (or two Numpy arrays) into a tfrecord file.
For supervised learning, feed training inputs to X and training labels to Y.
For unsupervised learning, only feed training inputs to X, and feed None to Y.
The length of ... | d8f1cf8e64904ffbf90fab8af659d47f7b787635 | 3,602,085 |
def generate_pyi(src, options=None, loader=None):
"""Run the inferencer on a string of source code, producing output.
Args:
src: The source code.
options: config.Options object.
loader: A load_pytd.Loader instance.
Returns:
A tuple, (errors.ErrorLog, PYI Ast as string, TypeDeclUnit).
Raises:
... | 1e88e5a53f86be49013cfbe80591abe79bdc2647 | 3,602,086 |
def get_pi_noise_clipped(pi, noise_scale=0.1, noise_clip=0.5, act_limit=10.):
""" Add clipped noise to sampled target action, and then clip to stay
within the valid value of the action """
clipped_noise = get_clipped_noise(
tf.shape(pi), noise_scale=noise_scale, noise_clip=noise_clip)
pi_noise =... | a189ece154738bdc6b226a024ad955c1ef09a8e2 | 3,602,087 |
def shp(arr):
""" return dimension of an array
Parameters
----------
arr : ndarray
Returns
-------
shp : tuple
Examples
--------
>>> import pylayers.util.pyutil as pyu
>>> import numpy as np
>>> from scipy import *
>>> a = np.arange(10)
>>> pyu.shp(a)
(1,... | 39e9d344cbc62da60dd1eb28c1727ab7d01ded96 | 3,602,088 |
def form2_end_term(request):
"""TODO: Docstring for home.
:returns: TODO
"""
form2_end_term = models.Form2EndTerm.objects.all()
return render(request, 'membership/form2_end_term.html', { 'form2_end_term': form2_end_term }) | dc13b1295c10b494a47f1f84065463f8497dd1d7 | 3,602,089 |
from typing import Union
from pathlib import Path
from typing import Iterable
from typing import Any
from typing import List
def discover_attributes(
source: Union[Path, str, Module, Iterable[Module]],
signature: type = Any, # type: ignore
include_privates: bool = False,
in_private_mo... | c064969a93895e029a2c35757a65d7eee794a444 | 3,602,090 |
import torch
import logging
def config_network(scene, task, tiny, grayscale, uncertainty, fullsize, network_in, num_enc=0):
"""
Configure evaluation network.
"""
if 'urbanscape' in scene.lower() or 'naturescape' in scene.lower():
if task == 'coord':
num_task_channel = 3
eli... | 3d4c1cdca4c97c7fc2c7a95e6b6ceabe36dba666 | 3,602,091 |
import signal
def cfg_job_class(value):
"""Return job queue class based on name
Args:
value (object): May be class or str.
Returns:
object: `Background` or `Celery` class.
"""
if isinstance(value, type) and issubclass(value, (Celery, Background)):
# Already initialized b... | 5ba5ef6379db0c873913b8e63e108bd9cf27e591 | 3,602,092 |
import os
import sys
import inspect
def getCorrectPath(filePath):
"""Returns the correct path (relative/absolute) wether is a frozen app or a script
Args:
filePath (str): The path to the resource you need
Returns:
str: Final resolved path
"""
# Se il percorso specificato è assoluto non fare nulla
if os.pat... | 5945abf0c628434ecd72835878c93bacbad434d3 | 3,602,093 |
def _split_examples(examples, config):
"""Split examples into a sampled and a remaining subset based on config."""
# Only consider unique examples.
# TODO(petershaw): Consider preserving the number of occurences for each
# unique example to better weight sampling for computing the dataset encoding
# codelengt... | deac88a82376e73c0526d8a75fc19d12bcf6a613 | 3,602,094 |
import json
def get_team_port(duthost, pc):
"""
Dump teamd info
Args:
duthost: DUT host object
pc: PortChannel name
"""
dut_team_cfg = duthost.shell("teamdctl {} config dump".format(pc))['stdout']
dut_team_port = json.loads(dut_team_cfg)['ports'].keys()
return dut_team_port... | f60c18d1a4f8514ec0ee042a820eaec3902bfc24 | 3,602,095 |
from typing import List
from re import A
def compose(transforms_to_compose: List[BasicTransform]) -> A.Compose:
"""
Wrapper for albumentations compose func. Takes in a list of
albumentation transforms and composes them to one transformation
pipeline
Returns:
----------
A composed pi... | ba45e24d6e56facf6fe7b8ba17c4bbd793c63595 | 3,602,096 |
def varadd(a, b, undef=-9999.):
"""
Addition:
x = varadd(a, b) means x = a + b, where a and b are ndarray or float.
Parameters
----------
a : ndarray
input variable 1
b : ndarray
input variable 2
undef : float, optional
elements are excluded from the calculat... | e972799d84fa4bc96a0e6a2fdeb2195b0894f35d | 3,602,097 |
def subnet_to_string(subnet):
"""Given Subnet instance returns a string describing it."""
# Count number of least significant zero bits in the mask.
mask = subnet.mask
i = 0
while not (mask & 1) and i < subnet.bits:
mask = mask >> 1
i += 1
base_ip = IP(subnet.bits, subnet.base)
return '%s/%d' % (i... | 8a24cdf1f8133f0265a4a4d196d1ac58696c2f53 | 3,602,098 |
def parse_leaderboard_args(args, user_timezone: timezone = None):
"""Parse the leaderboard command arguments, return a dictionary with the values parsed:
dict:{
'names': [<str>] | None,
'canvas': <Boolean>,
'lines': <int>,
'speed': <Boolean>,
'last': <str> | None,
... | d5ca4deeeab5b69bc5f7c9d6963a82285422d5cd | 3,602,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.