content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
import contextlib
import socket
def resolve(hostname: str) -> Optional[str]:
""" Get the IP address of a subdomain """
with contextlib.suppress(socket.gaierror):
return socket.gethostbyname(hostname) | cb4924f3120f97e558fabccbab1c30612e52dc2c | 48,661 |
from typing import List
from typing import Dict
def get_researcher_allowed_studies(request: ResearcherRequest) -> List[Dict]:
"""
Return a list of studies which the currently logged-in researcher is authorized to view and edit.
"""
kwargs = {}
if not request.session_researcher.site_admin:
... | 9c0d38b8f4786fbda56b092504e2fd17c277857e | 48,662 |
def fast_non_dominated_sort(values1, values2):
""" Function to carry out NSGA-II's fast non dominated sort """
S = [[] for i in range(0, len(values1))]
front = [[]]
n = [0 for i in range(0, len(values1))]
rank = [0 for i in range(0, len(values1))]
for p in range(0, len(values1)):
S[p] =... | ee7275aea0c2b0acadd6fb523fc24e5618165bfe | 48,663 |
def generate_list(n,idx_excl,n_rand):
"""
random_array = generate_list(n,idx_excl,n_rand)
Generates a list
Parameters
----------
n : INT, total number of samples
idx_excl : 2D array, start,stop index for each seizure
n_rand : INT, number of random samples
Returns
-------
1D... | e639df120d8c78c9bf777f1a569658ffec8d4a65 | 48,664 |
def _neighboring_points(o_index, i_index, e_len, f_len):
"""
A function that returns list of neighboring points in
an alignment matrix for a given alignment (pair of indexes)
"""
result = []
if o_index > 0:
result.append((o_index - 1, i_index))
if i_index > 0:
result.append(... | f7501e25b25a1be50f7eeaf7d32d46a5e55c8ee0 | 48,665 |
import io
import base64
import json
def pose_estimate(event, context):
"""Perform human pose estimation."""
try:
# Get image from the request
picture, filename = fetch_input_image(event)
image = load_image(picture)
print('Loading model')
model = Model(MODEL_PATH)
... | 4c7cc9670d94b62dcaf926b94ee980f7f33de550 | 48,666 |
import collections
def CreateAssocVarPairs(rappor_metrics):
"""Yield a list of pairs of variables that should be associated.
For now just do all (string x boolean) analysis.
"""
var_pairs = collections.defaultdict(list)
for metric, var_list in rappor_metrics.iteritems():
string_vars = []
boolean_v... | d9be4a5904bb3486d9761cef89299bbee67178b8 | 48,667 |
def read_text(unformatted_text: str) -> str:
"""Open text from the file or read it directly.
Arguments:
unformatted_text (str): path to a file OR inputed text
Returns:
str: reads and returns text as a string
"""
try:
with open(unformatted_text, "rt") as f:
# cre... | 180238bf545ee7daef56169cc64a9c6277599546 | 48,670 |
def regions(**kw_params):
"""
Get all available regions for the EC2 service.
You may pass any of the arguments accepted by the VPCConnection
object's constructor as keyword arguments and they will be
passed along to the VPCConnection object.
:rtype: list
:return: A list of :class:`boto.ec2.... | 7e099f76714d4ccfc557c24bccea6ac96d734828 | 48,671 |
def read_from_txt(txt_file: str = "untitled.txt") -> list:
"""Opens a text file to get all words, called from outside the class instantiation"""
with open(txt_file, "r") as words:
lines = words.readlines()
return [
line.split(".")[1].strip().upper() for line in lines
] | 4b5a195b77b8eb4028246e54b75cf0862628fcaa | 48,672 |
def extensionOP(extension):
"""
Get an extension's associated operator
:param extension: the extension
:return: the DAT source of extension or the internal parameters' comp or
None if undetermined
"""
eop = None
if isinstance(extension, ParCollection):
# assume internal parameters
eop = extension.stdswi... | 2203ced8580c2f6d51e892f8aae14c238b615e21 | 48,673 |
import tokenize
def _integerize(json_data, word_to_id, dataset):
"""Transform words into integers."""
sequences = np.full((len(json_data), MAX_TOKENS_SEQUENCE[dataset]),
word_to_id[PAD], np.int32)
sequence_lengths = np.zeros(shape=(len(json_data)), dtype=np.int32)
for i, sentence in enum... | 039336371843f0ffb809be94c6100ef659f63248 | 48,674 |
def plot_pq_all(mean_arr, std_arr, label_list, title='QP_accu',
metric='rmse', ax=None, colors=None, alpha=0.5):
"""Generate a summary QP plots with different methods.
Args:
mean_arr (np.ndarray): Mean performance of each method at a certain
quantile, (#methods, #quantiles).... | 42229b9a6a30b20e2847c19dab99f7f11dadb7bb | 48,675 |
import numpy
def rechannel(channels):
"""A data node to rechannel data.
Parameters
----------
channels : int or list
The channel mapping.
Receives
------
data : ndarray
The original signal.
Yields
------
data : ndarray
The rechanneled signal.
"""
... | 993863df43b0fe1a074617a59dc6dca97e2f3076 | 48,676 |
def prepare_traveler_from_raw_data(trips: list):
"""
Construct a traveler by combining a list of single trips
:param trips:
:return:
"""
traveler_chekins = []
for trip in trips:
traveler_chekins = traveler_chekins + generate_checkins(trip)
return sorted(traveler_chekins, key=lamb... | 2fb3e09da47e0c24790864e32b6ff0e232f1d795 | 48,677 |
def spglib_get_primitive(struct, **kwds):
"""Find primitive structure for given :class:`~pwtools.crys.Structure`.
If `struct` is irreducible (is already a primitive cell), we return None,
else a Structure.
Uses spglib.
Parameters
----------
struct : Structure
**kwds : keywords
... | 03a181f49ca4066e78bc7d93ae5cec1ca80a2ac3 | 48,678 |
import asyncio
async def async_query_for_ptr_with_proto(protocol, ips_to_lookup):
"""Send and receiver the PTR queries."""
time_outs = 0
query_for_ip = {}
for ip in ips_to_lookup:
req = async_generate_ptr_query(ip)
query_for_ip[ip] = req.id
try:
await asyncio.wait_f... | e7502b250f02c9345cc7af2c4a913a8f010fc10c | 48,679 |
def fft_shift_phasor_2d(shape, offset, grad=False):
"""Return phasor array used to shift an array (in real space) by
multiplication in fourier space.
Parameters
----------
shape : (int, int)
Length 2 iterable giving shape of array.
offset : (float, float)
Offset in array ele... | cb8e37bcc24f4a6925b1af4b4b6a2563a30b4600 | 48,680 |
def get_ar(bbox):
"""
:param bbox: top left, right down
:return: aspect ratio
"""
[x1, y1, x2, y2] = bbox
return (y2 - y1) / (x2 - x1) | d79eb51eafec917b1754558a9a87307734fd8ac4 | 48,681 |
def log_p_xi(meanLike, covarLike, xi):
"""
Calculate log-likelihood of a single xi, given its
mean/covar after collapsing P(A | X_{-i}, Z)
"""
D = float(xi.shape[1])
ll = -(D / 2) * np.log(covarLike)
ll -= (1 / (2 * covarLike)) * np.power(xi - meanLike, 2).sum()
return ll.item() | 88ce5ea31907a6b9d586912e7ba95a4f7d01b298 | 48,682 |
def get_statsTable(dType, dFreq, df, dates_as_index=True, ptiles=None):
"""
Construct detailed tables with summary statistics.
Parameters
___________
dType : str
Dataset type of the portfolios. Possible choices are:
* ``Returns``
* ``Factors``
* ``NumFir... | 6ca9e3c83177b676dc98db73b282688e8b26c606 | 48,683 |
def has_parameter(param_key_matcher, param_value_matcher):
"""Check values of the stacks parameters."""
return StackParameterMatcher(wrap_matcher(param_key_matcher), wrap_matcher(param_value_matcher)) | 1f1284bc80b27615d3bd7a6b5f6a658dbf5a7fc6 | 48,684 |
import glob
def get_run_files_from_formatter(run_id, formatter, **kwargs):
"""Get a set of files for a particular run
Parameters
----------
run_id : `str`
The number number we are reading
formatter : `FilenameFormat`
Object that constructs the file naem
kwargs
Passed t... | 1266babe827f230176241613b312eec1cc64adcc | 48,685 |
def create_assigment_rule(sbml_model: libsbml.Model,
assignee_id: str,
formula: str,
rule_id: str = None,
rule_name: str = None) -> libsbml.AssignmentRule:
"""Create SBML AssignmentRule
Arguments:
sb... | 62165da36f4f5117bd9f17305842588968dc44f4 | 48,686 |
def regula_falsi(f: Function, xi: float, xf: float, tol: float, iter: bool = False) -> float:
"""
Regula Falsi
============
Regula falsi method to find a root of a function
Parameters
----------
f : Function
Function
xi : float
First point
xf : float
Sec... | b33b5bfec8598b5f5afbff066b75d43ea135970d | 48,687 |
def SelectCard():
# Method Description:
"""Selects A Card Using A Terminal As UI"""
# Endless Loop Till User Enters A Valid Card Number
while(True):
# Prompt user to select card
i= int(input("Please choose a card: "))
# If the position entered is correct
if (i > 0) and (... | c48daf472b6c1b8577762324a4a992fb806c84d9 | 48,688 |
def temperature_salinity_timeseries(
temperature, salinity, colors, data_date, prediction, bloom_dates, titles,
):
"""Create a time series plot figure object showing temperature
on the left axis and salinity on the right.
"""
fig = matplotlib.figure.Figure(figsize=(15, 4.25), facecolor=colors['bg'])... | 398234b6c73c11127449f5d8caa99cf90c99f764 | 48,689 |
import pandas
def readCSVfile(fileName):
"""twitter_follower_yyyymmdd_hhMMss.csv を開く"""
lines = pandas.read_csv(fileName, encoding="utf8")
return lines | 421502f6ae7ac1a92e89044b5c78d4d95e238214 | 48,690 |
def validate_image_pull_credentials(image_pull_credentials):
"""
Validate ImagePullCredentialsType for Project
Property: Environment.ImagePullCredentialsType
"""
VALID_IMAGE_PULL_CREDENTIALS = ("CODEBUILD", "SERVICE_ROLE")
if image_pull_credentials not in VALID_IMAGE_PULL_CREDENTIALS:
... | f4953fefbca3ca5906ca58497152b25a07247c9a | 48,692 |
def dynamic_import_st(module, backend):
"""Import ST models dynamically.
Args:
module (str): module_name:class_name or alias in `predefined_st`
backend (str): NN backend. e.g., pytorch, chainer
Returns:
type: ST class
"""
model_class = dynamic_import(module, predefined_st.... | e83a0f75da0894aecac760d421c25107419e155f | 48,693 |
def num_bits(i):
"""Returns the number of bits in an unsigned integer."""
n = 0
while i:
n += 1
i &= i - 1
return n | 3eb664bd642717556af0b2c09314000d70209b44 | 48,694 |
def available_solvers():
"""Returns a list of all available solvers.
These can be used in :func:'optunity.make_solver'.
"""
return solver_registry.solver_names() | d90d1c6b0b2bf2af28ad696a91fb6d62d561ea6e | 48,696 |
import math
def coefficient_of_drag_adjusted(state, only_in_range=False):
"""
Calculate the coefficient of drag. The drag is calculated by a bilinear
interpolation from values spaced evenly through Mach values and log10
Reynolds numbers. These values were initially computed from one of the
other... | 95e2f0e553ce90cc2c0b8cf789551ff5cefa9a75 | 48,697 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: "192.168.1.123", CONF_MAC: "aabbccddeeff"},
) | 72d859c574605471e8e5a542eda38fdbeb5cc985 | 48,698 |
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):
"""Instantiates a placeholder tensor and returns it.
# Arguments
shape: Shape of the placeholder
(integer tuple, may include `None` entries).
ndim: Number of axes of the tensor.
At least one of ... | a5d6cb761bca6b94fc64d20bfc0efe83a74cfd9b | 48,699 |
import functools
def action_logging(f):
"""
Decorator to log user actions
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
with create_session() as session:
if g.user.is_anonymous:
user = 'anonymous'
else:
user = g.user.username... | 60a54aae190b111bf522c873e34126bdf964f154 | 48,700 |
def ClassifyWspecifier(wspecifier):
"""Interprets type / filenames / options for the given wspecifier.
Args:
wspecifier: A string indicating the wspecifier.
Returns:
(WspecifierType, archive_filename, script_filename, WspecifierOptions)
for the given filename.
Examples:
... | 446ca165d4e028ab3be4eed21ff7f0e601d6f0a1 | 48,701 |
def canonicalize_instance_info(node):
"""
Convert what is returned from GCE into the butter standard format.
"""
return Instance(
instance_id=node.uuid,
public_ip=node.public_ips[0],
private_ip=node.private_ips[0],
state=node.state) | 6c5760fb231822f2b3edfc3f76937fb2e82ea464 | 48,702 |
def get_track( track_id ):
"""Returns data of a track having `track_id`
No request params.
"""
try:
track = g.user.get_track( track_id )
data = {
'title' : track.title,
'path' : track.path,
'artist' : track.artist,
... | 1def539d9065c562b61cb520848ec36ae4b120c3 | 48,703 |
def _is_rule_exists(nat_rules, rule_type,
original_ip, original_port,
translated_ip, translated_port, protocol):
"""
check if we already have some rule with same properties
"""
# gatewayNatRule properties may be None or string
# convert to str, bacause por... | c6ad5920b789e18d357941d71dd9e08922aa26a0 | 48,704 |
def lsgan_loss_generator(prob_fake_is_real):
"""Computes the LS-GAN loss as minimized by the generator.
Rather than compute the negative loglikelihood, a least-squares loss is
used to optimize the discriminators as per Equation 2 in:
Least Squares Generative Adversarial Networks
Xudong Mao,... | a524108b8486111e475ad56fa4e910bb9283592c | 48,705 |
from collections import defaultdict
def split_by_x(points):
"""Partitions an array of points into two by x-coordinate. All points with
the same x-coordinate should remain on the same side of the partition. All
points in the right partition should have strictly greater x-coordinates
than all points in ... | ff41bec793544a59791912c1d97b09ccb175e77e | 48,706 |
import json
def dumps(*args, **kwargs):
"""
See :func:`json.dumps()`.
"""
kwargs["ensure_ascii"] = True
kwargs["cls"] = _ExtendedJsonEncoder
return json.dumps(*args, **kwargs) | c3e06e4f06bf39b01fcde74a4924d6edc97035f4 | 48,707 |
def remove_quoted_text(line):
"""get rid of content inside quotes
and also removes the quotes from the input string"""
while line.count("\"") % 2 == 0 and line.count("\"") > 0:
first = line.find("\"")
second = line.find("\"", first+1)
line = line[0:first] + line[second+1:]
while ... | ef0776ddfd9d60474077fd106474728de10b9e8f | 48,708 |
def ryu_from_jsondict(jsondict):
""" Load a ryu object from a json dictionary
jsondict: A dictionary loaded by json.load
"""
assert len(jsondict) == 1
for oftype, value in jsondict.items():
cls = getattr(parser, oftype)
if issubclass(cls, parser.OFPFlowMod):
value["d... | c9db51a0b026749b118eeb09bccc237a874f70f3 | 48,709 |
def conv_block(
inp,
cweight,
bweight,
reuse,
scope,
use_stride=True,
activation=tf.nn.leaky_relu,
pn=False,
bn=False,
gn=False,
ln=False,
scale=None,
bias=None,
class_bias=None,
use_bias=False,
... | 3699166a4c626c7520b7fa372a27735f19672949 | 48,710 |
from typing import Tuple
import numpy
def qa_statistics(raster, mask, blocks, confidence=None) -> Tuple[float, float]:
"""Retrieve raster statistics efficacy and not clear ratio, based in Fmask values.
Notes:
Values 0 and 1 are considered `clear data`.
Values 2 and 4 are considered as `not cl... | cc45c084a9860414d66de893cf27387b4c55c7b7 | 48,711 |
from varappx.main.view_tools import authenticate as auth
def user_activation(email_to_file=None, rank_required=ADMIN_LEVEL):
"""Activate a user's account"""
# logger.info("Activate/deactivate user")
if auto_process_OPTIONS(request):
return auto_process_OPTIONS(request)
username = request.form[... | 03e688c10a618096d2e13d217cc1674cd75489f1 | 48,712 |
import re
def remove_emoji_and_non_alphanumeric(word_list):
"""
Remove both emojis and non-alphanumeric tokens in the given word list
parameters
-----------
:param word_list: list of str
:return: list of str
"""
filtered_list = [word for word in word_list if word not in emoji.UNICODE_... | d187a7ac23fde91cdbb5ce931050c4a5562a8564 | 48,713 |
def active_matrix_from_extrinsic_euler_zyx(e):
"""Compute active rotation matrix from extrinsic zyx Cardan angles.
Parameters
----------
e : array-like, shape (3,)
Angles for rotation around z-, y-, and x-axes (extrinsic rotations)
Returns
-------
R : array-like, shape (3, 3)
... | e4660706b7e2b651a2f3c02d6f9620ea4095becb | 48,715 |
def get_index_of_feature(feature_list, item):
"""
Gets the index of the feature in the provided feature list
:rtype : int
:param feature_list: List of features to search from
:param item: The feature to search
:return: The index where the feature was founded, -1 otherwise
"""
# getting... | 2f2d79d4caf953b60ecf841a23d86e8b4a00b937 | 48,716 |
import logging
import pytz
def get_timezone(WindowsZoneName=True):
"""
Get the TimeZone Name
if WindowsZoneName is True, then it returns the name used by the Microsoft Windows Platform
otherwise it returns the Olsen name (used by all other platforms)
Note: this needs to get tested on Windows
... | e175aae37bc544d8ecd51ad7cafafbc88b5862f7 | 48,717 |
def fix_ghdx_birth_weights(df):
"""Ensure the child birth weight is in grams and is a legal value.
The original survey allowed answers to weights to be coded in grams or
kilograms. The GHDx data has recoded the values into grams. However, a
few cases are clearly still coded in kilograms. The survey als... | a11e50a1a1db780389ad99051e7cf93a025155ae | 48,718 |
def __virtual__():
"""
Only load if boto is available.
"""
if "boto3_elasticache.cache_cluster_exists" in __salt__:
return "boto3_elasticache"
return (False, "boto3_elasticcache module could not be loaded") | d844dc256eaf81e5a368afd14ac7169969a4bab6 | 48,719 |
def parse_adjlist(lines, comments='#', delimiter=None,
create_using=None, nodetype=None):
"""Parse lines of a graph adjacency list representation.
Parameters
----------
lines : list or iterator of strings
Input data in adjlist format
create_using: NetworkX graph container... | b395366c1f5ae8a048b80f8d78de33e1dc234966 | 48,720 |
def get_slovakia():
"""
gets all the data for Slovakia
:return: object
"""
slovakia = Country('Slovak Republic')
slovakia.get_gdp('https://www.quandl.com/api/v3/datasets/WWDI/SVK_'
'NY_GDP_PCAP_CD.json?api_key=2jhCWecEKmuxzVY9ifwp')
slovakia.get_investment_inflows('https... | 98c6febb03c088e0f614e60573898aa680169297 | 48,721 |
from scipy.optimize import linear_sum_assignment as linear_assignment
def cluster_acc(y_true, y_pred):
"""
Calculate clustering accuracy. Require scikit-learn installed
# Arguments
y: true labels, numpy.array with shape `(n_samples,)`
y_pred: predicted labels, numpy.array with shape `(n_sa... | de82c781709b6c147177f54ab7363edf7365ad85 | 48,722 |
def calc_rms_df(df, measured_tox_col, modeled_tox_col):
"""
Calculate the root mean square deviation for two columns of a DataFrame
returns √[ ∑(x-y)² / n ]
"""
df_rms = df[[measured_tox_col, modeled_tox_col]].dropna()
toxobs = df_rms[measured_tox_col].tolist()
toxmod = df_rms[modeled_tox_co... | 9160881aa3ce08164aae1613eddf282ba1b43375 | 48,723 |
def dist(p1, p2):
"""
Distance between two points represented by arrays.
"""
return distance(p1[0], p1[1], p2[0], p2[1]) | 52f1a59c6aa125adcde80398712c30d7d61f2164 | 48,724 |
def trim_motif(pfm, motif, min_ic=0.2, pad=0):
"""
Given the PFM and motif (both L x 4 arrays) (the motif could be the
PFM itself), trims `motif` by cutting off flanks of low information
content in `pfm`. `min_ic` is the minimum required information
content. If specified this trimmed motif will be e... | ee8207336ff01c32f3e22bb6ea2bc1a2e53b4c1c | 48,725 |
def org_search():
"""
Organisation REST controller
- limited to just search.json for use in Autocompletes
- allows differential access permissions
"""
s3.prep = lambda r: r.representation == "json" and \
r.method == "search"
return s3_rest_controller(modu... | 6e74da5fbcaf8d48c4d39105a7d73d65e51b1419 | 48,726 |
def in_quiet_hours() -> bool:
"""Check whether the current time is within quiet hours.
Returns:
bool: True if within quiet hours
Raises:
AttributeError: if quiet hours weren't defined in config
"""
now = pendulum.now()
hour = now.hour
if config.QUIET_START > config.QUIET_E... | 782ccf47b045f8ff23a63dd81f81f89b0a11a5cf | 48,727 |
def int_to_smile(list_of_int):
"""
Convert the list of int to list of token according to the vocabulary
:param list_of_int: list of int representing the SMILES
:type list_of_int: list of int
:return: list of token
"""
return [p.tokens[s] for s in list_of_int] | 28475b1357e0de3304823840cc81482bf789b2f4 | 48,728 |
def searchLibary(keyword):
"""
Keyword based search for books, case insensitive in author and title
Args:
keyword (string): Keyword to search for
Return:
List of search results
"""
results = []
lk = keyword.lower()
for bookid, book in library.LIBRARY.items():
... | 1bef76e977983ed13898a6f0ab4ffb80729e36a7 | 48,729 |
def emprestarLivro(livro):
""" Emprestimo do livro
"""
return biblioteca_temp.emprestarLivro(livro) | 835a6621e0fd1ccd52e03cd21a228d7a6c2068fb | 48,730 |
from typing import Any
from operator import lt
def _heapify(items: list[Any], d: int, comp=lt) -> list[Any]:
"""Создать на месте кучу из списка за время O(log(len(items))).
:param items: список элементов
:param d: коэффициент ветвления (максимальное число потомков у одного элемента)
:param comp: функ... | 5c32093dc3beddaceea76e4e9c36839f31610f95 | 48,731 |
def build_generator_growth_layer_block(conv_layers, params, block_idx):
"""Builds generator growth block internals through call.
Args:
conv_layers: list, the current growth block's conv layers.
params: dict, user passed parameters.
block_idx: int, the current growth block's index.
... | 192701b6282ac8bd53b40b71b54e647e8aa9ec81 | 48,732 |
def isfloat(s):
"""**Returns**: True if s is the string representation of a number
:param s: the candidate string to test
**Precondition**: s is a string
"""
try:
x = float(s)
return True
except:
return False | 6967444007388793a70b9bd74d3153d6f88b6a4d | 48,733 |
import random
import string
def generate_password(length=10):
"""Generate rnadom password of the given length.
"""
return ''.join(
random.SystemRandom().choice(
string.ascii_lowercase + string.ascii_uppercase + string.digits
)
for _ in range(length)
) | e4d65ea76bee72c68afbfbcc011676e9ae35c588 | 48,734 |
import numpy
def reference_transit(samples, per, rp, a, inc, ecc, w, u, limb_dark):
"""Returns an Earth-like transit of width 1 and depth 1"""
f = numpy.ones(tls_constants.SUPERSAMPLE_SIZE)
duration = 1 # transit duration in days. Increase for exotic cases
t = numpy.linspace(-duration * 0.5, duratio... | 716ac7ecda59a608389d03c2a091434ebdef2bcf | 48,735 |
import math
def sol_rad_from_t(et_radiation, cs_radiation, temperature_min, temperature_max, coastal):
"""
Estimate incoming solar (or shortwave) radiation, *Rs*, (radiation hitting
a horizontal plane after scattering by the atmosphere) from min and max
temperature together with an empirical adjustmen... | 6952aa6509897494551839e412d5a15e51b5e30c | 48,736 |
def moving_avg(v, N):
"""
simple moving average.
Parameters
----------
v : list
data ta to average
N : integer
number of samples per average.
Returns
-------
m_avg : list
averaged data.
"""
s, m_avg = [0], []
for i, x in enumerate(v, 1):
... | 2e71eefb91ac694eaf06c2167e38ef497671145e | 48,737 |
def solve():
"""This method will compute and return the solution if it exists, as a list of (row, column) tuples, zero-based.
Else, an exception will be raised stating a loop was detected and that no solution exists."""
robot = Robot(number_of_rows, number_of_columns, ball_location, goal_location, block... | c24be000f6004ba6d3295b56f85b0a5921eb83c0 | 48,738 |
def hashed_password(username: str, password: str) -> str:
"""
ハッシュ化したパスワードを返す。
"""
tmp = adcconfig.SALT + username + password
return sha256(tmp.encode('utf-8')).hexdigest() | c91fff9edaf1a6dd487a4d912b77aaa27c5f197f | 48,739 |
def linierRegression(features, weights):
"""
Performs simple linier regression
"""
return np.dot(features, weights) | 24791550134b5f1efa102b956fa44be81053b001 | 48,740 |
from typing import List
def get_students(tas: List[str], gr:str)->List[str]:
""" From the list of all TAs, find TAs matching the constraint string
For example, gr could be "cs17|es18" this represents all the students
whole roll numbers start from cs17 or es18
This function returns the list of TAs fr... | b952fa3688b3ff107a5a1289fc3216244f4f0554 | 48,741 |
def calculate_prototypes_from_labels(embedding,
labels,
max_label=None):
"""Calculates prototypes from labels.
This function calculates prototypes (mean direction) from embedding features
for each label. This function is also used as the m... | d085117b45ec236d36528cafeb352030d5fce858 | 48,742 |
def get_mask(pos, shape, radius, include_edge=True, return_masks=False):
""" Create a binary mask that masks pixels farther than radius to all
given feature positions.
Optionally returns the masks that recover the individual feature pixels from
a masked image, as follows: ``image[mask][masks_single[i]]... | 2e46235cbd32ae5f4ae48fb1c7990d189c0464a9 | 48,743 |
def Volume(v,u,w):
"""Calculate volume of solid created by three vectors.
Returns int
Attributes
----------
v: Vector
First Vector
u: Vector
Second Vector
w: Vector
Third Vector
"""
return abs(DotProduct(CrossProduct(v,u), w)) | be1fc8285fa339820cc71e59390a2a5a92bc9ace | 48,744 |
def is_admin(user_id):
"""
Retrieves a user's admin status from the permissions directory.
"""
perms = get_current_permissions()
return user_id in perms["admins"] | 610528eb3ea18370261aa34aabf9ff05811bc9c0 | 48,745 |
def _get_commits(output):
"""Returns the commits message in the output. All commits must have
been made by `Alice Author` or `PY C` to be found.
"""
commits = []
save = False
cnt = 0
for row in output.split("\n"):
if row.strip() in ["Alice Author", "Alice Äuthòr", "PY C"]:
... | 0514d0c3279c7e14810403412284e6d07eb03d16 | 48,746 |
import platform
import glob
def scan():
"""scan for available ports. return a list of names"""
system_name = platform.system()
if system_name == 'Windows':
available = []
for i in range(200):
try:
s = serial.Serial(i)
available.append(s.portstr)
... | 2737052aa0f69454354d0ecc72e634940799285e | 48,747 |
def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
"""Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote function... | 19d5e46187701d187a81e9f38f35725052fad83d | 48,748 |
import struct
def steg(in_path, out_path=None, data=None):
"""
The steg function (use the LSB of the color table entries to hide the data)
"""
# Must encode the length of the data so we know how much to read when extracting
if data is not None:
data_array = bytearray(data)
data_ar... | 1464dadec850816d20de9c13b5297b4c49fda59a | 48,750 |
def _make_specific_identifier(param_name, identifier):
# type: (str, str) -> str
"""
Only adds an underscore between the parameters.
"""
return "{}_{}".format(param_name, identifier) | 5268d366f04c616d8180e7cc4167030efdec9070 | 48,751 |
import torch
def resnet50(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False):
"""Constructs a ResNet-50 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): onl... | 634c3e0a2446fe1b470e0eba311d71cda6bb7cae | 48,752 |
def ReadTag(buffer, pos):
"""Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decodi... | 91c0a1e86816066768b15a3a2e7b8a8468900661 | 48,753 |
def emptyStack():
""" Empties the stack while collecting each element as it is removed.
Returns the collected elements. """
elements = ""
while not stack.isEmpty():
if isOperator(stack.peek()):
elements += stack.pop()
elif stack.peek() == '(':
raise ParensMism... | 72be5b7c6752093c8a30063d36f0bfa70bc5fb8d | 48,754 |
from typing import Union
import re
def get_brackets(title: str) -> Union[str, None]:
"""
Return the substring of the first instance of bracketed text.
"""
regex_brackets = re.search(r"\[(.*?)\]", title)
if regex_brackets is None:
return None
else:
return regex_brackets.group() | f1d985cf79ae881e8aca168c065d40e640a9c1ff | 48,755 |
def stack_3rd_dimension_along_axis(u_jkir, axis):
"""
Take the 3D input matrix, slice it along the 3rd axis and stack the resulting 2D matrices
along the selected matrix while maintaining the correct order.
:param u_jkir: 3D array of the shape [JK, I, R]
:param axis: 0 or 1
:... | db9e126503beb99b43032bea7df7ffb9cc432a07 | 48,756 |
from typing import Union
from typing import List
def _op_nodes(
graph: Union[tf.Graph, testutils.GraphDef]) -> List[testutils.NodeDef]:
"""Return arithmetic/nn operation nodes from a graph"""
graph_def = graph.as_graph_def() if isinstance(graph, tf.Graph) else graph
def _op(node): return node.op n... | 7e2d854a5bbdb3e2401d3df8ed8fbaa9f564acac | 48,757 |
def _compositeImageToVideoSegment(compositeImage):
"""
:param compositeImage:
:return:
@type compositeImage: CompositeImage
"""
if compositeImage is None or compositeImage.videomasks is None:
return []
return [segmentToVideoSegment(item) for item in compositeImage.videomasks] | b730e0f3152a512cb200436c4732abaed3c147e3 | 48,758 |
from bids import BIDSLayout
import warnings
def collect_sessions(bids_dir, session=None, strict=False, bids_validate=True):
"""
List the sessions under the BIDS root and checks that sessions
designated with the participant_label argument exist in that folder.
Returns the list of sessions to be finally... | 6c905038d5eca24c57197d574d1efb8c4ccf0a66 | 48,759 |
def _dof(mean_tau, sd_tau2):
"""
Returns the degrees of freedom for the chi-2 distribution from the mean and
variance of the uncertainty model, as reported in equation 5.5 of Al Atik
(2015)
"""
return (2.0 * mean_tau ** 4.) / (sd_tau2 ** 2.) | 9a4a395c9aea7b965a477550c7f254bf744cadc5 | 48,760 |
def stations():
"""Return a list of stations."""
print("Received Station API Request.")
# Query the station list
station_data = session.query(Station).all()
# Create a list of dictionaries
station_list = []
for station in station_data:
station_dict = {}
station_dict["id"] ... | 67ffb7a8691ea4f44420b0f0f0b4d4c4a2ecd3ba | 48,761 |
from typing import Iterable
import yaml
def yaml_load(string):
"""Parse multiple strings as yaml data. Multiple dictionaries are combined togather."""
if isinstance(string, str):
return ordered_load(string)
if not isinstance(string, Iterable):
raise TypeError('Invalid yaml_load argument t... | 3310aa780d774d325cabbbf353d45062a1c243a5 | 48,762 |
def check_tensors_dtype_same(data_dtype, value_dtype, op_name):
"""Check tensors data type same."""
if data_dtype in value_dtype:
return True
raise TypeError(f"For '{op_name}', the value data type '{value_dtype}' "
f"is not consistent with assigned tensor data type {data_dtype}."... | f31e34dea4ccb83938319db82a7a679876505a75 | 48,764 |
import tqdm
def generate_data(data_dirs, save_dir):
"""
Routine for generating train data in tfrecords
Args:
data_dirs: where simulation data is.
save_dir: where tfrecords will go.
Returns: list of tfrecords.
"""
def data_generator():
def _get_data(dir):
... | 9a67f3219e32787016e726e4da6d1025b80fac3b | 48,765 |
def to_categories(df, cat_map):
""" Convert a dataframe to use categories, based on the category map created by table_category_map.
:param df: CHIS Dataframe to convert, loaded from Metatab
:param cat_map: category map, from table_category_map
:return:
"""
df = df.copy()
for col in df.c... | 66fb82fdc9d0d91e063e08a912673ab6acf0ef17 | 48,766 |
def xgcd(vals):
"""Calculate extended greatest commond divisor."""
_xgcd = Xgcd(vals)
return _xgcd.run() | cf4956bec4141780b1a6c3eedd311a4e727df4ae | 48,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.