content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dict_compare(d1, d2):
"""
compares all differences between 2x dicts.
returns sub-dicts: "added", "removed", "modified", "same"
"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_ke... | 284368eade7de1e1abfd629ea903f6dff113e279 | 3,655,200 |
from datetime import datetime
def toLocalTime(seconds, microseconds=0):
"""toLocalTime(seconds, microseconds=0) -> datetime
Converts the given number of seconds since the GPS Epoch (midnight
on January 6th, 1980) to this computer's local time. Returns a
Python datetime object.
Examples:
>>... | 9dd9352003b19b5e785766c7fb6e11716284c3ed | 3,655,201 |
def get_part_01_answer():
"""
Static method that will return the answer to Day01.01
:return: The product result
:rtype: float
"""
return prod(summation_equals(puzzle_inputs, 2020, 2)) | 4fcc108bef3d0e5117caff4f02ff7797021a0efd | 3,655,202 |
def eig_of_series(matrices):
"""Returns the eigenvalues and eigenvectors for a series of matrices.
Parameters
----------
matrices : array_like, shape(n,m,m)
A series of square matrices.
Returns
-------
eigenvalues : ndarray, shape(n,m)
The eigenvalues of the matrices.
e... | fd34bdb1dc1458d0d495259a07572e0b0a2e685a | 3,655,203 |
from re import T
def injectable(
cls: T = None,
*,
qualifier: str = None,
primary: bool = False,
namespace: str = None,
group: str = None,
singleton: bool = False,
) -> T:
"""
Class decorator to mark it as an injectable dependency.
This decorator accepts customization paramete... | 06f1b6d5b3747d92e91cf751e62d90222e06d9a8 | 3,655,204 |
def build_graph(defined_routes):
"""
build the graph form route definitions
"""
G = {}
for row in defined_routes:
t_fk_oid = int(row["t_fk_oid"])
t_pk_oid = int(row["t_pk_oid"])
if not t_fk_oid in G:
G[t_fk_oid] = {}
if not t_pk_oid in G:
G[t_p... | 16962ee1f4e336a9a1edc7cc05712113461f9a1a | 3,655,205 |
def grando_transform_gauss_batch(batch_of_images, mean, variance):
"""Input: batch of images; type: ndarray: size: (batch, 784)
Output: batch of images with gaussian nois; we use clip function
to be assured that numbers in matrixs belong to interval (0,1);
type: ndarray; size: (batch, 784);
"""
... | 4def857b315c425337d3edb6273af16f052cb1ba | 3,655,206 |
import subprocess
def get_poetry_project_version() -> VersionInfo:
"""Run poetry version and get the project version"""
command = ["poetry", "version"]
poetry_version_output = subprocess.check_output(command, text=True)
return version_string_to_version_info(poetry_version_output.split(" ")[1]) | a4dc920239aef09b269a6f75568701788db2f708 | 3,655,207 |
def LF_DG_DISTANCE_SHORT(c):
"""
This LF is designed to make sure that the disease mention
and the gene mention aren't right next to each other.
"""
return -1 if len(list(get_between_tokens(c))) <= 2 else 0 | 23b5450b844f91d6cae0993f2b7cda5c80460be1 | 3,655,208 |
def populate_user_flags(conf, args):
"""Populate a dictionary of configuration flag parameters, "conf", from
values supplied on the command line in the structure, "args"."""
if args.cflags:
conf['cflags'] = args.cflags.split(sep=' ')
if args.ldflags:
conf['ldflags'] = args.ldflags.sp... | 3f3fe64e2e352e0685a048747c9c8351575e40fb | 3,655,209 |
def combine_raytrace(input_list):
"""
Produce a combined output from a list of raytrace outputs.
"""
profiler.start('combine_raytrace')
output = dict()
output['config'] = input_list[0]['config']
output['total'] = dict()
output['total']['meta'] = dict()
output['total']['image'] = dic... | 2ed47dc60585e793bdc40fa39e04057c26db347d | 3,655,210 |
def is_dict():
"""Expects any dictionary"""
return TypeMatcher(dict) | 81bed05f5c8dae6ba3b8e77caa4d2d7777fb7ea9 | 3,655,211 |
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.bids import BIDSFreeSurferDir
import os
from pathlib import Path
def init_dmriprep_wf():
"""
Build *dMRIPrep*'s pipeline.
This workflow organizes the execution of *dMRIPrep*, with a sub-workflow for
each... | 3cc4825cf5e1f376c19610c9289e89d2813e7125 | 3,655,212 |
import re
def get_list_from_comma_separated_string(comma_separated_list):
"""
get a python list of resource names from comma separated list
:param str comma_separated_list:
:return:
"""
# remove all extra whitespace after commas and before/after string but NOT in between resource names
rem... | 73df5fe431aceec0fec42d6019269a247b5587a5 | 3,655,213 |
def cci(series, window=14):
"""
compute commodity channel index
"""
price = typical_price(series)
typical_mean = rolling_mean(price, window)
res = (price - typical_mean) / (.015 * np.std(typical_mean))
return pd.Series(index=series.index, data=res) | b3eeabd4369fc1a041c3a714edc193deced804dc | 3,655,214 |
def load_definition_from_string(qualified_module, cache=True):
"""Load a definition based on a fully qualified string.
Returns:
None or the loaded object
Example:
.. code-block:: python
definition = load_definition_from_string('watson.http.messages.Request')
request = definit... | c435b4945878c5b5c2f5c7e252259da2be2345d0 | 3,655,215 |
import requests
import logging
def get_session(auth_mechanism, username, password, host):
"""Takes a username, password and authentication mechanism, logs into ICAT
and returns a session ID"""
# The ICAT Rest API does not accept json in the body of the HTTP request.
# Instead it takes the form parame... | 2395751bc64300ae32c052e5a9aba04e50f7941f | 3,655,216 |
from typing import List
def _create_all_aux_operators(num_modals: List[int]) -> List[VibrationalOp]:
"""Generates the common auxiliary operators out of the given WatsonHamiltonian.
Args:
num_modals: the number of modals per mode.
Returns:
A list of VibrationalOps. For each mode the numbe... | 58a30221757bfcaa5c8b8790fd5556b060ecc8d1 | 3,655,217 |
from typing import List
from typing import Concatenate
def add_conv(X: tf.Tensor, filters: List[int], kernel_sizes: List[int],
output_n_filters: int) -> tf.Tensor:
"""
Builds a single convolutional layer.
:param X: input layer.
:param filters: number of output filters in the convolution.... | 69e907fc87780ce754c69500108dc00866fef716 | 3,655,218 |
def show_toast(view, message, timeout=DEFAULT_TIMEOUT, style=DEFAULT_STYLE):
# type: (sublime.View, str, int, Dict[str, str]) -> Callable[[], None]
"""Show a toast popup at the bottom of the view.
A timeout of -1 makes a "sticky" toast.
"""
messages_by_line = escape_text(message).splitlines()
c... | 910809b3efca6c1256af3540acbe42449080bebc | 3,655,219 |
def flip_metropolised_gibbs_numba_classic(p, z):
"""
Given the *probability* of z=1
flip z according to metropolised Gibbs
"""
if z == 1:
if p <= .5:
return -z
# alpha = 1 # TODO, can return -x here
else:
alpha = (1 - p) / p
else:
if p ... | c2399ae8923fd8a533e1b9020a2462d8109c0855 | 3,655,220 |
def get_default_interpreter():
"""Returns an instance of the default interpreter class."""
return __default_interpreter.get() | 8807e2480787d26e81ab1be3377f8e3a11daa1de | 3,655,221 |
def fx_ugoira_frames():
"""frames data."""
return {
'000000.jpg': 1000,
'000001.jpg': 2000,
'000002.jpg': 3000,
} | e3517b37bb4c9cd1dfb70b13128d16ef80a9801a | 3,655,222 |
import array
def coherent_tmm(pol, n_list, d_list, th_0, lam_vac):
"""
This is my slightly modified version of byrnes's "coh_tmm"
I've rearranged the calculations in a way that is more intuitive to me
Example inputs:
For angle dependence, be careful to include air first, otherwise the angle ... | 3e10041325ee211d684c9ad960b445df8e6de2db | 3,655,223 |
def base_info():
"""
基本资料的展示和修改
1、尝试获取用户信息
2、如果是get请求,返回用户信息给模板
如果是post请求:
1、获取参数,nick_name,signature,gender[MAN,WOMAN]
2、检查参数的完整性
3、检查gender性别必须在范围内
4、保存用户信息
5、提交数据
6、修改redis缓存中的nick_name
注册:session['nick_name'] = mobile
登录:session['nick_name'] = user.nick_name
修... | 87d5595171e2cecc469ea933b210783e15c477d2 | 3,655,224 |
def to_list(obj):
""" """
if isinstance(obj, np.ndarray):
return obj.tolist()
raise TypeError('Not serializable') | 92e4851bb117ab908dc256f8b42ef03c85d70e28 | 3,655,225 |
from sage.symbolic.expression import Expression
from sage.symbolic.ring import SR
from inspect import signature, Parameter
def symbolic_expression(x):
"""
Create a symbolic expression or vector of symbolic expressions from x.
INPUT:
- ``x`` - an object
OUTPUT:
- a symbolic expression.
... | 648c85a8fd3f4ffefec44e5720f8c9ac68c10388 | 3,655,226 |
def seq_hyphentation(words):
"""
Converts words in a list of strings into lists of syllables
:param words: a list of words (strings)
:return: a list of lists containing word syllables
"""
return [hyphenation(w) for w in words] | dd1ab65f64926e724718edac316a98bac99991da | 3,655,227 |
def angle(A, B, dim=1):
"""
Computes the angle in radians between the inputs along the specified dimension
Parameters
----------
A : Tensor
first input tensor
B : Tensor
second input tensor
dim : int (optional)
dimension along the angle is computed (default is 1)
... | f64950b8004a32e2ab274efee3a9bedf6441439a | 3,655,228 |
import functools
def _run_lint_helper(
*, fail_on_missing_sub_src, exclude_lint, warn_lint, site_name=None):
"""Helper for executing lint on specific site or all sites in repo."""
if site_name:
func = functools.partial(engine.lint.site, site_name=site_name)
else:
func = engine.lint... | a73e2e9a4bb968376622308cf7af2f97f6533595 | 3,655,229 |
def simulate_from_orders_nb(target_shape: tp.Shape,
group_lens: tp.Array1d,
init_cash: tp.Array1d,
call_seq: tp.Array2d,
size: tp.ArrayLike = np.asarray(np.inf),
price: tp.ArrayLik... | 32898fa1a1aadf50d6d07553da8e7bed94f3de0e | 3,655,230 |
def get_data_value(k: int, data: bytes) -> bytes:
"""Extracts the kth value from data.
data should be in the format value0:value1:value2:...:valueN. This last representation
is merely for understanding the logic. In practice, data will be a sequence of bytes,
with each value preceded by the length of s... | 9ee1c2370ff8935df2f26680c73655b89dfcc7aa | 3,655,231 |
def exp_map_individual(network, variable, max_degree):
"""Summary measure calculate for the non-parametric mapping approach described in Sofrygin & van der Laan (2017).
This approach works best for networks with uniform degree distributions. This summary measure generates a number
of columns (a total of ``m... | cb4424ad10dae3df4a3d60ec5d7b143b2130a9bb | 3,655,232 |
def bridge_meshes(Xs, Ys, Zs, Cs):
"""
Concatenate multiple meshes, with hidden transparent bridges, to a single mesh, so that plt.plot_surface
uses correct drawing order between meshes (as it really should)
:param list Xs: list of x-coordinates for each mesh
:param list Ys: list of y-coordinates fo... | 389948e3d357cb7a87e844eee8417f2466c41cab | 3,655,233 |
def get_groups():
"""
Get the list of label groups.
@return: the list of label groups.
"""
labels_dict = load_yaml_from_file("labels")
groups = []
for group_info in labels_dict["groups"]:
group = Group(**group_info)
label_names = group_info.pop("labels", [])
groups.a... | 03822287ab1a2525560f6fdf2a55a3c2461c6bea | 3,655,234 |
def diffractometer_rotation(phi=0, chi=0, eta=0, mu=0):
"""
Generate the 6-axis diffracometer rotation matrix
R = M * E * X * P
Also called Z in H. You, J. Appl. Cryst 32 (1999), 614-623
:param phi: float angle in degrees
:param chi: float angle in degrees
:param eta: float angle in degree... | 7f56caf6585f74406b8f681614c6a6f32592ad91 | 3,655,235 |
def supports_build_in_container(config):
"""
Given a workflow config, this method provides a boolean on whether the workflow can run within a container or not.
Parameters
----------
config namedtuple(Capability)
Config specifying the particular build workflow
Returns
-------
tu... | 278bde73252d13784298d01d954a56fcecd986dc | 3,655,236 |
def get_img_array_mhd(img_file):
"""Image array in zyx convention with dtype = int16."""
itk_img = sitk.ReadImage(img_file)
img_array_zyx = sitk.GetArrayFromImage(itk_img) # indices are z, y, x
origin = itk_img.GetOrigin() # x, y, z world coordinates (mm)
origin_zyx = [origin[2], origin[1], origin... | 6c6bafedf34aaf0c03367c9058b29401bf133fd0 | 3,655,237 |
def registration(request):
"""Render the registration page."""
if request.user.is_authenticated:
return redirect(reverse('index'))
if request.method == 'POST':
registration_form = UserRegistrationForm(request.POST)
if registration_form.is_valid():
r... | dae59392e290291d9d81ca427ee35b07c6ed554b | 3,655,238 |
def _get_arc2height(arcs):
"""
Parameters
----------
arcs: list[(int, int)]
Returns
-------
dict[(int, int), int]
"""
# arc2height = {(b,e): np.abs(b - e) for b, e in arcs}
n_arcs = len(arcs)
arcs_sorted = sorted(arcs, key=lambda x: np.abs(x[0] - x[1]))
arc2height = {ar... | feb929e9f2e23e1c154423930ae33944b95af699 | 3,655,239 |
from shutil import copyfile
def init_ycm(path):
"""
Generate a ycm_extra_conf.py file in the given path dir to specify
compilation flags for a project. This is necessary to get
semantic analysis for c-family languages.
Check ycmd docs for more details.
"""
conf = join(path, '.ycm_extra_... | 361d744982c2a8c4fd1e787408150381a3b111d3 | 3,655,240 |
def get_aggregate_stats_flows_single_appliance(
self,
ne_pk: str,
start_time: int,
end_time: int,
granularity: str,
traffic_class: int = None,
flow: str = None,
ip: str = None,
data_format: str = None
) -> dict:
"""Get aggregate flow stats data for a single appliance filter by
... | 5ca6e2b5ce1b176aea603a254b0ca655e0f43c0c | 3,655,241 |
def load_user(userid):
"""Callback to load user from db, called by Flask-Login"""
db = get_db()
user = db.execute("SELECT id FROM users WHERE id = ?", [userid]).fetchone()
if user is not None:
return User(user[0])
return None | 0dd9516af3670794c107bd6633c74a033f0a4983 | 3,655,242 |
import torch
def get_partial_outputs_with_prophecies(prophecies, loader, model, my_device,
corpus, seq2seq):
"""
Parameters
----------
prophecies : dict
Dictionary mapping from sequence index to a list of prophecies, one
for each prefix in... | cae0ed8643f677a5d2a2f3e75858b68f473acc50 | 3,655,243 |
from typing import Tuple
from typing import Optional
from typing import List
import io
import textwrap
from re import I
def _generate_deserialize_impl(
symbol_table: intermediate.SymbolTable,
spec_impls: specific_implementations.SpecificImplementations,
) -> Tuple[Optional[Stripped], Optional[List[Error]]]:
... | 3e2e3c78709b75a8b650d775d4b0f8b6c8287ca0 | 3,655,244 |
def timestep_to_transition_idx(snapshot_years, transitions, timestep):
"""Convert timestep to transition index.
Args:
snapshot_years (list): a list of years corresponding to the provided
rasters
transitions (int): the number of transitions in the scenario
timestep (int): the... | 96bcda2493fcd51f9c7b335ea75fd612384207e3 | 3,655,245 |
import os
def _make_abs_path(path, cwd=None, default=None):
"""convert 'path' to absolute if necessary (could be already absolute)
if not defined (empty, or None), will return 'default' one or 'cwd'
"""
cwd = cwd or get_cwd()
if not path:
abs_path = default or cwd
elif os.path.isabs(pa... | 7fbe6187d544935cf3dd933b0796a119c7cf36d0 | 3,655,246 |
def resolve_checks(names, all_checks):
"""Returns a set of resolved check names.
Resolving a check name expands tag references (e.g., "@tag") to all the
checks that contain the given tag. OpenShiftCheckException is raised if
names contains an unknown check or tag name.
names should be a sequence o... | d86dcd9a5539aeaa31fb3c86304c62f8d86bbb11 | 3,655,247 |
from typing import Optional
def swish(
data: NodeInput,
beta: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performing Swish activation function Swish(x, beta=1.0) = x * sigmoid(x * beta)).
:param data: Tensor with input data floating point type.
:r... | d17562d0e63aa1610d9bc641faabec27264a2919 | 3,655,248 |
from datetime import datetime
def cut_out_interval(data, interval, with_gaps=False):
"""
Cuts out data from input array.
Interval is the start-stop time pair.
If with_gaps flag is True, then one NaN value will be added
between the remaining two pieces of data.
Returns modified data array.
... | 753be7e45102a7e0adc1b19365d10e009c8f6b89 | 3,655,249 |
import re
def _abbreviations_to_word(text: str):
"""
对句子中的压缩次进行扩展成单词
:param text: 单个句子文本
:return: 转换后的句子文本
"""
abbreviations = [
(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
... | 576eb1588c40ab4b9ffa7d368249e520ecf887ba | 3,655,250 |
def resnet56(num_classes=100):
"""Constructs a ResNet-56 model for CIFAR-10 (by default)
Args:
num_classes (uint): number of classes
"""
model = CifarResNet(ResNetBasicblock, 56, num_classes)
return model | 98070a6a1b6f69b2d253537b604c616ae52de9b2 | 3,655,251 |
import logging
def _fetch_latest_from_memcache(app_version):
"""Get the latest configuration data for this app-version from memcache.
Args:
app_version: the major version you want configuration data for.
Returns:
A Config class instance for most recently set options or None if none
could be found ... | d9d4fc89c492b58e56b847dee7a2d69f98715a9e | 3,655,252 |
def pad_set_room(request):
"""
pad修改关联会议室
:param request:
:return:
"""
dbs = request.dbsession
user_id = request.POST.get('user_id', '')
room_id = request.POST.get('room_id', '')
pad_code = request.POST.get('pad_code', '')
if not user_id:
error_msg = '用户ID不能为空!'
elif ... | 1646204a666e68021c649b6d322b74cbcd515fd2 | 3,655,253 |
def airffromrh_wmo(rh_wmo,temp,pres,asat=None,dhsat=None,chkvals=False,
chktol=_CHKTOL,asat0=None,dhsat0=None,chkbnd=False,mathargs=None):
"""Calculate dry fraction from WMO RH.
Calculate the dry air mass fraction from the relative humidity. The
relative humidity used here is defined by the WMO as:... | 1e4418591087a4bd26b48c470239df58087cdb6e | 3,655,254 |
import ast
def resolve_If(node: ast.If, tree: ast.Module, context: Context) -> WorkflowStep:
"""
Make the resolved condition string and body into a workflow step.
TODO: support assignments, not just calls
TODO: support multi-statement bodies
"""
if len(node.body) > 1:
raise NotImpleme... | 386b154a48ca36a28b6c91c4e355178fadf74eb7 | 3,655,255 |
import base64
import zlib
def inflate(data: str) -> str:
"""
reverses the compression used by draw.io
see: https://drawio-app.com/extracting-the-xml-from-mxfiles/
see: https://stackoverflow.com/questions/1089662/python-inflate-and-deflate-implementations
:param data: base64 encoded string
:r... | e4456c7482591611436a92a71464754871461fd5 | 3,655,256 |
import operator
def get_tree(data_path,sep,root,cutoff,layer_max,up=True):
"""
This function takes the path of a data file of edge list with numeric
weights and returns a tree (DiGraph object). The parameters include:
data_path: The path of a data file of edge list with numeric weights.
sep: The ... | 6f2d151aac39786311c61da4f38140e6c0159562 | 3,655,257 |
def delete_functions(lambda_client, function_list) -> list:
"""Deletes all instances in the instances parameter.
Args:
lambda_client: A lambda boto3 client
function_list: A list of instances you want deleted.
Returns:
A count of deleted instances
"""
terminated_functions = ... | f0ca59647f6813d04bf2bbd6ec33ed7744acdd04 | 3,655,258 |
def make_random_shares(seed, minimum, n_shares, share_strength=256):
"""
Generates a random shamir pool for a given seed phrase.
Returns share points as seeds phrases (word list).
"""
if minimum > n_shares:
raise ValueError(
"More shares needed (%d) to recover the seed phrase tha... | a8496909cc06f3663d07036e54af744ac7e26b18 | 3,655,259 |
from typing import Optional
from typing import Sequence
def confusion_matrix(
probs: Optional[Sequence[Sequence]] = None,
y_true: Optional[Sequence] = None,
preds: Optional[Sequence] = None,
class_names: Optional[Sequence[str]] = None,
title: Optional[str] = None,
):
"""
Computes a multi-r... | c2b63ccf7e3f226b6bfbea4656bc816eaa6e336a | 3,655,260 |
import html
def get_monitor_details():
"""Render the index page."""
monitor_id = paranoid_clean(request.args.get('id'))
monitors = mongo.db[app.config['MONITORS_COLLECTION']]
monitor = monitors.find_one({'hashed': monitor_id}, {'_id': 0})
if not monitor:
return jsonify({'success': False, '... | 6a45ed67ff79216c9048ce9e3ed80be4e43b9bd9 | 3,655,261 |
def _simplify(obj: object) -> object:
"""
This function takes an object as input and returns a simple
Python object which is supported by the chosen serialization
method (such as JSON or msgpack). The reason we have this function
is that some objects are either NOT supported by high level (fast)
... | fc17b64e3701faa70ea5bfb36a8e2b9195dcbab1 | 3,655,262 |
import copy
def match_v2v3(aperture_1, aperture_2, verbose=False):
"""Use the V2V3 from aperture_1 in aperture_2 modifying X[Y]DetRef,X[Y]SciRef to match.
Also shift the polynomial coefficients to reflect the new reference point origin
and for NIRCam recalculate angles.
Parameters
----------
... | 295eb72c43f073f71b1cedaf8a94d6b1cc61dbf7 | 3,655,263 |
import sys
def PlatformPager() -> PagerCommand:
"""
Return the default pager command for the current platform.
"""
if sys.platform.startswith('aix'):
return More()
if sys.platform.startswith('win32'):
return More()
return Less() | 23aaaf8a14b4ed83ea3b2e92dfbf8e58c18817a7 | 3,655,264 |
import time
def get_offset(sample_time):
"""
Find simple offsett values.
During the sample time of this function
the BBB with the magnetometer on should be rotated
along all axis.
sample_time is in seconds
"""
start = time.clock()
mag_samples = []
mag_max = [0,0,0]
mag_mi... | 712fe82dbdc50e198baf93b752f572331ce33f63 | 3,655,265 |
import os
def get_zips(directory: str) -> list:
"""
Return a the ZIP from a specified directory after running
some sanity checks
"""
zips = {}
for file in [os.path.join(dp, file) for dp, dn, fn in os.walk(directory) for file in fn]:
if file.split('.')[-1] != 'zip':
cont... | 7bee4d1acc1fa51fc1499ca47a8759a9aa61ec67 | 3,655,266 |
def get_multimode_2d_dist(num_modes: int = 1, scale: float = 1.0):
"""Get a multimodal distribution of Gaussians."""
angles = jnp.linspace(0, jnp.pi * 2, num_modes + 1)
angles = angles[:-1]
x, y = jnp.cos(angles) * scale / 2., jnp.sin(angles) * scale / 2.
loc = jnp.array([x, y]).T
scale = jnp.ones((num_mode... | dab5400e545feb7cde2804af151f3c20c600b0ce | 3,655,267 |
def residual_squared_error(data_1, data_2):
"""
Calculation the residual squared error between two arrays.
Parameters
----------
data: numpy array
Data
calc: numpy array
Calculated values
Return
------
rse: float
residual squared error
"""
RSS = np.... | 771c365fc38d6eda07989a1a6eb34c0f96347c3c | 3,655,268 |
def by_index(pot):
""" Build a new potential where the keys of the potential dictionary
correspond to the indices along values of n-dimensional grids,
rather than, possibly, the coordinate values of the grids themselves.
Key Transformation:
((grid_val_i, grid_val_j, ...)_i,) -> ((i,... | 7235322f606cf972c8bf4ad46a614001f235b3e9 | 3,655,269 |
def current_user():
"""Получить текущего пользователя или отредактировать профиль"""
user = get_user_from_request()
if request.method == "POST":
json = request.get_json()
user.email = json.get("email", user.email)
user.name = json.get("name", user.name)
user.about = sanitiz... | e7e3db1744e21c64732217e1609a113b938c677c | 3,655,270 |
from datetime import datetime
async def async_union_polygons(bal_name, geom_list):
"""union a set of polygons & return the resulting multipolygon"""
start_time = datetime.now()
big_poly = unary_union(geom_list)
print(f"\t - {bal_name} : set of polygons unioned: {datetime.now() - start_time}")
r... | 2432818d6bb38232e08a4439e7a69007a7c24334 | 3,655,271 |
def _error_text(because: str, text: str, backend: usertypes.Backend) -> str:
"""Get an error text for the given information."""
other_backend, other_setting = _other_backend(backend)
if other_backend == usertypes.Backend.QtWebKit:
warning = ("<i>Note that QtWebKit hasn't been updated since "
... | cb4fda8ab6c06d01ae01e6226d435d30cd0bd971 | 3,655,272 |
def COUNT(condition: pd.DataFrame, n: int):
"""the number of days fits the 'condition' in the past n days
Args:
condition (pd.DataFrame): dataframe index by date time(level 0) and asset(level 1), containing bool values
n (int): the number of past days
"""
return condition.rolling(n, ce... | ed380061249803e9c378950a88dc5162543cfee0 | 3,655,273 |
def Mat33_nrow():
"""Mat33_nrow() -> int"""
return _simbody.Mat33_nrow() | 7f22177bcf150458e6545ed204e47b3326ce6193 | 3,655,274 |
def isstruct(ob):
""" isstruct(ob)
Returns whether the given object is an SSDF struct.
"""
if hasattr(ob, '__is_ssdf_struct__'):
return bool(ob.__is_ssdf_struct__)
else:
return False | 465196af79c9de1f7685e0004e92b68a7f524149 | 3,655,275 |
def where_between(field_name, start_date, end_date):
"""
Return the bit of query for the dates interval.
"""
str = """ {0} between date_format('{1}', '%%Y-%%c-%%d %%H:%%i:%%S')
and date_format('{2}', '%%Y-%%c-%%d 23:%%i:%%S')
""" .format( field_name,
... | 4801d01ac8743f138e7c558da40518b75ca6daed | 3,655,276 |
def to_console_formatted_string(data: dict) -> str:
"""..."""
def make_line(key: str) -> str:
if key.startswith('__cauldron_'):
return ''
data_class = getattr(data[key], '__class__', data[key])
data_type = getattr(data_class, '__name__', type(data[key]))
value = '{... | 05cec50b3eee8199b19024aae32dda2a8ba33115 | 3,655,277 |
def cluster_instance_get_info_ajax(request, c_id):
"""
get cluster instance status
"""
dic = {"res": True, "info":None, "err":None}
instance_id = request.GET.get("instance_id")
require_vnc = request.GET.get("require_vnc")
if require_vnc == "true":
require_vnc = True
else:
require_vnc = False
if instance_id... | 1c000a659893b375a2e89faadedccde7ca8dcab6 | 3,655,278 |
import time
def timeit(verbose=False):
"""
Time functions via decoration. Optionally output time to stdout.
Parameters:
-----------
verbose : bool
Example Usage:
>>> @timeit(verbose=True)
>>> def foo(*args, **kwargs): pass
"""
def _timeit(f):
@wraps(f)
def wra... | 5e8e0441914b5d26db99fc378374bebde2d39376 | 3,655,279 |
def signal_period(peaks, sampling_rate=1000, desired_length=None,
interpolation_order="cubic"):
"""Calculate signal period from a series of peaks.
Parameters
----------
peaks : list, array, DataFrame, Series or dict
The samples at which the peaks occur. If an array is passed i... | dae9a7af6d23fdaa1f742cbc3b18649a525c4041 | 3,655,280 |
import google.cloud.dataflow as df
from google.cloud.dataflow.utils.options import PipelineOptions
def model_co_group_by_key_tuple(email_list, phone_list, output_path):
"""Applying a CoGroupByKey Transform to a tuple.
URL: https://cloud.google.com/dataflow/model/group-by-key
"""
p = df.Pipeline(options=Pipel... | 7256b9dac30fe731011729ea463e37b39d8c4dde | 3,655,281 |
def get_recommendation(anime_name, cosine_sim, clean_anime, anime_index):
"""
Getting pairwise similarity scores for all anime in the data frame.
The function returns the top 10 most similar anime to the given query.
"""
idx = anime_index[anime_name]
sim_scores = list(enumerate(cosine_sim[idx]))... | 93bc3e53071200810b34e31674fcaa0a98cdaebb | 3,655,282 |
def get_nwb_metadata(experiment_id):
"""
Collects metadata based on the experiment id and converts the weight to a float.
This is needed for further export to nwb_converter.
This function also validates, that all metadata is nwb compatible.
:param experiment_id: The experiment id given by the us... | 9882e71cb869e1ebf762fd851074d316b9fda462 | 3,655,283 |
from typing import Tuple
from typing import Union
def string_to_value_error_mark(string: str) -> Tuple[float, Union[float, None], str]:
"""
Convert string to float and error.
Parameters
----------
string : str
DESCRIPTION.
Returns
-------
value : float
Value.
erro... | c2c69c419d44e8342376ee24f6a4ced6ee2090e7 | 3,655,284 |
import itertools
def _children_with_tags(element, tags):
"""Returns child elements of the given element whose tag is in a given list.
Args:
element: an ElementTree.Element.
tags: a list of strings that are the tags to look for in child elements.
Returns:
an iterable of ElementTree.Element instance... | 522151e7e9ad355e5c6850cef62093e1bd4ed0a0 | 3,655,285 |
import logging
import collections
import functools
def train_and_eval():
"""Train and evaluate StackOver NWP task."""
logging.info('Show FLAGS for debugging:')
for f in HPARAM_FLAGS:
logging.info('%s=%s', f, FLAGS[f].value)
hparam_dict = collections.OrderedDict([
(name, FLAGS[name].value) for name ... | 807284651327ef29260ac2ce8ab753d40349a786 | 3,655,286 |
def align_with_known_width(val, width: int, lowerBitCntToAlign: int):
"""
Does same as :func:`~.align` just with the known width of val
"""
return val & (mask(width - lowerBitCntToAlign) << lowerBitCntToAlign) | 8c9b7ffd8fced07f2ca78db7665ea5425417e45a | 3,655,287 |
def get_email_from_request(request):
"""Use cpg-utils to extract user from already-authenticated request headers."""
user = get_user_from_headers(request.headers)
if not user:
raise web.HTTPForbidden(reason='Invalid authorization header')
return user | 60872f86bb69de6b1b339f715a2561dafd231489 | 3,655,288 |
from typing import List
from typing import Tuple
def get_kernels(params: List[Tuple[str, int, int, int, int]]) -> List[np.ndarray]:
"""
Create list of kernels
:param params: list of tuples with following format ("kernel name", angle, multiplier, rotation angle)
:return: list of kernels
"""
ker... | b39fd152fe94f4c52398ae4984414d2cefbf401f | 3,655,289 |
def forward_propagation(propagation_start_node, func, x):
"""A forward propagation starting at the `propagation_start_node` and
wrapping the all the composition operations along the way.
Parameters
----------
propagation_start_node : Node
The node where the gradient function (or anything si... | 12fbbb53fd329aacdf5f5fffbfa2a81342663fb8 | 3,655,290 |
import requests
def main():
"""
Main function of the script.
"""
args = parse_args()
if args.version:
print("{v}".format(v=__version__))
return 0
config = ConfigFile(args.config_file, CONFIG_FILE_SCHEMA)
if args.help_config:
print(config.help())
return 0... | bdbbb2d695a69a253aee2454128d9c098392bd57 | 3,655,291 |
def read_entities():
"""
find list of entities
:return:
"""
intents = Entity.objects.only('name','id')
return build_response.sent_json(intents.to_json()) | 842ec7506b49abd6557219e2c9682bdd48df86fb | 3,655,292 |
def available(unit, item) -> bool:
"""
If any hook reports false, then it is false
"""
for skill in unit.skills:
for component in skill.components:
if component.defines('available'):
if component.ignore_conditional or condition(skill, unit):
if not... | 7550a197e2d877ef4ff622d08a056be434f1f06e | 3,655,293 |
def cleanArray(arr):
"""Clean an array or list from unsupported objects for plotting.
Objects are replaced by None, which is then converted to NaN.
"""
try:
return np.asarray(arr, float)
except ValueError:
return np.array([x if isinstance(x, number_types) else None
... | 7ab7d645209ad0815a3eb831a1345cdad0ae4aba | 3,655,294 |
import argparse
def parse_args():
"""Main function for parsing args. Utilizes the 'check_config'
function from the config module to ensure an API key has been
passed. If not, user is prompted to conduct initial configuration
for pwea.
If a valid configuration is found (there is currently no valid... | ebac086d48fad3ec8a8c715c9d75acb1ac1e5e24 | 3,655,295 |
def _ensure_args(G, source, method, directed,
return_predecessors, unweighted, overwrite, indices):
"""
Ensures the args passed in are usable for the API api_name and returns the
args with proper defaults if not specified, or raises TypeError or
ValueError if incorrectly specified.
... | 6d9168de0d25f5ee4d720347182763ad744600a6 | 3,655,296 |
def read_siemens_scil_b0():
""" Load Siemens 1.5T b0 image form the scil b0 dataset.
Returns
-------
img : obj,
Nifti1Image
"""
file = pjoin(dipy_home,
'datasets_multi-site_all_companies',
'1.5T',
'Siemens',
'b0.nii.gz'... | edf700fc6e14a35b5741e4419ba96cb753188da8 | 3,655,297 |
def gdpcleaner(gdpdata: pd.DataFrame):
"""
Author: Gabe Fairbrother
Remove spurious columns, Rename relevant columns, Remove NaNs
Parameters
----------
gdpdata: DataFrame
a loaded dataframe based on a downloaded Open Government GDP at basic prices dataset (https://open.canada.ca/en/open... | 4c685a244a746f05fbef5216518e23a956ae8da7 | 3,655,298 |
import re
def sort_with_num(path):
"""Extract leading numbers in a file name for numerical sorting."""
fname = path.name
nums = re.match('^\d+', fname)
if nums:
return int(nums[0])
else:
return 0 | 2209384720c33b8201c06f7a14b431972712814a | 3,655,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.