content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 contour_area_filter(image, kernel=(9,9), resize=1.0, uint_mode="scale",
min_area=100, min_area_factor=3, factor=3, **kwargs):
"""
Checks that a contour can be returned for two thresholds of the image, a
mean threshold and an otsu threshold.
Parameters
----------
imag... | 8f0a21210b714f85142a6f72e5d778cee8baf7ba | 3,639,217 |
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 |
import os
def vectors_intersect(vector_1_uri, vector_2_uri):
"""Take in two OGR vectors (we're assuming that they're in the same
projection) and test to see if their geometries intersect. Return True of
so, False if not.
vector_1_uri - a URI to an OGR vector
vector_2_uri - a URI to an OGR vector... | dbbf0bbfd91e8641ddf43b1d9eea4f732e9ade7a | 3,639,222 |
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 os
import shutil
def new_doc():
"""Creating a new document."""
if request.method == 'GET' or request.form.get('act') != 'create':
return render_template('new.html', title='New document', permalink=url_for('.new_doc'))
else:
slug = request.form['slug'].strip()
src = os.path.j... | f961076dda04d0a0d6c0c9f11dc8d29b373183a5 | 3,639,227 |
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 |
import os
def get_db_path():
"""Return the path to Dropbox's info.json file with user-settings."""
if os.name == 'posix': # OSX-specific
home_path = os.path.expanduser('~')
dbox_db_path = os.path.join(home_path, '.dropbox', 'info.json')
elif os.name == 'nt': # Windows-specific
h... | 04ee901faea224dde382a11b433f913557c7cb21 | 3,639,244 |
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 |
def test_db_transaction_n1(monkeypatch):
"""Raise _DB_TRANSACTION_ATTEMPTS OperationalErrors to force a reconnection.
A cursor for each SQL statement should be returned in the order
the statement were submitted.
0. The first statement execution produce no results _DB_TRANSACTION_ATTEMPTS times (Operat... | 4dcb32f14d8a938765f4fde5375b6b686a6a5f5c | 3,639,254 |
import requests
from datetime import datetime
def fetch_status():
"""
解析サイト<https://redive.estertion.win> からクラバト情報を取ってくる
return
----
```
{
"cb_start": datetime,
"cb_end": datetime,
"cb_days": int
}
```
"""
# クラバト開催情報取得
r = requests.get(
"htt... | 683c9fe84bf346a1cce703063da8683d3469ccc2 | 3,639,255 |
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post(uuid, tapi_path_computation_routing_constraint=None): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post
creates tapi.path.computation.RoutingConstraint # noqa: E501
:p... | 7d56e6a544b2ac720aa311127aa5db9b3153a0c3 | 3,639,256 |
def A004086(i: int) -> int:
"""Digit reversal of i."""
result = 0
while i > 0:
unit = i % 10
result = result * 10 + unit
i = i // 10
return result | b0a65b7e203b7a92f7d6a1846888798c369ac869 | 3,639,257 |
def should_raise_sequencingerror(wait, nrep, jump_to, goto, num_elms):
"""
Function to tell us whether a SequencingError should be raised
"""
if wait not in [0, 1]:
return True
if nrep not in range(0, 16384):
return True
if jump_to not in range(-1, num_elms+1):
return Tru... | fc7c4bdb29cd5b90faec59a4f6705b920304aae0 | 3,639,258 |
from typing import Optional
from typing import Mapping
import functools
def add_task_with_sentinels(
task_name: str,
num_sentinels: Optional[int] = 1):
"""Adds sentinels to the inputs/outputs of a task.
Adds num_sentinels sentinels to the end of 'inputs' and at the beginning
of 'targets'. This is known... | 2d040f37d4346770e836c5a8b71b90c1acce9d1d | 3,639,259 |
import sys
def to_routing_header(params):
"""Returns a routing header string for the given request parameters.
Args:
params (Mapping[str, Any]): A dictionary containing the request
parameters used for routing.
Returns:
str: The routing header string.
"""
if sys.versio... | 654118e165c95c2c541e969a5a1d9cbc87e86bea | 3,639,260 |
def mk_llfdi(data_id, data): # measurement group 10
"""
transforms a k-llfdi.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json... | 42717f4d182b3df60e27f213c36278c894597ded | 3,639,261 |
def valid_distro(x):
"""
Validates that arg is a Distro type, and has
:param x:
:return:
"""
if not isinstance(x, Distro):
return False
result = True
for required in ["arch", "variant"]:
val = getattr(x, required)
if not isinstance(val, str):
result =... | 8fc68700a4d024b7ba756c186225ef22622db584 | 3,639,262 |
import time
import os
def validate(dataloader,
model,
criterion,
total_batches,
debug_steps=100,
local_logger=None,
master_logger=None,
save='./'):
"""Validation for the whole dataset
Args:
dataloader: paddle.io... | cf879823f6051a4f758c145cf2c060a296302f03 | 3,639,263 |
def encode(message):
"""
Кодирует строку в соответсвие с таблицей азбуки Морзе
>>> encode('MAI-PYTHON-2020') # doctest: +SKIP
'-- .- .. -....-
.--. -.-- - .... --- -. -....-
..--- ----- ..--- -----'
>>> encode('SOS')
'...
---
...'
>>> encode('МАИ-ПИТОН-2020') # doctest: +ELLI... | efa312c510738f89608af0febff3435b17235eb8 | 3,639,264 |
def get_group_to_elasticsearch_processor():
"""
This processor adds users from xform submissions that come in to the User Index if they don't exist in HQ
"""
return ElasticProcessor(
elasticsearch=get_es_new(),
index_info=GROUP_INDEX_INFO,
) | 12e9371282298c96968263e76d1d02848fc5dcb3 | 3,639,265 |
import torch
def loss_function(recon_x, x, mu, logvar, flattened_image_size = 1024):
"""
from https://github.com/pytorch/examples/blob/master/vae/main.py
"""
BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, flattened_image_size), reduction='sum')
# see Appendix B from VAE paper:
... | 73abe5c0944f646b4c9240fdb80e17cabf83a22d | 3,639,266 |
def remove_poly(values, poly_fit=0):
"""
Calculates best fit polynomial and removes it from the record
"""
x = np.linspace(0, 1.0, len(values))
cofs = np.polyfit(x, values, poly_fit)
y_cor = 0 * x
for co in range(len(cofs)):
mods = x ** (poly_fit - co)
y_cor += cofs[co] * mo... | 3699dcd3cae6021a5f2a0b4cad08882a4383d09c | 3,639,267 |
def generate_per_host_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id):
"""Generates infeed enqueue ops for per-host input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
hooks = []
with ops.device(device):
user_context = tpu_context.TPU... | a632fac96d555d3ce21d75183c00c6e7627ba5ac | 3,639,268 |
import os
import yaml
def from_path(path, vars=None, *args, **kwargs):
"""Read a scenario configuration and construct a new scenario instance.
Args:
path (basestring): Path to a configuration file. `path` may be a directory
containing a single configuration file.
*args: Arguments passed to Scenario... | ab9131427c1c759e72a9a0e73d735a0b6c3a0388 | 3,639,269 |
def SogouNews(*args, **kwargs):
""" Defines SogouNews datasets.
The labels includes:
- 0 : Sports
- 1 : Finance
- 2 : Entertainment
- 3 : Automobile
- 4 : Technology
Create supervised learning dataset: SogouNews
Separately returns the tra... | e10eaf10ba6e999d40a40f09f7e79b47eb5aa8a5 | 3,639,270 |
def add_volume (activity_cluster_df,
activity_counts):
"""Scales log of session counts of each activity and merges into activities dataframe
Parameters
----------
activity_cluster_df : dataframe
Pandas dataframe of activities, skipgrams features, and cluster la... | 1ea67909e2c48500ca2f022a3ae5ebcbe28da6c8 | 3,639,271 |
def handle_message(message):
"""
Where `message` is a string that has already been stripped and lower-cased,
tokenize it and find the corresponding Hand in the database. (Also: return some
helpful examples if requested, or an error message if the input cannot be parsed.)
"""
if 'example' in mes... | 910f07a3c612c9d8e58762b99dd508e76ad2f5aa | 3,639,272 |
import functools
def MemoizedSingleCall(functor):
"""Decorator for simple functor targets, caching the results
The functor must accept no arguments beyond either a class or self (depending
on if this is used in a classmethod/instancemethod context). Results of the
wrapped method will be written to the class... | 1757583cd416900d59c297a090800114a1bfcb3b | 3,639,273 |
def polyadd(c1, c2):
"""
Add one polynomial to another.
Returns the sum of two polynomials `c1` + `c2`. The arguments are
sequences of coefficients from lowest order term to highest, i.e.,
[1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
Parameters
----------
c1, c2 : array_lik... | 0dc8327abf94126fca5bbcc836bc1c404c92148e | 3,639,274 |
def weighted_categorical_crossentropy(target, output, n_classes = 3, axis = None, from_logits=False):
"""Categorical crossentropy between an output tensor and a target tensor.
Automatically computes the class weights from the target image and uses
them to weight the cross entropy
# Arguments
target: A tensor of ... | e7fe2c583b4158afe5c04632c53402af1c64cc20 | 3,639,275 |
from django.conf import settings
def get_config(key, default):
"""
Get the dictionary "IMPROVED_PERMISSIONS_SETTINGS"
from the settings module.
Return "default" if "key" is not present in
the dictionary.
"""
config_dict = getattr(settings, 'IMPROVED_PERMISSIONS_SETTINGS', None)
if con... | 8e4d03b71f568e6c3450e6674d16624ae44181a8 | 3,639,276 |
import os
def fetch_protein_interaction(data_home=None):
"""Fetch the protein-interaction dataset
Constant features were removed
=========================== ===================================
Domain drug-protein interaction network
Features ... | 14e033e690889fb8c560b0f79caee8ec35c144ca | 3,639,277 |
def prefetched_iterator(query, chunk_size=2000):
"""
This is a prefetch_related-safe version of what iterator() should do.
It will sort and batch on the default django primary key
Args:
query (QuerySet): the django queryset to iterate
chunk_size (int): the size of each chunk to fetch
... | e8a8feeea8073161283018f19de742c9425e2f94 | 3,639,278 |
import os
def get_dir(foldername, path):
""" Get directory relative to current file - if it doesn't exist create it. """
file_dir = os.path.join(path, foldername)
if not os.path.isdir(file_dir):
os.mkdir(os.path.join(path, foldername))
return file_dir | 8574dfc0503c8cc6410dc013a23689ac2b77f5d6 | 3,639,279 |
def dicom_strfname( names: tuple) -> str:
"""
doe john s -> dicome name (DOE^JOHN^S)
"""
return "^".join(names) | 864ad0d4c70c9bb4acbc65c92bf83a97415b9d35 | 3,639,280 |
import json
def plot_new_data(logger):
"""
Plots mixing ratio data, creating plot files and queueing the files for upload.
This will plot data, regardless of if there's any new data since it's not run continously.
:param logger: logging logger to record to
:return: bool, True if ran corrected, F... | 186b11d496c8b1097087f451e43d235b40d7a2ba | 3,639,281 |
def plot_graphs(graphs=compute_graphs()):
""" Affiche les graphes avec la bibliothèque networkx """
GF, Gf = graphs
pos = {1: (2, 1), 2: (4, 1), 3: (5, 2), 4: (4, 3), 5: (1, 3), 6: (1, 2), 7: (3, 4)}
plt.figure(1)
nx.draw_networkx_nodes(GF, pos, node_size=500)
nx.draw_networkx_labels(GF, pos)... | 4db21b3f5a823b5a7a17264a611435d2aa3825a4 | 3,639,282 |
def get_polygon_name(polygon):
"""Returns the name for a given polygon.
Since not all plygons store their name in the same field, we have to figure
out what type of polygon it is first, then reference the right field.
Args:
polygon: The polygon object to get the name from.
Returns:
The name for t... | da89efece12fbb27a5ceafef83b73ade392644cb | 3,639,283 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return redirect("/login")
# E... | 8699a3f0f162706c2e0a0ab9565b8b595cbb7574 | 3,639,284 |
from . import paval as pv
import configparser
def read_option(file_path, section, option, fallback=None):
"""
Parse config file and read out the value of a certain option.
"""
try:
# For details see the notice in the header
pv.path(file_path, "config", True, True)
pv.strin... | 6a9b839e36509630813c3cab5e45402b37377837 | 3,639,285 |
import pathlib
import os
def find_theme_file(theme_filename: pathlib.Path) -> pathlib.Path:
"""Find the real address of a theme file from the given one.
First check if the user has the file in his themes.
:param theme_file_path: The name of the file to look for.
:return: A file path that exists with... | 73784d715f325fef0e547a7e2f467755ac0ba32b | 3,639,286 |
import json
def msg_to_json(msg: Msg) -> json.Data:
"""Convert message to json serializable data"""
return {'facility': msg.facility.name,
'severity': msg.severity.name,
'version': msg.version,
'timestamp': msg.timestamp,
'hostname': msg.hostname,
'a... | ee01821bdbcdcbe88f5c63f0a1f22d050814aa7f | 3,639,287 |
def get_direct_dependencies(definitions_by_node: Definitions, node: Node) -> Nodes:
"""Get direct dependencies of a node"""
dependencies = set([node])
def traverse_definition(definition: Definition):
"""Traverses a definition and adds them to the dependencies"""
for dependency in definition... | 6dfbfd9068ecc3759764b3542be62f270c45e4c1 | 3,639,288 |
def get_timeseries_metadata(request, file_type_id, series_id, resource_mode):
"""
Gets metadata html for the aggregation type (logical file type)
:param request:
:param file_type_id: id of the aggregation (logical file) object for which metadata in html
format is needed
:param series_id: if of ... | 056707f6bd1947dd227c61dccb99b4f9d46ce9c9 | 3,639,289 |
def standardize(tag):
"""Put an order-numbering ID3 tag into our standard form.
This function does nothing when applied to a non-order-numbering tag.
Args:
tag: A mutagen ID3 tag, which is modified in-place.
Returns:
A 2-tuple with the decoded version of the order string.
raises:
... | 66edb2f402e2781deaf39ae470b5f3c54411c1c3 | 3,639,290 |
def _count_objects(osm_pbf):
"""Count objects of each type in an .osm.pbf file."""
p = run(["osmium", "fileinfo", "-e", osm_pbf], stdout=PIPE, stderr=DEVNULL)
fileinfo = p.stdout.decode()
n_objects = {"nodes": 0, "ways": 0, "relations": 0}
for line in fileinfo.split("\n"):
for obj in n_objec... | f3792b457e3cc922b6df3cef69dfb4c8d00c68d9 | 3,639,291 |
def combine_multi_uncertainty(unc_lst):
"""Combines Uncertainty Values From More Than Two Sources"""
ur = 0
for i in range(len(unc_lst)):
ur += unc_lst[i] ** 2
ur = np.sqrt(float(ur))
return ur | 6f06afc7bda7d65b8534e7294411dbe5e499b755 | 3,639,292 |
def export_performance_df(
dataframe: pd.DataFrame, rule_name: str = None, second_df: pd.DataFrame = None, relationship: str = None
) -> pd.DataFrame:
"""
Function used to calculate portfolio performance for data after calculating a trading signal/rule and relationship.
"""
if rule_name is not None:... | e0587a658aab2e629bff7c307e5f1aaec63a80fe | 3,639,293 |
def attention(x, scope, n_head, n_timesteps):
"""
perform multi-head qkv dot-product attention and linear project result
"""
n_state = x.shape[-1].value
with tf.variable_scope(scope):
queries = conv1d(x, 'q', n_state)
keys = conv1d(x, 'k', n_state)
values = conv1d(x, 'v',... | 63456ce40c4e72339638f460a8138dcd143e7352 | 3,639,294 |
def std_ver_minor_inst_valid_possible(std_ver_minor_uninst_valid_possible): # pylint: disable=redefined-outer-name
"""Return an instantiated IATI Version Number."""
return iati.Version(std_ver_minor_uninst_valid_possible) | 9570918df11a63faf194da9db82aa4ea1745c920 | 3,639,295 |
def sequence_loss_by_example(logits, targets, weights,
average_across_timesteps=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits (per example).
Args:
logits: List of 2D Tensors of shape [batch_size x n... | adf8a063c6f41b41e174852466489f535c7e0761 | 3,639,296 |
def skip(line):
"""Returns true if line is all whitespace or shebang."""
stripped = line.lstrip()
return stripped == '' or stripped.startswith('#!') | 4ecfb9c0f2d497d52cc9d9e772e75d042cc0bcce | 3,639,297 |
def get_dss_client(deployment_stage: str):
"""
Returns appropriate DSSClient for deployment_stage.
"""
dss_env = MATRIX_ENV_TO_DSS_ENV[deployment_stage]
if dss_env == "prod":
swagger_url = "https://dss.data.humancellatlas.org/v1/swagger.json"
else:
swagger_url = f"https://dss.{ds... | 4e260b37c6f74261362cc10b77b3b28d1464d49d | 3,639,298 |
def bounce_off(bounce_obj_rect: Rect, bounce_obj_speed,
hit_obj_rect: Rect, hit_obj_speed):
"""
The alternative version of `bounce_off_ip`. The function returns the result
instead of updating the value of `bounce_obj_rect` and `bounce_obj_speed`.
@return A tuple (`new_bounce_obj_rect`, `new_bounce_... | 84b038c05f5820065293ba90b73497f0d1e7a7b9 | 3,639,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.