content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def uploadResourceFileUsingSession(url, session, resourceName, fileName, fullPath, scannerId):
"""
upload a file for the resource - e.g. a custom lineage csv file
works with either csv for zip files (.csv|.zip)
returns rc=200 (valid) & other rc's from the post
"""
print(
"uploading fi... | 8a4a8c21563f1467db284f2e98dd1b48dbb65a3c | 3,639,145 |
from typing import Literal
def read_inc_stmt(line: str) -> tuple[Literal["inc"], str] | None:
"""Attempt to read INCLUDE statement"""
inc_match = FRegex.INCLUDE.match(line)
if inc_match is None:
return None
inc_path: str = inc_match.group(1)
return "inc", inc_path | 64ac4b53363a4aa5b9e2c4cf91b27f169ad0465c | 3,639,146 |
def sent2vec(s, model):
"""
Transform a sentence to a vector.
Pre: No parameters may be None.
Args:
s: The sentence to transform.
model: A word2vec model.
Returns: A vector, representing the given sentence.
"""
words = word_tokenize(s.lower())
# Stopwords and numbers m... | 1e61639cc27e3a430257ff3ac4b2a002a42cf177 | 3,639,148 |
def subnet_group_present(
name,
subnet_ids=None,
subnet_names=None,
description=None,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Ensure ElastiCache subnet group exists.
.. versionadded:: 2015.8.0
name
The name for the ElastiCache subn... | d7d441dcfacd92f33b4172e33299df398cfa3ba2 | 3,639,149 |
def GetTensorFlowVersion(vm):
"""Returns the version of tensorflow installed on the vm.
Args:
vm: the target vm on which to check the tensorflow version
Returns:
installed python tensorflow version as a string
"""
stdout, _ = vm.RemoteCommand(
('echo -e "import tensorflow\nprint(tensorflow.__v... | 4380ec75f2b5713ab0ead31189cdd7b3f81c6b9b | 3,639,150 |
import json
from typing import OrderedDict
def datetime_column_evrs():
"""hand-crafted EVRS for datetime columns"""
with open(
file_relative_path(__file__, "../fixtures/datetime_column_evrs.json")
) as infile:
return expectationSuiteValidationResultSchema.load(
json.load(infile... | c229f08250c51a805a15db653e3e70513a6f6e9a | 3,639,152 |
def pd_df_timeseries():
"""Create a pandas dataframe for testing, with timeseries in one column"""
return pd.DataFrame(
{
"time": pd.date_range(start="1/1/2018", periods=100),
"A": np.random.randint(0, 100, size=100),
}
) | 9b6b217e2a4bc80b5f54cecf56c55d5fb229d288 | 3,639,154 |
from typing import Union
def n_tokens(doc: Union[Doc, Span]):
"""Return number of words in the document."""
return len(doc._._filtered_tokens) | 4b1f1cbb9cb6baf5cb70d6bd38a88d3e0e54610a | 3,639,155 |
def getJobs(numJobs=1):
"""
Return a list of dictionary data as provided to the plugin `submit` method
"""
job = {'allowOpportunistic': False,
'bulkid': None,
'cache_dir': TEST_DIR + '/JobCollection_1_0/job_1',
'estimatedDiskUsage': 5000000,
'estimatedJobTime'... | 56543a5a6ef66ec7fdf9f3ef26594eafa3f7bb41 | 3,639,156 |
def create_test_user():
"""Creates a new user with random username for testing
If two randomly assigned usernames overlap, it will fail
"""
UserModel = get_user_model()
username = '%s_%s' % ('test', uuid4().get_hex()[:10],)
user = UserModel.objects.create(username=username)
return user | d20ecbdb07db886a526402c09d7d14d768329c2b | 3,639,157 |
def make_logical_or_tests(options):
"""Make a set of tests to do logical_or."""
return _make_logical_tests(tf.logical_or)(options, expected_tf_failures=1) | b4c7f5c0d89139938881f7301930651c9a3e7d0a | 3,639,158 |
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
:param key:
:param values:
:return:
"""
return [min(values)-max(values), (max(key)-min(key))/3, min(values)] | 908868b150340b02ba61fcc6ccf5937ba31bfe30 | 3,639,159 |
from datetime import datetime
import time
def add_metadata_values_to_record(record_message, schema_message):
"""Populate metadata _sdc columns from incoming record message
The location of the required attributes are fixed in the stream
"""
extended_record = record_message['record']
extended_record... | e85e2620b816907204443af1c014ca4d927cb20c | 3,639,160 |
from datetime import datetime
def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):
"""
This function is used to alter the reservation beeing build inside
a cookie. This function automatically crafts the required response.
"""
js_string: str = ""
r: GroupReservati... | f93b8e2ed68daebdf04aa15898e52f41a5df1e49 | 3,639,161 |
def _dense_to_sparse(data):
"""Convert a numpy array to a tf.SparseTensor."""
indices = np.where(data)
return tf.SparseTensor(
np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) | b1fe24dd82eff2aa31e40f6b86e75f655e7141c7 | 3,639,162 |
def getflookup(facetid):
"""
find out if a facet with this id has been saved to the facet_files table
"""
found = FacetLookup.objects.all().values_list('graphdb', flat=True).get(id=facetid)
if found:
return True
else:
return False | a1c6b0ec7e8ab96eef16574e64ac1948f0fa8419 | 3,639,163 |
def numeric_to_string(year):
"""
Convert numeric year to string
"""
if year < 0 :
yearstring = "{}BC".format(year*-1)
elif year >= 0:
yearstring = "{}AD".format(year)
else:
raise
return yearstring | 3469e2dd5e05c49b4861782da2dd88bac781c61d | 3,639,164 |
def _get_num_ve_sve_and_max_num_cells(cell_fracs):
"""
Calculate the num_ve, num_sve and max_num_cells
Parameters
----------
cell_fracs : structured array, optional
A sorted, one dimensional array,
each entry containing the following fields:
:idx: int
Th... | c0d154898bbfeafd66d89a2741dda8c2aa885a9a | 3,639,165 |
from datetime import datetime
def is_void(at):
"""Returns True if the given object is an ``adatetime`` with all of its
attributes equal to None.
"""
if isinstance(at, datetime):
return False
return all((getattr(at, attr) is None) for attr in adatetime.units) | 49744c361177060b508d5537a1ace16da6aef37d | 3,639,166 |
def _get_metric_fn(params):
"""Get the metrix fn used by model compile."""
batch_size = params["batch_size"]
def metric_fn(y_true, y_pred):
"""Returns the in_top_k metric."""
softmax_logits = y_pred
logits = tf.slice(softmax_logits, [0, 1], [batch_size, 1])
# The dup mask should be obtained from... | 2793975542241f36850aaaaef4256aa59ea4873f | 3,639,167 |
def check():
"""Check if all required modules are present.
Returns 0 on success, non-zero on error.
"""
flag = 0
for package in import_list:
try:
exec( "import " + package )
except Exception:
log.error( "Missing module: %s", package )
flag = True
... | 027ae4346a642740ca4b1ef4ebec5a831688f850 | 3,639,168 |
def flip_nums(text):
""" flips numbers on string to the end (so 2019_est --> est_2019)"""
if not text:
return ''
i = 0
s = text + '_'
while text[i].isnumeric():
s += text[i]
i += 1
if text[i] == '_':
i += 1
return s[i:] | e0534e25e95b72e1d6516111413e32a6dae207ef | 3,639,169 |
def nnls(A, b, k=None, maxiter=None):
"""
Compute the least-squares solution to the equation ``A @ x = b`` subject to
the nonnegativity constraints ``x[:k] >= 0``.
Parameters
----------
A : array_like, shape (m, n)
Matrix `A` as shown above.
b : array_like, shape (m,)
Right-... | 4d6c7e7d53e570222b752c4bf2013100c15b7297 | 3,639,170 |
def extent2(texture):
""" Returns the extent of the image data (0.0-1.0, 0.0-1.0) inside its texture owner.
Textures have a size power of 2 (512, 1024, ...), but the actual image can be smaller.
For example: a 400x250 image will be loaded in a 512x256 texture.
Its extent is (0.78, 0.98), the... | 16c6d220ad48201fd133ed11c97452bf0831c0d8 | 3,639,173 |
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
# Store the total length of the hand
hand_len = 0
# For every letter in the hand
for key in hand.keys():
# Add the number of... | 297f8af5943bf87bb7999a1212d54430857de12b | 3,639,174 |
def add_fieldmap(fieldmap: BIDSFile, layout: BIDSLayout) -> dict:
"""
Locates fieldmap-related json file and adds them in an appropriate dictionary with keys that describe their directionality
Parameters
----------
fieldmap : BIDSFile
Fieldmap's NIfTI
layout : BIDSLayout
BIDSLay... | 227fa27d9ecb2f260700debc6b2837d60018bd61 | 3,639,175 |
def fit_plane_lstsq(XYZ):
"""
Fits a plane to a point cloud.
Where z=a.x+b.y+c; Rearranging: a.x+b.y-z+c=0
@type XYZ: list
@param XYZ: list of points
@rtype: np.array
@return: normalized normal vector of the plane in the form C{(a,b,-1)}
"""
[rows, cols] = XYZ.shape
G = np.ones(... | c734cb17462e72c40bb65464c42d298c21e4a922 | 3,639,176 |
def clean_name(name: str) -> str:
"""Clean a string by capitalizing and removing extra spaces.
Args:
name: the name to be cleaned
Returns:
str: the cleaned name
"""
name = " ".join(name.strip().split())
return str(titlecase.titlecase(name)) | e19354767d38164004c984c76827b2882ef4c4fd | 3,639,177 |
from typing import Callable
from re import T
from typing import List
def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]:
"""
Pull a list of items.
"""
items = []
with pull_block(buf, capacity) as length:
end = buf.tell() + length
while buf.tell() < end:
... | ab9833fdab157e05df00d65dee96080c98140bb2 | 3,639,178 |
def ResNet(
stack_fn, preact, use_bias, model_name='resnet', include_top=True, weights='imagenet',
input_tensor=None, input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', bottomright_maxpool_test=False,
use_group_norm=False, **kwargs):
"""Instantiates the Re... | 810b04481eb6ad5d8b3723b87581b3f2136cc80f | 3,639,179 |
import yaml
def read_yaml(yaml_path):
"""
Read yaml file from the path
:param yaml_path:
:return:
"""
stream = open(yaml_path, "r")
docs = yaml.load_all(stream)
result = dict()
for doc in docs:
for k, v in doc.items():
result[k] = v
return result | a3f32d6f5c6cb5c8e94ad9b68a0540aa001f83b2 | 3,639,180 |
def _server_allow_run_on_save() -> bool:
"""Allows users to automatically rerun when app is updated.
Default: true
"""
return True | 3a895abd8201ce97c8f2f928b841eb86bf6327d1 | 3,639,181 |
def _strip_schema(url):
"""Returns the url without the s3:// part"""
result = urlparse(url)
return result.netloc + result.path | 9e7dc96c23d799f202603109cd08b2fe049951a5 | 3,639,182 |
def simple_word_tokenize(text, _split=GROUPING_SPACE_REGEX.split):
"""
Split text into tokens. Don't split by a hyphen.
Preserve punctuation, but not whitespaces.
"""
return [t for t in _split(text) if t and not t.isspace()] | 5b9e66d2a369340028b4ece2eee083511d0e9746 | 3,639,183 |
def merge_strategy(media_identifier, target_site, sdc_data, strategy):
"""
Check if the file already holds Structured Data, if so resolve what to do.
@param media_identifier: Mid of the file
@param target_site: pywikibot.Site object to which file should be uploaded
@param sdc_data: internally forma... | 0e59cc312e00cc7d492bfe725b0a9a297734a5e0 | 3,639,184 |
def convert_translations_to_dict(js_translations):
"""Convert a GNUTranslations object into a dict for jsonifying.
Args:
js_translations: GNUTranslations object to be converted.
Returns:
A dictionary representing the GNUTranslations object.
"""
plural, n_plural = _get_plural_forms(... | 8db0fc022002504a943f46b429ca71b6e0e90b06 | 3,639,185 |
import asyncio
def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
"""
Apply function of two arguments cumulatively to the items of sequence,
from left to right, so as to reduce the sequence to a single value.
Reduction will be executed sequentially without concurrency,
... | 64b55a082df11fa9d6b7971ecd1508c1e4c9f1c9 | 3,639,186 |
def sigm_temp(base_sim_param, assumptions, t_base_type):
"""Calculate base temperature depending on sigmoid diff and location
Parameters
----------
base_sim_param : dict
Base simulation assumptions
assumptions : dict
Dictionary with assumptions
Return
------
t_base_cy :... | 276af880050698a9f15dcd142aac952809807fdb | 3,639,187 |
import select
import socket
def is_socket_closed(sock):
"""Check if socket ``sock`` is closed."""
if not sock:
return True
try:
if not poll: # pragma nocover
if not select:
return False
try:
return bool(select([sock], [], [], 0.0)[... | e89ddec6e7603b5636f6a6d87831d12f0a76e9d9 | 3,639,188 |
def _fit_ovo_binary(estimator, X, y, i, j):
"""Fit a single binary estimator (one-vs-one)."""
cond = np.logical_or(y == i, y == j)
y = y[cond]
y_binary = np.empty(y.shape, np.int)
y_binary[y == i] = 0
y_binary[y == j] = 1
ind = np.arange(X.shape[0])
return _fit_binary(estimator, X[ind[co... | 59325562549656d35b615a3274112357b0c4854c | 3,639,189 |
def get_implicit_permissions_for_user(user: str, domain=None):
"""
GetImplicitPermissionsForUser gets implicit permissions for a user or role.
Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles.
For example:
p, admin, data1, read
p, alice, data2, re... | 08477a3ac772597f66f36b7b04fc7d8a29f2522b | 3,639,190 |
def Law_f(text):
"""
:param text: The "text" of this Law
"""
return '\\begin{block}{Law}\n' + text + '\n\\end{block}\n' | 594b279c5971a9d379666179c4d0633fc02a8bd9 | 3,639,191 |
import operator
from typing import OrderedDict
def ordered_dict_intersection(first_dict, second_dict, compat=operator.eq):
"""Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
... | cfef1a1d5c3cc9fc5b792a68bae0fe8279b752da | 3,639,192 |
import scipy
def get_cl2cf_matrices(theta_bin_edges, lmin, lmax):
"""
Returns the set of matrices to go from one entire power spectrum to one binned correlation function.
Args:
theta_bin_edges (1D numpy array): Angular bin edges in radians.
lmin (int): Minimum l.
lmax (int): Maxim... | 0231218c8501409e3660ed6c446b0c163229ab8a | 3,639,193 |
from operator import concat
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
"""
Frame a time series as a supervised learning dataset.
Arguments:
data: Sequence of observations as a list or NumPy array.
n_in: Number of lag observations as input (X).
n_out: Number of o... | 1756380140dd74045880cc4501623c8b48ce5773 | 3,639,194 |
import torch
def valid_from_done(done):
"""Returns a float mask which is zero for all time-steps after a
`done=True` is signaled. This function operates on the leading dimension
of `done`, assumed to correspond to time [T,...], other dimensions are
preserved."""
done = done.type(torch.float)
... | 0ca2bd0f9e23605091b2f8d1bc15e67e1632b82b | 3,639,195 |
import logging
def get_transfer_options(transfer_kind='upload', transfer_method=None):
"""Returns hostnames that the current host can upload or download to.
transfer_kind: 'upload' or 'download'
transfer_method: is specified and not None, return only hosts with which
we can work using... | f5aea7498bf98d3be3fe9e97eda4e6eaa9181cea | 3,639,196 |
def calc_utility_np(game, iter):
"""Calc utility of current position
Parameters
----------
game : camel up game
Camel up game class
iter : int
Iterations to run the monte carlo simulations
Returns
-------
np.array
Numpy structured array with expected utilities
... | c69740652ea18d753c9a2a894f1ba36ab1eecff8 | 3,639,197 |
def add_masses(line, mass_light, mass_heavy):
"""
Add m/z information in the output lines
"""
new_line = "{} {} {}\n".format(round_masses(mass_light), round_masses(mass_heavy), line)
return new_line | d8e92acf43d17e9a00de1e985e6cecadec0fa4b4 | 3,639,198 |
def load_r_ind_sent_bars():
"""
Loads the random index-barcodes of the actual networks
"""
bars = []
for text in texts:
bars.append(np.load('Textbooks/{}/r_ind_sent_bars.npy'.format(text)))
return bars | 331b217976bc5a03a4e3a20331f06ba33a7aaad1 | 3,639,199 |
import pickle
def load_pickle(indices, image_data):
""""
0: Empty
1: Active
2: Inactive
"""
size = 13
# image_data = "./data/images.pkl"
with open(image_data, "rb") as f:
images = pickle.load(f)
x = []
y = []
n = []
cds = []
for idx in indices:
D... | dff3eeb151c8f32511c8d62d8bc9fa313bc36019 | 3,639,200 |
def summarize_vref_locs(locs:TList[BaseObjLocation]) -> pd.DataFrame:
"""
Return a table with cols (partition, num vrefs)
"""
vrefs_by_partition = group_like(objs=locs, labels=[loc.partition for loc in locs])
partition_sort = sorted(vrefs_by_partition)
return pd.DataFrame({
'Partition': ... | 3894404874004e70ab0cc243af4f645f5cf84582 | 3,639,201 |
def rescale_list_to_range(original, limits):
"""
Linearly rescale values in original list to limits (minimum and maximum).
:example:
>>> rescale_list_to_range([1, 2, 3], (0, 10))
[0.0, 5.0, 10.0]
>>> rescale_list_to_range([1, 2, 3], (-10, 0))
[-10.0, -5.0, 0.0]
>>> rescale_list_to_rang... | bdd38bb24b597648e4ca9045ed133dfe93ad4bd8 | 3,639,202 |
from typing import Optional
from typing import Union
from typing import Mapping
def build_list_request(
filters: Optional[dict[str, str]] = None
) -> Union[IssueListInvalidRequest, IssueListValidRequest]:
"""Create request from filters."""
accepted_filters = ["obj__eq", "state__eq", "title__contains"]
... | b0fc85921f11ef28071eba8be4ab1a7a4837b56c | 3,639,203 |
def get_ratings(labeled_df):
"""Returns list of possible ratings."""
return labeled_df.RATING.unique() | 2b88b1703ad5b5b0a074ed7bc4591f0e88d97f92 | 3,639,204 |
from typing import Dict
def split_edge_cost(
edge_cost: EdgeFunction, to_split: LookupToSplit
) -> Dict[Edge, float]:
"""Assign half the cost of the original edge to each of the split edges.
Args:
edge_cost: Lookup from edges to cost.
to_split: Lookup from original edges to pairs of split... | 8e307f6dfd19d65ec1979fa0eafef05737413b3d | 3,639,205 |
def get_ants_brain(filepath, metadata, channel=0):
"""Load .nii brain file as ANTs image."""
nib_brain = np.asanyarray(nib.load(filepath).dataobj).astype('uint32')
spacing = [float(metadata.get('micronsPerPixel_XAxis', 0)),
float(metadata.get('micronsPerPixel_YAxis', 0)),
float... | 5011d1f609d818c1769900542bc07b8194a4a10f | 3,639,206 |
def numpy_max(x):
"""
Returns the maximum of an array.
Deals with text as well.
"""
return numpy_min_max(x, lambda x: x.max(), minmax=True) | 0b32936cde2e0f6cbebf62016c30e4265aba8b57 | 3,639,207 |
import copy
def get_train_val_test_splits(X, y, max_points, seed, confusion, seed_batch,
split=(2./3, 1./6, 1./6)):
"""Return training, validation, and test splits for X and y.
Args:
X: features
y: targets
max_points: # of points to use when creating splits.
seed: se... | 3f76dade9dd012666f29742b3ec3749d9bcfafe2 | 3,639,208 |
def require_apikey(key):
"""
Decorator for view functions and API requests. Requires
that the user pass in the API key for the application.
"""
def _wrapped_func(view_func):
def _decorated_func(*args, **kwargs):
passed_key = request.args.get('key', None)
if passed_ke... | 9db9be28c18cd84172dce27d27be9bfcc6f7376e | 3,639,209 |
from math import cos,pi
from numpy import zeros
def gauss_legendre(ordergl,tol=10e-14):
"""
Returns nodal abscissas {x} and weights {A} of
Gauss-Legendre m-point quadrature.
"""
m = ordergl + 1
def legendre(t,m):
p0 = 1.0; p1 = t
for k in range(1,m):
p = ((2.0*k + ... | 5353373ee59cd559817a737271b4ff89cc031709 | 3,639,210 |
def simple_message(msg, parent=None, title=None):
"""
create a simple message dialog with string msg. Optionally set
the parent widget and dialog title
"""
dialog = gtk.MessageDialog(
parent = None,
type = gtk.MESSAGE_INFO,
buttons = gtk.BUTTONS_OK,
... | c6b021a4345f51f58fdf530441596001843b0506 | 3,639,211 |
def accept(value):
"""Accept header class and method decorator."""
def accept_decorator(t):
set_decor(t, 'header', CaseInsensitiveDict({'Accept': value}))
return t
return accept_decorator | f7b392c2b9ab3024e96856cbcda9752a9076ea73 | 3,639,212 |
from pathlib import Path
def screenshot(widget, path=None, dir=None):
"""Save a screenshot of a Qt widget to a PNG file.
By default, the screenshots are saved in `~/.phy/screenshots/`.
Parameters
----------
widget : Qt widget
Any widget to capture (including OpenGL widgets).
path : ... | dbb221f25f1b2dbe4b439afda225c452692b24fb | 3,639,213 |
def xyz_to_rtp(x, y, z):
"""
Convert 1-D Cartesian (x, y, z) coords. to 3-D spherical coords.
(r, theta, phi).
The z-coord. is assumed to be anti-parallel to the r-coord. when
theta = 0.
"""
# First establish 3-D versions of x, y, z
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
... | db8fbcb50cde2c529fe94e546b0caaea79327df6 | 3,639,214 |
import re
def irccat_targets(bot, targets):
"""
Go through our potential targets and place them in an array so we can
easily loop through them when sending messages.
"""
result = []
for s in targets.split(','):
if re.search('^@', s):
result.append(re.sub('^@', '', s))
... | b7dce597fc301930aae665c338a9e9ada5f2be7e | 3,639,215 |
import struct
def _watchos_stub_partial_impl(
*,
ctx,
actions,
binary_artifact,
label_name,
watch_application):
"""Implementation for the watchOS stub processing partial."""
bundle_files = []
providers = []
if binary_artifact:
# Create intermedi... | dd4342893eb933572262a3b3bd242112c1737b3b | 3,639,216 |
def catMullRomFit(p, nPoints=100):
"""
Return as smoothed path from a list of QPointF objects p, interpolating points if needed.
This function takes a set of points and fits a CatMullRom Spline to the data. It then
interpolates the set of points and outputs a smoothed path with the desired ... | fb63e67b2bf9fd78e04436cd7f12d214bb6904c7 | 3,639,218 |
def pdf_from_ppf(quantiles, ppfs, edges):
"""
Reconstruct pdf from ppf and evaluate at desired points.
Parameters
----------
quantiles: numpy.ndarray, shape=(L)
L quantiles for which the ppf_values are known
ppfs: numpy.ndarray, shape=(1,...,L)
Corresponding ppf-values for all ... | 52c3d19ee915d1deeb99f39ce036deca59c536b3 | 3,639,219 |
import types
import re
def get_arg_text(ob):
"""Get a string describing the arguments for the given object"""
arg_text = ""
if ob is not None:
arg_offset = 0
if type(ob) in (types.ClassType, types.TypeType):
# Look for the highest __init__ in the class chain.
fob = ... | 5dc6d262dfe7e10a5ba93fd26c49a0d6bae3bb37 | 3,639,220 |
import random
def create_ses_weights(d, ses_col, covs, p_high_ses, use_propensity_scores):
"""
Used for training preferentially on high or low SES people. If use_propensity_scores is True, uses propensity score matching on covs.
Note: this samples from individual images, not from individual people. I thi... | de5b401ef1419d61664c565f5572d3dd80c6fdfb | 3,639,221 |
def decoder_g(zxs):
"""Define decoder."""
with tf.variable_scope('decoder', reuse=tf.AUTO_REUSE):
hidden_layer = zxs
for i, n_hidden_units in enumerate(FLAGS.n_hidden_units_g):
hidden_layer = tf.layers.dense(
hidden_layer,
n_hidden_units,
activation=tf.nn.relu,
... | 6974624dccecae7bbb5f650f0ebe0c819df4aa67 | 3,639,223 |
def make_evinfo_str(json_str):
"""
[メソッド概要]
DB登録用にイベント情報を文字列に整形
"""
evinfo_str = ''
for v in json_str[EventsRequestCommon.KEY_EVENTINFO]:
if evinfo_str:
evinfo_str += ','
if not isinstance(v, list):
evinfo_str += '"%s"' % (v)
else:
... | 6717652f1adf227b03864f8b4b4268524eb7cbc4 | 3,639,224 |
def parse_cisa_data(parse_file: str) -> object:
"""Parse the CISA Known Exploited Vulnerabilities file and create a new dataframe."""
inform("Parsing results")
# Now parse CSV using pandas, GUID is CVE-ID
new_dataframe = pd.read_csv(parse_file, parse_dates=['dueDate', 'dateAdded'])
# extend datafra... | 7bc95a4d60b869395f20d8619f80b116156de4ad | 3,639,225 |
def camera():
"""Video streaming home page."""
return render_template('index.html') | 75c501daa3d9a8b0090a0e9174b29a0b848057be | 3,639,226 |
import tqdm
def fit_alternative(model, dataloader, optimizer, train_data, labelled=True):
"""
fit method using alternative loss, executes one epoch
:param model: VAE model to train
:param dataloader: input dataloader to fatch batches
:param optimizer: which optimizer to utilize
:param train_da... | 3889d2d72ce71095d3016427c87795ef65aa9fa4 | 3,639,228 |
def FlagOverrider(**flag_kwargs):
"""A Helpful decorator which can switch the flag values temporarily."""
return flagsaver.flagsaver(**flag_kwargs) | 39a39b1884c246ae45d8166c2eae9bb68dea2c70 | 3,639,229 |
def cli(ctx, path, max_depth=1):
"""List files available from a remote repository for a local path as a tree
Output:
None
"""
return ctx.gi.file.tree(path, max_depth=max_depth) | 4be4fdffce7862332aa27a40ee684aae31fd67b5 | 3,639,230 |
def warp_p(binary_img):
"""
Warps binary_image using hard coded source and destination
vertices. Returns warped binary image, warp matrix and
inverse matrix.
"""
src = np.float32([[580, 450],
[180, 720],
[1120, 720],
[700, ... | ea0ca98138ff9fbf52201186270c3d2561f57ec2 | 3,639,231 |
def _get_xml_sps(document):
"""
Download XML file and instantiate a `SPS_Package`
Parameters
----------
document : opac_schema.v1.models.Article
Returns
-------
dsm.data.sps_package.SPS_Package
"""
# download XML file
content = reqs.requests_get_content(document.xml)
x... | 908ceb96ca2b524899435f269e60ddd9b7db3f0c | 3,639,232 |
def plot_confusion_matrix(ax, y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
From scikit-learn example:
https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
... | ba88d9f96f9b9da92987fa3df4d38270162fc903 | 3,639,233 |
def _in_docker():
""" Returns: True if running in a Docker container, else False """
with open('/proc/1/cgroup', 'rt') as ifh:
if 'docker' in ifh.read():
print('in docker, skipping benchmark')
return True
return False | 4a0fbd26c5d52c5fe282b82bc4fe14986f8aef4f | 3,639,234 |
def asPosition(flags):
""" Translate a directional flag from an actions into a tuple indicating
the targeted tile. If no directional flag is found in the inputs,
returns (0, 0).
"""
if flags & NORTH:
return 0, 1
elif flags & SOUTH:
return 0, -1
elif flags & EAST:
... | 9e1b2957b1cd8b71033b644684046e71e85f5105 | 3,639,235 |
from nibabel import load
import numpy as np
def pickvol(filenames, fileidx, which):
"""Retrieve index of named volume
Parameters
----------
filenames: list of 4D file names
fileidx: which 4D file to look at
which: 'first' or 'middle'
Returns
-------
idx: index of first or middle ... | 7090ab35959289c221b6baab0ba1719f0c518ef4 | 3,639,236 |
def merge(d, **kwargs):
"""Recursively merges given kwargs int to a
dict - only if the values are not None.
"""
for key, value in kwargs.items():
if isinstance(value, dict):
d[key] = merge(d.get(key, {}), **value)
elif value is not None:
d[key] = value
return ... | 168cc66cce0a04b086a17089ebcadc16fbb4c1d0 | 3,639,237 |
def init_config_flow(hass):
"""Init a configuration flow."""
flow = config_flow.VelbusConfigFlow()
flow.hass = hass
return flow | 6eccc23ceca6b08268701486ed2e79c47c220e13 | 3,639,238 |
from typing import Dict
from datetime import datetime
from typing import FrozenSet
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]:
"""Find all service identifiers by date"""
feed = load_raw_feed(path)
return _service_ids_by_date(feed) | 60e39ccb517f00243db97835b223e894c9f64540 | 3,639,239 |
def get_all_services(org_id: str) -> tuple:
"""
**public_services_api**
returns a service governed by organization_id and service_id
:param org_id:
:return:
"""
return services_view.return_services(organization_id=org_id) | d779e7312d363ad507c994c38ba844912bf49e9c | 3,639,240 |
def get_initializer(initializer_range=0.02):
"""Creates a `tf.initializers.truncated_normal` with the given range.
Args:
initializer_range: float, initializer range for stddev.
Returns:
TruncatedNormal initializer with stddev = `initializer_range`.
"""
return tf.keras.initializers... | fa6aca01bd96c6cb97af5e68f4221d285e482612 | 3,639,241 |
import math
def findh_s0(h_max, h_min, q):
"""
Znajduje siłę naciągu metodą numeryczną (wykorzystana metoda bisekcji),
należy podać granice górną i dolną dla metody bisekcji
:param h_max: Górna granica dla szukania siły naciągu
:param h_min: Dolna granica dla szukania siły naciągu
:param q: c... | 28926742c6d786ffa47a084a318f54fafb3da98c | 3,639,242 |
def velocity_dependent_covariance(vel):
"""
This function computes the noise in the velocity channel.
The noise generated is gaussian centered around 0, with sd = a + b*v;
where a = 0.01; b = 0.05 (Vul, Frank, Tenenbaum, Alvarez 2009)
:param vel:
:return: covariance
"""
cov = []
for... | 4a1bb6c8f6c5956585bd6f5a09f4d80ee397bbe5 | 3,639,243 |
def msd_Correlation(allX):
"""Autocorrelation part of MSD."""
M = allX.shape[0]
# numpy with MKL (i.e. intelpython distribution), the fft wont be
# accelerated unless axis along 0 or -1
# perform FT along n_frame axis
# (n_frams, n_particles, n_dim) -> (n_frames_Ft, n_particles, n_dim)
allFX... | c212e216d32814f70ab861d066c8000cf7e8e238 | 3,639,245 |
import math
def convert_table_value(fuel_usage_value):
"""
The graph is a little skewed, so this prepares the data for that.
0 = 0
1 = 25%
2 = 50%
3 = 100%
4 = 200%
5 = 400%
6 = 800%
7 = 1600% (not shown)
Intermediate values scale between those values. (5.5 is 600%)
"... | 15e4deedb4809eddd830f7d586b63075b71568ef | 3,639,246 |
import TestWin
def FindMSBuildInstallation(msvs_version = 'auto'):
"""Returns path to MSBuild for msvs_version or latest available.
Looks in the registry to find install location of MSBuild.
MSBuild before v4.0 will not build c++ projects, so only use newer versions.
"""
registry = TestWin.Registry()
ms... | daf5151c08e52b71110075b3dd59071a3a6f124f | 3,639,247 |
def create_toc_xhtml(metadata: WorkMetadata, spine: list[Matter]) -> str:
"""
Load the default `toc.xhtml` file, and generate the required terms for the creative work. Return xhtml as a string.
Parameters
----------
metadata: WorkMetadata
All the terms for updating the work, not all com... | 9971d408f39056b6d2078e5157f2c39dbce8c202 | 3,639,248 |
def convertSLToNumzero(sl, min_sl=1e-3):
"""
Converts a (neg or pos) significance level to
a count of significant zeroes.
Parameters
----------
sl: float
Returns
-------
float
"""
if np.isnan(sl):
return 0
if sl < 0:
sl = min(sl, -min_sl)
num_zero = np.log10(-sl)
elif sl > 0:
... | c8cbea09904a7480e36529ffc7a62e6cdddc7a47 | 3,639,249 |
def calibrate_time_domain(power_spectrum, data_pkt):
"""
Return a list of the calibrated time domain data
:param list power_spectrum: spectral data of the time domain data
:param data_pkt: a RTSA VRT data packet
:type data_pkt: pyrf.vrt.DataPacket
:returns: a list containing the calibrated tim... | a4bfa279ac4ada5ffe6d7bd6e8cf64e59ae0bf61 | 3,639,250 |
def func(x):
"""
:param x: [b, 2]
:return:
"""
z = tf.math.sin(x[...,0]) + tf.math.sin(x[...,1])
return z | daf4e05c6a8c1f735842a0ef6fa115b14e85ef40 | 3,639,251 |
from typing import Tuple
from typing import Dict
from typing import Any
from typing import List
def parse_handler_input(handler_input: HandlerInput,
) -> Tuple[UserMessage, Dict[str, Any]]:
"""Parses the ASK-SDK HandlerInput into Slowbro UserMessage.
Returns the UserMessage object and... | 5be16af3f460de41af9e33cacc4ce94c447ceb45 | 3,639,252 |
def _validate_show_for_invoking_user_only(show_for_invoking_user_only):
"""
Validates the given `show_for_invoking_user_only` value.
Parameters
----------
show_for_invoking_user_only : `None` or `bool`
The `show_for_invoking_user_only` value to validate.
Returns
-------
show_fo... | a1f9612927dfc1423d027f242d759c982b11a8b8 | 3,639,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.