content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_session_middleware(app, global_conf,
session_type=NoDefault,
cookie_name=NoDefault,
**store_config):
"""
Wraps the application in a session-managing middleware.
The session service can then be found in
``environ... | ffb4a685f3174f8b4d73089064c407995c5f5095 | 3,596,745 |
def create_comment(comment_text, indent):
"""
method create_comment
Creates a comment object from a given string
Arguments:
comment_text - the text to be in the comment
"""
new_comment = Comment(indent)
for line in comment_text.split("\n"):
new_comment.comment_lines.append(str... | f4a9d1ade9408376377baa943cabfc4cd1314028 | 3,596,746 |
def filename_to_title(filename):
"""Convert the Verilog filename into the web page title"""
return base_filename(filename).replace("_", " ") | 2a952d002c4867bafb22e723f74d6fb1b9f4a0fc | 3,596,747 |
def fill_in_bounds(bounds_vec, endpoint=False):
"""
Fill in the outline of contiguous integer regions with integers. For example:
[10, 13, 20, 24] -> [10, 11, 12, 20, 21, 22, 23]
:param bounds_vec: list of int or 1-d numpy array of int, outline of contiguous integer regions. Must
have even number o... | 255b7f514a246e572bdc3d75edcba4e92e5b39b9 | 3,596,748 |
def radec(ra, dec):
""" return SkyCoord object from ra, dec"""
ra = ra2deg(ra)
dec = dec2deg(dec)
# print ra, dec
return SkyCoord(ra, dec, unit=('deg, deg')) | bd62bd91c44a74ec0455262ffd5ae26c7e5577b4 | 3,596,750 |
def simple_query_expansion(Q, data, inds, top_k=10):
"""
Get the top-k closest vectors, average and re-query
:param ndarray Q:
query vector
:param ndarray data:
index data vectors
:param ndarray inds:
the indices of index vectors in ascending order of distance
:param int... | 637eb1ee04f18725e39709f6868c4d04ebd36b4a | 3,596,751 |
import gzip
import pickle
def load_mnist():
"""
Loads the MNIST handwritten digits dataset into three tuples training_data/
:return: Three tuples containing training data, validation data and test data
"""
f = gzip.open('./data/mnist.pkl.gz')
training_data, validation_data, test_data = pickle... | b688fb8f4f690d3bab83ad42da564cd26d308d0d | 3,596,752 |
import requests
def newSDDCService(proxy_url,sessiontoken,service_id,service_entries):
""" Create a new SDDC Service based on service_entries """
myHeader = {'csp-auth-token': sessiontoken}
proxy_url_short = proxy_url.rstrip("sks-nsxt-manager")
# removing 'sks-nsxt-manager' from proxy url to get corre... | 70d3c14f5ae531e7a4f13e789e39730eba3bf3f4 | 3,596,753 |
def tacacsplus_provider_group_provider_get(handle, group_name, name,
caller="tacacsplus_provider_group_provider_get"):
"""
checks if a tacacsplus provider added to a tacacsplus provider group
Args:
handle (UcsHandle)
group_name (string): tacacsplus provider group... | 7e048939772c97fba7ca05f13c68abf599a24060 | 3,596,754 |
def hardnet68(**kwargs):
"""
HarDNet-68 model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Loca... | 4d316d64c05f1f92f099f4dec8dabad9ad0c23c1 | 3,596,755 |
def cdl(sqrtchi = 2, corechi = 1, isSym = False):
"""
generate a random corner double line tensor
Parameters
----------
sqrtchi : integer, optional
dimension of the matrix, equal to square root of the bound
dimension chi. The default is 2.
Returns
-------
cdlT : four-le... | fee6aff070c3cfa3f6c4b57fde5d4504f783b4f1 | 3,596,756 |
def commentify(environment: Environment, value: str, indent=0, wrap_in_brackets=False):
"""
Builds a comment.
"""
if not value:
return
value = indented_wordwrap(environment, value, indent=(" " * indent) + "-- ", first=False)
if wrap_in_brackets:
return "\< " + value + " \>"
else:
return value | 5df8229c125eed452a5c52a80fc44799060419f9 | 3,596,757 |
from typing import Counter
def count_word_num(corpus: list):
"""Count words
:param corpus: two-dimensional list
:return: list, the element is Count type
"""
word_list = split_sentence(corpus)
count_list = []
unrepeated_word_list = []
for i in range(len(word_list)):
# The Counte... | 9b07974953611d0ee63cd7ff30f97a0d56aa357f | 3,596,758 |
from operator import sub
from operator import mul
def jcbn(S1,S2):
""" Jacobian Determinant
<div class=jython>
JCBN ( S1, S2 ) = DDX (S1) * DDY (S2) - DDY (S1) * DDX (S2)
</div>
"""
return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) | 2670087a1dae84bc5597c117e0a54a665b7045ec | 3,596,759 |
def bangbang_compressor(bangbang_protocol
):
"""Compresses the bang bang protocol.
Merges chunks of contiguous bangbang chunks into a Tuple of duration (in
number of chunks) and which Hamiltonian to apply.
Args:
bangbang_protocol: List of HamiltonianType values, determines which
... | 7e3b6e0e5678e705c54c39e31561a908900d9b08 | 3,596,760 |
def id_has_suffix(suffix):
"""
Select cases that have a case id suffix `suffix`.
Note that this is not the suffix of the whole case function name, but the case id,
possibly overridden with `@case(id=)`
"""
return CaseFilter(lambda case: CaseInfo.get_from(case).id.endswith(suffix)) | 9df53a776aa150028e8ef6291933cab62d0c107e | 3,596,761 |
def CountGroups(fingerprint_groups: list, group_labels: list, d: dict) -> list:
"""Count groups for fingerprint."""
return [
[[x[0] for x in d[y]].count(z) for z in fingerprint_groups[i]]
for (i, y) in enumerate(group_labels)
] | 37e7c95abf6d69cc66c0cfb449827ba7e26db66a | 3,596,762 |
from datetime import datetime
def now_str(fmt=NOW_TS_FORMAT):
""" A timestamp string to the current second to use as for logging. """
return datetime.now().strftime(fmt) | 1eb9af1189ca86fed36a84904a0290610ccf4fd3 | 3,596,763 |
async def _state_error(user_pkg: UserAuthPackage) -> tuple[str, UserAuthPackage]:
"""State is an endpoint for all non-recoverable errors. Sets user authorized to False.
Transition(s):
None
Parameters
----------
user_pkg : UserAuthPackage
Instance of UserAuthPackage which stores au... | f2af1d9164ac2b387668236458aa1bd21f32f822 | 3,596,765 |
def add_data_statistics(axes, parser, obs, conditions,
condition_repr='master'):
"""Add dynamics of single observable statistics.
Parameters
----------
axes : list of :class:`matplotlib.axes.Axes`
parser : :class:`Parser` instance
obs : :class:`Observable` instance
c... | c1796d76e8597053a1dd152ad453277251036c1e | 3,596,766 |
def start_movement(body): # noqa: E501
"""Communication between DMEs. Signals the other DME to prepare for movement
# noqa: E501
:param body: Target path for creation
:type body: dict | bytes
:rtype: None
"""
if connexion.request.is_json:
body = StartDM.from_dict(connexion.reque... | 464f30b2ce3bd9aff4793f3afde15bd551fd4452 | 3,596,768 |
def trace_edges(segmentation):
"""
Traces segments, assumes a 4-connectivity between pixels.
Pixel centers lie at [x.5, y.5], vertices are at [x.0, y.0].
:param segmentation:
:return:
"""
edges = []
height = len(segmentation)
width = len(segmentation[0])
widthp = width + 1
... | cb9b6647156812d4f67cf3215df2904832e61146 | 3,596,769 |
def getThreshold(data):
"""Get threshold according to balanced histogram thresholding method.
( https://en.wikipedia.org/wiki/Balanced_histogram_thresholding )
Parameters
----------
data : list
list of values
Returns
-------
float
threshold
"""
def getIndex(en... | a2e54de8ba9358296aaddd5e3b5acacdccba7a4d | 3,596,770 |
def create_indexed_image_non_dither(original, rgb_palette):
"""Create a indexed image given the original image and the palette, without dithering."""
pil_palette = create_pil_palette(rgb_palette)
newimage = Image.new('P', original.size)
newimage.putpalette(pil_palette)
# The paste() method... | 693379af0b2d75d2af9ddee806a15ab5fc4724fc | 3,596,772 |
def impute_cumulative_df(df, src_col, dst_col, groupby_col):
"""Calculates imputed columns and returns
Args:
df (pandas.DataFrame): input DataFrame with a cumulative column
src_col (str): name of cumulative column to impute
dst_col (str): name of imputed cumulative column
groupb... | 0473d96edb871866b60252badbf3054d8c7ae439 | 3,596,773 |
def n_polygonal_number_func(n):
"""
Returns a function to generate the n-gonal numbers for a given n -
mathematically this function is obtained by restricting the general
function, which is a function of two variables n and k, to the given
value of n, e.g. to have a triangular numbe... | ca39c5c14d712c5cd3cecb620698f7c59b46b485 | 3,596,775 |
def isStakeBase(tx):
"""
Whether or not a tx could be considered as having a topically valid stake
base present.
"""
# A stake base (SSGen) must only have two transaction inputs.
if len(tx.txIn) != 2:
return False
# The previous output of a coin base must have a max value index and
... | fe52d5fa9ef1173c5b4de0405fff764c6f1a95d6 | 3,596,776 |
def mape(y_true, pred):
"""Metric for evaluating predictions"""
mape = 100 * np.mean(abs(y_true - pred) / y_true)
return mape | cea9d48a54051003b6db1bdf59eff65f6de83eaa | 3,596,777 |
def n_eff(stan_fit, pars):
"""Extracts n_eff from stan model's summary as a pandas dataframe.
Only considers parameters (Not all variables specified in stan's model).
Note that, when DDM parameters are estimated at a trial level, these are included in the n_eff stats.
Returns
-------
convergence... | 2a4381207fe8b636f44d7678bd929dbc92238632 | 3,596,778 |
def identify_species_in_target(ctx, target, rect_structs):
"""
Identify any species in the given target's image using the rectangles defined in rect_structs.
Returns a tuple (detected_species, error_msg). If detected_species is not None, it will contain
a list of all species IDs that were detected. If i... | 119b5f67bf3ed8f70695978473a3b77f2e31688b | 3,596,779 |
async def get_user(username: str) -> UserPydantic:
"""Get user info."""
return await UserPydantic.from_queryset_single(User.get(username=username)) | acdb82709850beb0a761a2163924d97294241605 | 3,596,780 |
def get_root(w: tk.Widget):
"""Get root widget
Args:
w (Widget): Widget
Returns:
The root widget"""
return w._nametowidget(w.winfo_parent()) # pylint: disable=W0212 | 159024604b5fd0f5e1f4cb3d518a65d318c1bc22 | 3,596,781 |
def add_donation(name, amount):
"""
add a donation to the database
"""
# If this is a new user, ensure that the database has the necessary
# data structure.
donor = find_donor(name)
if donor is None:
donor = add_donor(name)
# Record the donation
donor[1].append(amount)
... | e1525e3cd9197417c7c4ca6a3d3e5e374b66d71e | 3,596,782 |
async def experiencia_create(
request: Request,
experiencia: ExperienciaProfCreate,
db=Depends(get_db),
current_pessoa=Depends(get_current_active_pessoa),
):
"""
Create a new experiencia profissional
"""
return await create_experiencia(db, experiencia, current_pessoa.id) | 5366d88e6c3c8e7dcdead64229bcf9a5d61de5ad | 3,596,783 |
def get_denoise_kernel():
"""
Create a bell curve with a certain std.
Returns:
A kernel (length=7) that can be used to denoise the data
"""
kernel = norm.pdf(np.arange(-3, 4), 0.0, 1.0)
return kernel / np.sum(kernel) | 0d2d9f6d1031cdae8911dd0c79ee6665f219f28e | 3,596,784 |
def bf_get_snapshot_input_object_text(key, encoding="utf-8", snapshot=None):
# type: (Text, Text, Optional[Text]) -> Text
"""Returns the text content of the snapshot input object with specified key."""
with bf_get_snapshot_input_object_stream(key, snapshot) as stream:
text = stream.read().decode(enc... | eb44e72536a4702ed43b97912821455785c69022 | 3,596,785 |
def gdl_loss(gen_CT, gt_CT, alpha, batch_size_tf):
"""
Calculates the sum of GDL losses between the predicted and ground truth images.
@param gen_CT: The predicted CTs.
@param gt_CT: The ground truth images
@param alpha: The power to which each gradient term is raised.
@param batch_size_tf batc... | 207f6aad4cdb1e56d5799fd4d4865120740fa267 | 3,596,786 |
def convert_to_array(xx, mapped_type=None):
""" convert something to a Numpy Array """
if mapped_type is None:
mapped_type = get_type(xx)
if mapped_type is None:
return convert_to_array(convert_to_dataframe(xx))
if mapped_type == DataTypes.DataFrame:
return xx.values
elif... | df709565922797b06f40e3d0140b185e2a9b9588 | 3,596,787 |
def delete_user_by_login(login):
"""
Deletes the user with the given login.
:param login: The login of the user to be deleted.
:return: The response of the api.
"""
if login == configuration.GRAFANA_AUTH[0]:
logger.info("The user '%s' is used by this script for accessing Grafana thus wil... | 98096f3ef214f7e7829b9448de1bfefe7aa55d79 | 3,596,789 |
def getArgumentParser():
"""
@brief Provide a arguemnt parser with standard arguments for all pipelines.
"""
parser = ArgumentParser()
parser.add_argument('-H', '--host', dest='host', type=str, default='localhost',
help='Host interface to bind to')
parser.add_argument('-p',... | e819b61029f49743b599717bf63de31370732843 | 3,596,790 |
def logout():
"""
Handle requests to `/logout` route
Logout a user from session
"""
logout_user()
flash('You have been successfully logged out')
return redirect(url_for('auth.login')) | a35dabc113394856352fc81862898ce932d7de6f | 3,596,791 |
def tryConvert(cell):
"""
convert a cell, if possible, to its supposed type(int, float, string)
note: type of NaN cell is float
"""
try:
return int(cell)
except ValueError as TypeError:
try:
return float(cell)
except ValueError as TypeError:
return... | d7841bc2bf3c5a330a67cd54df90d67b4ff70966 | 3,596,792 |
def get_telescope_types(limit: int) -> Response:
"""Get a list of TelescopeType objects.
:param limit: the maximum number of TelescopeType objects to return.
:return: a Response object.
"""
return get_items(TelescopeType, limit) | 1aa492c438fd767e6282e20c02d2172672e3062d | 3,596,793 |
def getUpgrades(eUnit):
"""Returns the set of all units to which eUnit can upgrade."""
return upgradeUnits[eUnit] | 5d898fa891a75e1c48b96c74deb24f3bad707826 | 3,596,794 |
from typing import List
from typing import Optional
def make_operation(
args: List[Arg],
params: Optional[list] = None,
op_type: Optional[str] = "ID",
raw_op: Optional[Op] = None,
id_num: Optional[str] = None,
) -> ParsedOperation:
"""Construct an operation from a command"""
if params is N... | 7f75cd81c52f3da8e130b46416dc647b2f9259a6 | 3,596,795 |
def get_importer_handler(exc, log):
"""Get correct exception handler."""
if exc.__class__ in importer_exception_handlers:
handler = importer_exception_handlers[exc.__class__]
if handler is not None:
return handler
else:
log.set_failed(exc)
raise exc | 118a95a22e3a96f90c4887b999e724ae8c208e5d | 3,596,797 |
import yaml
def load_config(filename):
"""Load and return a config file."""
with open(filename, 'r') as f:
config = yaml.safe_load(f)
return config | 5c981d7a5aa7846486062c14c940cdb01cb0b5af | 3,596,798 |
def get_rnasc_sstructures(f):
"""Read the fasta file.
Input: f: HANDLE to input. e.g. sys.stdin, or open(<file>)
Return a secondary structure list.
"""
seqss_sstrucs_list = []
seqss_list = read_rnasc_fasta(f)
for seqss in seqss_list:
seqss_sstrucs_list.append(seqss.sstruc)
retu... | 5dcf5aea2910a63c2a0dc61d56f048351b7a6d60 | 3,596,800 |
def get_records_with_tag(inp,tag):
"""
Given a filename or an element tree in *inp*, return all records
matching *tag*
"""
if type(inp) == type(''): # Assume inp is a filename
inp = read_cml(inp)
return inp.findall(".//%s" % tag) | fb75dabedab7125bda5c0185fde368b5ad58bb69 | 3,596,801 |
def call(current: float, volatility: float, ttm: float, strike: float,
rf: float, days_in_year: int=cfg.days_in_year) -> float:
"""Function to compute the value of an Asian (i.e. average value) Call
Option under the Black-Scholes model world heuristic. The option is
parameterized using the underlyin... | f2a8d2a44b559598c7211ffe3e3f37f033dc4ea9 | 3,596,803 |
def flag_int2bits(flag_integer):
"""transform an integer value to bits. Input can be time series or scalars"""
# format input
if len(np.shape(flag_integer)) == 0: # input is scalar
flag_integer = np.array([[flag_integer]])
elif not isinstance(flag_integer, np.ndarray):
raise WrongInputF... | ce13844bb1bc4b4d33d7c7dced27f265b82cc90b | 3,596,804 |
import logging
def _maybe_pubsub_notify_now(result_summary, request):
"""Examines result_summary and sends task completion PubSub message.
Does it only if result_summary indicates a task in some finished state and
the request is specifying pubsub topic.
Returns False to trigger the retry (on transient error... | 6092e313d4a14ce7931f2d486062aa4a93debb03 | 3,596,805 |
def variant_position_within(coordsVar, coordsInterval):
"""
check if coordsVars is within coordsInterval. Return 0
"""
if coordsVar.CHROM == coordsInterval.seqid:
if coordsVar.POS >= coordsInterval.start:
if coordsVar.POS <= coordsInterval.end:
return(1)
... | 4f0cf0b6ce0d698eba5d30c0540efbf175704ea7 | 3,596,806 |
def encode_res(encoder):
"""Create a decorator that applies `encoder` to the return value of the
decorated function.
"""
@decorator
def new_f(f, *args, **kwargs):
res = f(*args, **kwargs)
return encoder(res)
return new_f | 2cfaa78789cb38e37514ee749e41b601f61b6772 | 3,596,810 |
def get_password_token(request, identifier='Password'):
"""
"""
if not (auth_string := request.headers.get('AUTHORIZATION')):
return None
return auth_string[len(identifier) + 1:] | 840146387e31b452cc7987413606adc6511d4309 | 3,596,811 |
import math
def torusTopology(elementList):
"""Creates a the adjacency list for a full meshed topology out of a linear
list of all elements in the network.
:param list[string] elementList: A list of all elements in the network.
"""
if not math.sqrt(len(elementList)) % 1 == 0:
raise Runtime... | 8f5834e180574936f9e256d804af0a16de3d0892 | 3,596,812 |
def tile(input, multiples):
"""
Constructs a tensor by tiling a given tensor.
Parameters
----------
input : tensor
A Tensor. 1-D or higher.
multiples : tensor
Must be one of the following types: int32, int64. 1-D.
Length must be the same as the number of dimensions in in... | 526b518d02593f315038ef61e67d7d42fedb8f47 | 3,596,813 |
def mean_negative_pois_llh(X, *, theta, beta, **kwargs):
"""Mean Poisson log-likelihood for each nonzero entry
Parameters
----------
X: coo_matrix
Data to compute Poisson log likelihood of. Assumed to be nonzero.
theta : HPF_Gamma
beta : HPF_Gamma
**kwargs : dict, optional
e... | bfe7b76fbb875377fce0916385c5d4ea1c81758a | 3,596,814 |
def argmin_except_c(x,p,c):
"""
argmin_except_c(x,p,c)
Ensure that p is the argmin, i.e. the position of the minimum value
in x, but ignores any value of c.
Note:
- If there are many minimum values then argmin_except_c(x,p,c) will find
all these values.
- We assume that there are at least one valu... | 8046dddc15113ccb5c75fb62ce9ff5434104811e | 3,596,815 |
def dist_list2dict(dist_list, group_id=1):
"""
将 距离列表 转换成 距离字典
:param dist_list:[1,2,3,4,5,6,7,8]
:param group_id:3
:return:{1-2-0:1, 1-2-1:2, 1-2-2:3,...}
"""
if not isinstance(dist_list, list):
# 如果dist_list 不是列表,则不作处理
return dist_list
dist_dict = {}
for n in range(... | 274975f63f9fc3a537fbed0472d0b7ad2d1c2855 | 3,596,816 |
def normalize_data_format(value):
"""Checks that the value correspond to a valid data format.
Copy of the function in keras-team/keras because it's not public API.
# Arguments
value: String or None. `'channels_first'` or `'channels_last'`.
# Returns
A string, either `'channels_first'`... | 6f1935a77d40f4a92284ea0795b51453fbe12364 | 3,596,817 |
def pdt(input_file, lamada, sw_dir):
"""Execute pdt command and generate feature vectors.
:param input_file: the input sequence file in FASTA format.
:param lamada: the value of parameter lamada.
:param sw_dir: the main dir of software.
"""
output_file = pdt_cmd_(input_file, lamada, sw_dir)
... | 4edf87a2e68678ff07a9fecd2bf9853ef883781a | 3,596,819 |
from typing import Optional
from typing import List
async def direct_threads(sessionid: str = Form(...),
amount: Optional[int] = Form(20),
clients: ClientStorage = Depends(get_clients)) -> List[DirectThread]:
"""Get all threads from inbox
"""
cl = clients.g... | 9d9726e85d59825f5ebe05087a2a121fcc48c17e | 3,596,820 |
from datetime import datetime
def transaction_from_sheets_values(values):
"""De-parse from sheets values.
Parameters
----------
values : list
Returns
-------
Transaction
"""
return Transaction(
id=values[0],
account=values[1],
date=datetime.strptime(values... | 355167a15bbc329e12b16f523dce49e4773baf35 | 3,596,821 |
import io
def ExtractErrorMessage(error_details):
"""Extracts error details from an apitools_exceptions.HttpError.
Args:
error_details: a python dictionary returned from decoding an error that
was serialized to json.
Returns:
Multiline string containing a detailed error message suitable to sho... | 9932afa111bc3cbf5b627d17622b35f3b55b0999 | 3,596,822 |
def uAna(x, L, v, D):
"""
u = \frac{1 - \e(-v_x x / D)}{1 - \e(-v_x L / D)}
Check for -v -- herleiten
"""
return (1 - np.exp(v * x / D))/(1. - np.exp(v * L / D)) | 9b017039ac8ce9ae432748539328b3d8c13ca841 | 3,596,823 |
def np_size(net):
"""
Calculate count of al network parameters (weight, bias, etc...)
"""
size = 0
for l in net.layers:
for prop in l.np.values():
size += prop.size
return size | d573d62f54eeb2beed0e8035c3635a46fdf4a9da | 3,596,825 |
from datetime import datetime
def get_index_components_history(index: str = 'SPX', start_date=None, end_date=None, freq='M'):
"""Get the historical components between start_date and end_date at a given frequency (e.g. monthly)
Args:
index: The index to get components for. Default = 'SPX'
star... | 07f2c437699b5043750046a9ab8c55ce8345624b | 3,596,827 |
def poisson_cuts(data,
mode = 'fit',
label = None,
force_cuts=False,
retention_data=None,
Bg_data=None,
m0=None, m1=None, f0=None, f1=None):
"""
A function that fits data to a two poissonian curve then extracts... | 2284d8f36e65522ad6eabaec97feaf4ca5f1c284 | 3,596,828 |
def load_transform_from_hdf5_file(file_name):
"""
Loads a `distpy.transform.Transform.Transform` object from an hdf5 file.
Parameters
----------
file_name : str
the name of the hdf5 file from which to load the
`distpy.transform.Transform.Transform`
Returns
-------
... | 81fbbe4f95b2491a33e23a56aaaf5b0424aa50ea | 3,596,830 |
def build_generator(inputs, labels, image_size):
"""Build a Generator Model
Inputs are concatenated before Dense layer.
Stack of BN-ReLU-Conv2DTranpose to generate fake images.
Output activation is sigmoid instead of tanh in orig DCGAN.
Sigmoid converges easily.
Arguments:
inputs (Laye... | b384b1a4153a69f4d00df7ef057343ca0af5f1ee | 3,596,831 |
def run_image(img, rgb=True, width=32, height=32):
# Histogram normalization in v channel only
# rgb add Lightness
"""
:type height: int
:type width: int
:type rgb: True
:type img: np.ndarray
:rtype: np.ndarray
"""
# central square crop
# get minimum shape height or width
... | 7fac73a0f55b20f9aa5a9588f538a9d509698f9d | 3,596,832 |
def macd(candles: np.ndarray, fastperiod=12, slowperiod=26, signalperiod=9, source_type="close",
sequential=False) -> MACD:
"""
MACD - Moving Average Convergence/Divergence
:param candles: np.ndarray
:param fastperiod: int - default: 12
:param slow_period: int - default: 26
:param sign... | 854a5407a74895f4b9b1a125eaf696f4470356e2 | 3,596,833 |
def compute(n: int) -> float:
"""
Compute the recursive sum ``s = 1 / (1**2) + 1 / (2**2) + ... + 1 / (n**2)``
>>> compute(0)
0
>>> compute(4)
1.4236111111111112
"""
if n == 0:
return 0
return sum(1 / (i ** 2) for i in range(1, n + 1)) | 974506e3523f1c0cfe646b1fdf54846ff7f96cc4 | 3,596,835 |
def get_internet_gateways(client, name, values, dry=True):
"""
Get internet gateways IPs by searching for stuff
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_internet_gateways
"""
try:
return client.describe_internet_gateways(Filters=... | 0de3882c5682c67cb37d885449bb20d7415b58eb | 3,596,836 |
def plot_pca_3d(s_obj, sample_id=None, pheno_id="isoniazid", hq_model_rank=0, lr_pval_thresh=1.0,
models_df=pd.DataFrame(),
FILTER_RXN_DIR=True, STANDARDIZE=False, figSIZE=(7, 5), ELEV_=-120,AZIM_=110,
alpha=0.7, s_size=20, labelsizes=10, labelpad=4.0, f_scale=1.0, show... | 9cb88ba69cc3f4cae8f33f104ade3038ab46fcf4 | 3,596,837 |
import glob
def fill_kwargs(fn, args, kwargs):
""" Read a csv file and fill up kwargs
This normalizes kwargs against a sample file. It does the following:
1. If given a globstring, just use one file
2. Get names from csv file if not given
3. Identify the presence of a header
4. Identify... | a5cf6a31b055965135073a083a48e38ac0e8278d | 3,596,838 |
def _ConstructSoftwareConfigurationSchedulerCountPatch(
scheduler_count, release_track=base.ReleaseTrack.GA):
"""Constructs a patch for updating scheduler count for Composer 1.*.*.
Args:
scheduler_count: number of schedulers.
release_track: base.ReleaseTrack, the release track of command. Will dictate
... | d0131828fa481406b04465a4360198161e61c045 | 3,596,839 |
def _mangle_table_get(obj, index):
"""
mangle indexing of object
e.g. obj[0, 0, 1] = obj[1] if obj.ndim == 1
e.g. obj[0, 0] = obj if obj.ndim == 0 or obj doesn't have ndim
"""
if hasattr(obj, 'view') and obj.view == 'bcast':
index2 = index
elif not hasattr(obj, 'ndim') or obj.ndim ... | 20f73ae6d62e5411dfd2d6c34827465537218e11 | 3,596,840 |
def test_gnu_make_support_old():
"""
Test if the system 'make' supports the job server implementation.
This simply checks if the `--jobserver-fds` option is supported by the
`make` command. It does not tests if the jobserver is actually working
properly.
"""
return test_gnu_make_support_co... | 65a1ce59737361dc2226c06fa92e7946a1d07608 | 3,596,841 |
def get_tile_montage(config, image_dir, hyperstack, icyc=0, iz=0, ich=0, ireg=0, bw=0, bv_fn=None):
"""Generate a montage image for a specific cycle, z-plane, channel, and region
This function supports both raw, flattened 2D images as well as consolidated, 5D
hyperstacks (as determined by `hyperstack` arg... | c8b2e38ba2a7b97f9d7f52dd19fed00b1268573f | 3,596,842 |
def extract_EEEBBB_mbb(mbb_inv):
"""this routine extract the E and B part of the mode coupling matrix
Parameters
----------
mbb_inv: 2d array
the inverse spin0 and 2 mode coupling matrix
"""
mbb_inv_array = so_mcm.coupling_dict_to_array(mbb_inv)
mbb_array = np.linalg.inv(mbb_inv_a... | 38b8e120069815a69337e79dcb8710e97be799af | 3,596,843 |
def download_tlds(url):
"""
Returns the (stripped) lines from the given URL that are not
comments.
The URL is assumed to a be that of a text file (no HTML parsing is
performed).
Comment lines start with `#`.
"""
# This is a separate function in order to isolate any future changes
#... | 59917f144cdee28dfc4a25da50db6e968f402c63 | 3,596,844 |
def usgs_phosphate_parse(*, df_list, source, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:return: df, parsed and partially formatted to flowbyactivity
specifications
... | 66b2f2b16e96870d543688579826babeead57ce7 | 3,596,846 |
from typing import Dict
from typing import Any
async def refresh_tokens_controller_mock() -> Dict[str, Any]:
"""Mock refresh tokens controller."""
return {
"access_token": "test",
"refresh_token": "test",
"expires_at": 0,
} | 9431f1311a1c0fa45a3e538ee70f66f0ef9de477 | 3,596,847 |
def ESearchResultParser(result_as_string):
"""Parses an ESearch result. Returns ESearchResult object."""
if '414 Request-URI Too Large' in result_as_string:
raise ValueError, "Tried to pass too large an URI:\n" + result_as_string
doc = parseString(result_as_string)
#assume one query result -- ma... | c9aa0f9c19c95b71874c3c76b3bb88b1397f1938 | 3,596,848 |
from typing import Tuple
def connect() -> Tuple[Cluster, Session]:
"""
Description: This method will connect to a Cassandra instance and
set the keyspace
Returns:
Optional[Tuple[cassandra.cluster.Session], None]: Session to the
connection to Cassandra. If method terminates prior t... | f40dc639eeb3dc96e756ab78c8961d6b7176ee72 | 3,596,850 |
def _unbinned_nll_tf(model: ztyping.PDFInputType, data: ztyping.DataInputType, fit_range: ZfitSpace, log_offset=None):
"""Return unbinned negative log likelihood graph for a PDF.
Args:
model: PDFs with a `.pdf` method. Has to be as many models as data
data:
fit_range:
Returns:
... | aa6055e94393e8f6bb168d6066365f3f91026772 | 3,596,851 |
def nest_sweeps(outer: Sweep, inner: Sweep) -> Sweep:
"""Nest two sweeps.
Iteration over the combined sweep will execute the full inner sweep for each
iteration step of the outer sweep.
"""
outer_specs = outer.get_data_specs()
outer_indeps = [s.name for s in outer_specs if s.depends_on is None]... | 35684cd6ab862440ef72a61f315991a94a478b0c | 3,596,852 |
def spectrogram_to_image(
signal, batch_first=False, color='viridis', origin='lower'):
"""
For more details of the output shape, see the tensorboardx docs
Args:
signal: Shape (frames, batch [optional], features)
batch_first: if true mask shape (batch [optional], frames, features]... | ff7af57d5e755127a0c30871d0bc3b663167f38f | 3,596,853 |
import json
def build_datagram_from_raw_message(fds, str_md, str_cmd_params):
"""
Build SBusDatagram from raw message received over sbus
:param fds: A list of file descriptors (integer) to pass with
the command
:param str_md: json serialized metadata dict
:param str_cmd_params: js... | 181fed80689a83537cf4d53ddd62f487a5c10763 | 3,596,854 |
def _basename(emane_model: "EmaneModel", interface: CoreInterface = None) -> str:
"""
Create name that is leveraged for configuration file creation.
:param emane_model: emane model to create name for
:param interface: interface for this model
:return: basename used for file creation
"""
nam... | 78d3148e587a52c649442a208c3a4b33ef86d633 | 3,596,855 |
def get():
"""
Gets the value of the first switch that it finds
"""
resp = _send('GetBinaryState')
tagValue = conn.extractSingleTag(resp, 'BinaryState')
return True if tagValue == '1' else False | 28ab151308c483bf4eef6d4ac5fe70bf026ee5eb | 3,596,856 |
def get_loglength(seq):
"""Compute loglength of the sequence.
Parameters:
-----------------------
seq: str,
peptide sequence
"""
return (np.log(len(seq))) | 5a7741dc1b4133b3471f116804b76080b7deb7b1 | 3,596,857 |
def to_slice(k, forty_five_deg, D_dimensions_to_check):
"""
:param k: axis idx.
:param forty_five_deg: bool determining if to slice in 45 deg.
:param D_dimensions_to_check: The dimensions to check by the user.
:return: When to slice the volume (in which axis/45 deg angles).
"""
if k not in D... | bfd4db06603fa9d1832b96c8b11edad7e2485bbb | 3,596,858 |
from typing import List
def get_data_names(header: Header) -> List[str]:
"""Return names (labels) of data."""
return header["Common"]["Data"]["Order"] | 8c5fadc028ed9cf779874682b59f7eceeb9989df | 3,596,860 |
import warnings
def get_table_caption():
"""Sets table caption.
Based on the testbedsettings.current_testbed
and genericsettings.runlength_based_targets.
"""
table_caption_one = r"""%
Expected runtime (\ERT\ in number of function
evaluations) divided by the respective ... | 0d777781b998e78307e7b01b195397c93e21af5b | 3,596,861 |
from typing import List
def expand_params(command: AnySlashCommand) -> List[Option]:
"""Update an option with its params *in-place*
Returns the created options
"""
sig = signature(command.callback)
_, inter_param, params, injections = collect_params(command.callback)
if inter_param is None:
... | adc106b8a9660ed1f66507e0ea1f57ec6332ca20 | 3,596,862 |
def GetFloat(Feature):
"""GetFloat(Feature) -> Value
Parameters:
Feature: str
Return value:
Value: ctypes.c_double"""
if _at_camera_handle is not None:
return _at_core_lib.AT_GetFloat(_at_camera_handle, Feature)
else:
raise AndorError('Andor library not initialized') | c5d5337d58b8aed0f9a6aef341489d327338610b | 3,596,863 |
def plot_scatter_from_table_iterator(table_iterator, figure, options):
"""Plots a 2D scatterplot whose points come from the given `table_iterator`.
The plot will be drawn on `figure`."""
xss, yss = [], []
for values in table_iterator:
# Odd number of columns? If so, skip this line.
if l... | a71991065a082d75c21d001cc0e94d468daedd3d | 3,596,864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.