uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4aaab4d7cb11a67da770f7aa | train | function | def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None):
"""
Detect missing and unexpected layers and load the TF weights accordingly to their names and shapes.
Args:
model (`tf.keras.models.Model`):
The model to load the weights into.
reso... | def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None):
| """
Detect missing and unexpected layers and load the TF weights accordingly to their names and shapes.
Args:
model (`tf.keras.models.Model`):
The model to load the weights into.
resolved_archive_file (`str`):
The location of the H5 file.
ignore_mismatched_si... | (output.keys()) and name != "args":
output[name] = kwargs.pop(name, signature[name].default)
# When creating a SavedModel TF calls the method with LayerCall.__call__(args, **kwargs)
# So to respect the proper output we have to add this exception
if "args" in output:
if output["args"] is... | 256 | 256 | 1,070 | 21 | 234 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | load_tf_weights | load_tf_weights | 494 | 602 | 494 | 494 | 3ad6754b3ca9a11f3c67f3ea0cd25e36c27130a0 | bigcode/the-stack | train |
23e80037f04d0eb976eada96 | train | class | class TFQuestionAnsweringLoss:
"""
Loss function suitable for question answering.
"""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
start_loss = loss_fn... | class TFQuestionAnsweringLoss:
| """
Loss function suitable for question answering.
"""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
start_loss = loss_fn(labels["start_position"], logi... | 1,)), -100)
reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, shape_list(logits)[2])), active_loss)
labels = tf.boolean_mask(tf.reshape(labels, (-1,)), active_loss)
return loss_fn(labels, reduced_logits)
class TFQuestionAnsweringLoss:
| 64 | 64 | 106 | 7 | 57 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFQuestionAnsweringLoss | TFQuestionAnsweringLoss | 192 | 204 | 192 | 192 | b0929789ff29e7b2ccf1daf5a21a65086e309208 | bigcode/the-stack | train |
003026916654f9e178e4fa09 | train | class | class TFMaskedLanguageModelingLoss(TFCausalLanguageModelingLoss):
"""
Loss function suitable for masked language modeling (MLM), that is, the task of guessing the masked tokens.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
| class TFMaskedLanguageModelingLoss(TFCausalLanguageModelingLoss):
| """
Loss function suitable for masked language modeling (MLM), that is, the task of guessing the masked tokens.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
| def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
return loss_fn(labels, logits)
class TFMaskedLanguageModelingLoss(TFCausalLanguageModelingLoss):
| 64 | 64 | 71 | 15 | 49 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFMaskedLanguageModelingLoss | TFMaskedLanguageModelingLoss | 261 | 270 | 261 | 261 | c291afdacebe59ac6d7381bbce12b61608d503c9 | bigcode/the-stack | train |
f47bd11905ae41ddf0b1bc41 | train | class | class TFNextSentencePredictionLoss:
"""
Loss function suitable for next sentence prediction (NSP), that is, the task of guessing the next sentence.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, ... | class TFNextSentencePredictionLoss:
| """
Loss function suitable for next sentence prediction (NSP), that is, the task of guessing the next sentence.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, labels, logits):
loss_fn = t... | """
Loss function suitable for masked language modeling (MLM), that is, the task of guessing the masked tokens.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
class TFNextSentencePredictionLoss:
| 63 | 64 | 209 | 7 | 56 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFNextSentencePredictionLoss | TFNextSentencePredictionLoss | 273 | 294 | 273 | 273 | 4c3cf0e856e32deba1eb5fd9417ceea6a9e35777 | bigcode/the-stack | train |
210f61eea4d6362f85e24944 | train | function | def keras_serializable(cls):
"""
Decorate a Keras Layer class to support Keras serialization.
This is done by:
1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at
serialization time.
2. Wrapping `__init__` to accept that `transformers_co... | def keras_serializable(cls):
| """
Decorate a Keras Layer class to support Keras serialization.
This is done by:
1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at
serialization time.
2. Wrapping `__init__` to accept that `transformers_config` dict (passed by Keras a... | ]
def dummy_loss(y_true, y_pred):
return tf.reduce_mean(y_pred)
class TFModelUtilsMixin:
"""
A few utilities for `tf.keras.Model`, to be used as a mixin.
"""
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get the number of (optionally, trainable) parameters i... | 169 | 169 | 565 | 6 | 163 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | keras_serializable | keras_serializable | 105 | 167 | 105 | 105 | 195f2d6d0f39e5e19ed550c005649896b05962ad | bigcode/the-stack | train |
dca87b487693d52de1dac3d6 | train | class | class TFSharedEmbeddings(tf.keras.layers.Layer):
r"""
Construct shared token embeddings.
The weights of the embedding layer is usually shared with the weights of the linear decoder when doing language
modeling.
Args:
vocab_size (`int`):
The size of the vocabulary, e.g., the num... | class TFSharedEmbeddings(tf.keras.layers.Layer):
| r"""
Construct shared token embeddings.
The weights of the embedding layer is usually shared with the weights of the linear decoder when doing language
modeling.
Args:
vocab_size (`int`):
The size of the vocabulary, e.g., the number of unique tokens.
hidden_size (`int`)... | nx (`int`):
The number of input features.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation to use to initialize the weights.
kwargs:
Additional keyword arguments passed along to the `__init__` of `tf.keras.layers.Layer`.
"""
... | 256 | 256 | 863 | 10 | 245 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFSharedEmbeddings | TFSharedEmbeddings | 1,808 | 1,903 | 1,808 | 1,808 | b96c953fa2294dc72cc46a2fb03df533f9227740 | bigcode/the-stack | train |
3e324437da4e3ad8fc79c0f7 | train | function | def dummy_loss(y_true, y_pred):
return tf.reduce_mean(y_pred)
| def dummy_loss(y_true, y_pred):
| return tf.reduce_mean(y_pred)
| Union[
List[tf.Tensor],
List[np.ndarray],
List[KerasTensor],
Dict[str, tf.Tensor],
Dict[str, np.ndarray],
Dict[str, KerasTensor],
tf.Tensor,
np.ndarray,
KerasTensor,
]
def dummy_loss(y_true, y_pred):
| 64 | 64 | 17 | 9 | 55 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | dummy_loss | dummy_loss | 79 | 80 | 79 | 79 | fee0a487c19646bd3a17973d06a8dc9b1a291114 | bigcode/the-stack | train |
f5e80ad8125a189ff293de1a | train | class | class TFTokenClassificationLoss:
"""
Loss function suitable for token classification.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCateg... | class TFTokenClassificationLoss:
| """
Loss function suitable for token classification.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
f... | Crossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
start_loss = loss_fn(labels["start_position"], logits[0])
end_loss = loss_fn(labels["end_position"], logits[1])
return (start_loss + end_loss) / 2.0
class TFTokenClassificationLoss:
| 70 | 70 | 236 | 6 | 63 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFTokenClassificationLoss | TFTokenClassificationLoss | 207 | 232 | 207 | 207 | d9971e053aa8e7ad446bbf1184f2ea83de19c049 | bigcode/the-stack | train |
0813a66fc56fdef37d75e14d | train | class | class Room(Document):
pass | class Room(Document):
| pass | # Copyright (c) 2022, rohit and contributors
# For license information, please see license.txt
#
import frappe
from frappe.model.document import Document
class Room(Document):
| 39 | 64 | 5 | 4 | 34 | rkadlak/Estate-mgmt-task | estate_management/estate_management/doctype/room/room.py | Python | Room | Room | 7 | 8 | 7 | 7 | b213b471116bc0229a9acbe1832450bf1bb82b49 | bigcode/the-stack | train |
ae5287b80d794427abc3bf01 | train | function | def test_tag_protocol_xml():
def tag(text: str, preprocess: bool): # pylint: disable=unused-argument
return [
dict(
token=['Ove', 'är', 'dum', '.'],
lemma=['ove', 'vara', 'dum', '.'],
pos=['PM', 'VB', 'ADJ', 'MAD'],
xpos=['PM', 'VB... | def test_tag_protocol_xml():
| def tag(text: str, preprocess: bool): # pylint: disable=unused-argument
return [
dict(
token=['Ove', 'är', 'dum', '.'],
lemma=['ove', 'vara', 'dum', '.'],
pos=['PM', 'VB', 'ADJ', 'MAD'],
xpos=['PM', 'VB', 'ADJ', 'MAD'],
... | import os
from os.path import join as jj
from unittest.mock import Mock
from uuid import uuid4
import pyriksprot
from .utility import RIKSPROT_PARLACLARIN_FAKE_FOLDER
def test_tag_protocol_xml():
| 51 | 71 | 239 | 6 | 44 | welfare-state-analytics/pyriksprot | tests/tag_test.py | Python | test_tag_protocol_xml | test_tag_protocol_xml | 11 | 35 | 11 | 11 | f36ea99d31ddd8f5b50ce3d2848fea21d15f453b | bigcode/the-stack | train |
22835556ab6383638fbfdbe0 | train | class | class PyTestCommand(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ... | class PyTestCommand(TestCommand):
| user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
class PyTestCommand(TestCommand):
| 45 | 64 | 103 | 7 | 37 | pashcovich/flaskbb | setup.py | Python | PyTestCommand | PyTestCommand | 11 | 26 | 11 | 11 | a734b1ac9e5e797be439352e73f12467fc9c8092 | bigcode/the-stack | train |
79926bde8a3dc55777f6ce0e | train | function | def get_requirements(e=None):
rf = "requirements.txt" if e is None else 'requirements-{}.txt'.format(e)
r = read(rf)
return [x.strip() for x in r.split('\n')
if not x.startswith('#') and not x.startswith("-e")]
| def get_requirements(e=None):
| rf = "requirements.txt" if e is None else 'requirements-{}.txt'.format(e)
r = read(rf)
return [x.strip() for x in r.split('\n')
if not x.startswith('#') and not x.startswith("-e")]
| noqa
errno = pytest.main(self.pytest_args)
sys.exit(errno)
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, *parts), 'r') as fp:
return fp.read()
def get_requirements(e=None):
| 64 | 64 | 63 | 7 | 57 | pashcovich/flaskbb | setup.py | Python | get_requirements | get_requirements | 35 | 39 | 35 | 35 | 592216a63ee4ff925474d85900e05ea913bad7dd | bigcode/the-stack | train |
e20a811322033d0b0fa104a8 | train | function | def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, *parts), 'r') as fp:
return fp.read()
| def read(*parts):
| here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, *parts), 'r') as fp:
return fp.read()
| test_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest # noqa
errno = pytest.main(self.pytest_args)
sys.exit(errno)
def read(*parts):
| 64 | 64 | 40 | 5 | 59 | pashcovich/flaskbb | setup.py | Python | read | read | 29 | 32 | 29 | 29 | 7722f399e33674b6b4c4245f447b7ee5b79ea02c | bigcode/the-stack | train |
75ad8bd20a2cdb3273f42519 | train | class | class GaussianRandomWalks(IrrelevantRedundantMixin, RNGMixin, gym.ObservationWrapper):
"""Add gaussian random walk variables to the observations.
Arguments:
env: a gym environment instance
size: the number of random walks to append to the observation.
loc: mean of the Gaussian distribut... | class GaussianRandomWalks(IrrelevantRedundantMixin, RNGMixin, gym.ObservationWrapper):
| """Add gaussian random walk variables to the observations.
Arguments:
env: a gym environment instance
size: the number of random walks to append to the observation.
loc: mean of the Gaussian distribution
scale: stddev of the Gaussian distribution
"""
def __init__(self, ... | """Wrapper for introducing irrelevant state variables."""
import gym
import numpy as np
from gym.spaces import Box
from .mixins import IrrelevantRedundantMixin, RNGMixin
from .utils import assert_flat_box_space
class GaussianRandomWalks(IrrelevantRedundantMixin, RNGMixin, gym.ObservationWrapper):
| 68 | 107 | 358 | 21 | 46 | angelolovatto/raylab | raylab/envs/wrappers/gaussian_random_walks.py | Python | GaussianRandomWalks | GaussianRandomWalks | 10 | 50 | 10 | 10 | 4547a21ccfd14b2bf8b1da96b2fdc6d3f9b30220 | bigcode/the-stack | train |
c8d38dbe39878c628a3c287c | train | function | def parse_operator(eff_op: Union[EffectiveOperator, Operator]):
"""Parse the operator `eff_op` into matchpy symbols with the SU(2) structure
expanded.
This is an unfortunately messy function and needs to be rewritten in a
cleaner way.
"""
if isinstance(eff_op, EffectiveOperator):
opera... | def parse_operator(eff_op: Union[EffectiveOperator, Operator]):
| """Parse the operator `eff_op` into matchpy symbols with the SU(2) structure
expanded.
This is an unfortunately messy function and needs to be rewritten in a
cleaner way.
"""
if isinstance(eff_op, EffectiveOperator):
operator = eff_op.operator
else:
operator = eff_op
f... | print(start)
while new != old:
# Check if max iterations reached
if counter > max_iterations:
print("Maximum iterations reached on fixed_point")
return new
old = new
new = apply_rules(rules, old)
if verbose:
print(new)
counter += ... | 221 | 222 | 740 | 14 | 207 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | parse_operator | parse_operator | 181 | 259 | 181 | 181 | a79783e36b17551f19dcdd2710b592b5634d95b9 | bigcode/the-stack | train |
d2ce2c8a233cdc8c4ad308e1 | train | function | def apply_rules(rules, subject):
for k, v in rules.items():
for substitution in match(subject, Pattern(k)):
subject = substitute(Pattern(v), substitution)
return subject
return subject
| def apply_rules(rules, subject):
| for k, v in rules.items():
for substitution in match(subject, Pattern(k)):
subject = substitute(Pattern(v), substitution)
return subject
return subject
| nu, RST): Op(Const(ye), hp, nu, nu, RST),
# vev
Op(h0, RST): Op(Const(v), RST),
Op(c(h0), RST): Op(Const(v), RST),
}
def apply_rules(rules, subject):
| 64 | 64 | 45 | 8 | 56 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | apply_rules | apply_rules | 128 | 134 | 128 | 128 | 20c16d4308905b503f429e321735f7bf57c98faf | bigcode/the-stack | train |
dc7bc1892f38c3e081b60390 | train | function | def fixed_point(start, rules=RULES, max_iterations=10, verbose=False):
old, new = None, start
counter = 1
if verbose:
print(start)
while new != old:
# Check if max iterations reached
if counter > max_iterations:
print("Maximum iterations reached on fixed_point")
... | def fixed_point(start, rules=RULES, max_iterations=10, verbose=False):
| old, new = None, start
counter = 1
if verbose:
print(start)
while new != old:
# Check if max iterations reached
if counter > max_iterations:
print("Maximum iterations reached on fixed_point")
return new
old = new
new = apply_rules(rules, o... | }
def apply_rules(rules, subject):
for k, v in rules.items():
for substitution in match(subject, Pattern(k)):
subject = substitute(Pattern(v), substitution)
return subject
return subject
def fixed_point(start, rules=RULES, max_iterations=10, verbose=False):
| 64 | 64 | 109 | 18 | 45 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | fixed_point | fixed_point | 137 | 154 | 137 | 137 | 64be162e70fdbad3d5e879baf05da07a62e8db0d | bigcode/the-stack | train |
6b49ff4283bb670d752e0c50 | train | function | def numerical_np_scale_estimate(expr):
"""Returns log10 of estimate of Λ in TeV."""
vev = 174
mv = 5e-11
loop = 1.0 / (16 * math.pi ** 2)
subs_list = [
(sympy.Symbol("v"), vev),
(sympy.Symbol("loop"), loop),
(sympy.Symbol("loopv2"), (loop + vev ** 2 / sympy.Symbol("Λ") ** 2),... | def numerical_np_scale_estimate(expr):
| """Returns log10 of estimate of Λ in TeV."""
vev = 174
mv = 5e-11
loop = 1.0 / (16 * math.pi ** 2)
subs_list = [
(sympy.Symbol("v"), vev),
(sympy.Symbol("loop"), loop),
(sympy.Symbol("loopv2"), (loop + vev ** 2 / sympy.Symbol("Λ") ** 2),),
(sympy.Symbol("g2"), 0.6295 ... | if lst else 1
prod *= sympy.Symbol("v") * sympy.Symbol("v") / sympy.Symbol("Λ")
for _ in range(n_loopv2):
prod *= sympy.Symbol("loopv2")
out.append(prod)
return out
def numerical_np_scale_estimate(expr):
| 67 | 67 | 224 | 8 | 58 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | numerical_np_scale_estimate | numerical_np_scale_estimate | 296 | 313 | 296 | 296 | 343324a813effc81ef8e0a0d196d36a74f6fe7fc | bigcode/the-stack | train |
8c6d8c92a703413882aab949 | train | function | def clean(op):
lst = list(op)
out = []
while lst:
item = lst.pop(0)
if item.head.name == "Const":
s = str(item.operands[0])
out.append(s)
else:
# raise Exception(f"Non Const symbol {item} encountered in reduced operator.")
return op
... | def clean(op):
| lst = list(op)
out = []
while lst:
item = lst.pop(0)
if item.head.name == "Const":
s = str(item.operands[0])
out.append(s)
else:
# raise Exception(f"Non Const symbol {item} encountered in reduced operator.")
return op
return out
| Check if max iterations reached
if counter > max_iterations:
print("Maximum iterations reached on fixed_point")
return new
old = new
new = apply_rules(rules, old)
if verbose:
print(new)
counter += 1
return new
def clean(op):
| 64 | 64 | 78 | 4 | 59 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | clean | clean | 157 | 169 | 157 | 157 | 90e6dc2e2e41abdbf7a1564e9ad0a073ec338b3a | bigcode/the-stack | train |
6f4d89924db3cb9bd689b6f1 | train | function | def numerical_mv(expr):
"""Returns estimate of neutrino-mass scale in GeV assuming a NP scale of 1
TeV.
"""
vev = 174
mv = 5e-11
loop = 1.0 / (16 * math.pi ** 2)
subs_list = [
(sympy.Symbol("v"), vev),
(sympy.Symbol("loop"), loop),
(sympy.Symbol("loopv2"), (loop + ve... | def numerical_mv(expr):
| """Returns estimate of neutrino-mass scale in GeV assuming a NP scale of 1
TeV.
"""
vev = 174
mv = 5e-11
loop = 1.0 / (16 * math.pi ** 2)
subs_list = [
(sympy.Symbol("v"), vev),
(sympy.Symbol("loop"), loop),
(sympy.Symbol("loopv2"), (loop + vev ** 2 / sympy.Symbol("Λ... | ("ye"), 1.78 / vev),
]
m = expr.subs(subs_list)
sol = sympy.solve(m - mv, sympy.Symbol("Λ"))[0]
scale = abs(sol) * 1e-3
return scale
def numerical_mv(expr):
| 64 | 64 | 210 | 5 | 58 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | numerical_mv | numerical_mv | 316 | 334 | 316 | 316 | ad6831d8e4e56c2b75a952b3f11f1210e71b8a66 | bigcode/the-stack | train |
a6d5d844d0bf5c19129a07f3 | train | function | def neutrino_mass_estimate(eff_op: Union[EffectiveOperator, List[Op]], verbose=False):
if isinstance(eff_op, EffectiveOperator):
clean_lst = [clean(fixed_point(op)) for op in parse_operator(eff_op)]
else:
clean_lst = [clean(fixed_point(op)) for op in eff_op]
out = []
for lst in clean_ls... | def neutrino_mass_estimate(eff_op: Union[EffectiveOperator, List[Op]], verbose=False):
| if isinstance(eff_op, EffectiveOperator):
clean_lst = [clean(fixed_point(op)) for op in parse_operator(eff_op)]
else:
clean_lst = [clean(fixed_point(op)) for op in eff_op]
out = []
for lst in clean_lst:
if not isinstance(lst, list):
if verbose:
print(... | []
for elem in res:
new_elem = elem.replace("*eps[0][1]", "").replace("*eps[1][0]", "")
if not "eps" in new_elem:
out.append(new_elem)
return [eval(f'Op({elem.replace("*", ",")})') for elem in out]
def neutrino_mass_estimate(eff_op: Union[EffectiveOperator, List[Op]], verbose=False... | 89 | 89 | 297 | 22 | 67 | johngarg/neutrinomass | neutrinomass/database/closures.py | Python | neutrino_mass_estimate | neutrino_mass_estimate | 262 | 293 | 262 | 262 | 9edf02079b7f65434c6c58cfaaeeb48bb2521f5e | bigcode/the-stack | train |
6f3a8479353a1fd9bf08c478 | train | class | class GridSearchResult:
def __init__(
self,
results: List[Result],
lower_limits_lists: LimitLists,
grid_priors: List[Prior]
):
"""
The result of a grid search.
Parameters
----------
results
The results of the n... | class GridSearchResult:
| def __init__(
self,
results: List[Result],
lower_limits_lists: LimitLists,
grid_priors: List[Prior]
):
"""
The result of a grid search.
Parameters
----------
results
The results of the non linear optimizations p... | from typing import List
import numpy as np
from autofit import exc
from autofit.mapper import model_mapper as mm
from autofit.mapper.prior.prior import Prior
from autofit.non_linear.result import Result
LimitLists = List[List[float]]
class GridSearchResult:
| 59 | 256 | 1,495 | 5 | 54 | vishalbelsare/PyAutoFit | autofit/non_linear/grid/grid_search/result.py | Python | GridSearchResult | GridSearchResult | 13 | 240 | 13 | 14 | f67af36de1bee0e3b4195990aef37dd7b9b0d44d | bigcode/the-stack | train |
be847e2e846e0843a40f5327 | train | class | class TransformerClassifierAgent(TorchClassifierAgent):
"""
Classifier based on Transformer.
"""
@staticmethod
def add_cmdline_args(parser):
TransformerRankerAgent.add_cmdline_args(parser) # add transformer args
TorchClassifierAgent.add_cmdline_args(parser)
parser.add_argum... | class TransformerClassifierAgent(TorchClassifierAgent):
| """
Classifier based on Transformer.
"""
@staticmethod
def add_cmdline_args(parser):
TransformerRankerAgent.add_cmdline_args(parser) # add transformer args
TorchClassifierAgent.add_cmdline_args(parser)
parser.add_argument(
'--load-from-pretrained-ranker',
... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.agents.transformer.transformer import (
TransformerRankerAgent,
TransformerMemNetModel,
)
from parlai... | 105 | 124 | 415 | 9 | 95 | takatoy/ParlAI | parlai/agents/transformer_classifier/transformer_classifier.py | Python | TransformerClassifierAgent | TransformerClassifierAgent | 14 | 72 | 14 | 14 | c751c29564e89319a111d58e810e6f7fab621d7a | bigcode/the-stack | train |
b317499665b762af7dd4854c | train | class | class MirroringCompleteMessage(BaseMessage):
def __init__(self, id=None, cloud_uname=None, cname=None):
super(MirroringCompleteMessage, self).__init__()
self.type = MIRRORING_COMPLETE
self.id = id
self.cloud_uname = cloud_uname
self.cname = cname
@staticmethod
def de... | class MirroringCompleteMessage(BaseMessage):
| def __init__(self, id=None, cloud_uname=None, cname=None):
super(MirroringCompleteMessage, self).__init__()
self.type = MIRRORING_COMPLETE
self.id = id
self.cloud_uname = cloud_uname
self.cname = cname
@staticmethod
def deserialize(json_dict):
msg = Mirroring... | # last generated 2016-12-30 20:36:48.051000
from messages import BaseMessage
from msg_codes import MIRRORING_COMPLETE as MIRRORING_COMPLETE
__author__ = 'Mike'
class MirroringCompleteMessage(BaseMessage):
| 55 | 64 | 125 | 8 | 47 | zadjii/nebula | messages/MirroringCompleteMessage.py | Python | MirroringCompleteMessage | MirroringCompleteMessage | 7 | 21 | 7 | 7 | b0bd1389175c5d478a65e0d04ff1d31bd75efc5f | bigcode/the-stack | train |
f62c2e11b2b409ba80b6269d | train | function | def test_context_has_app():
app = Flak(__name__)
with app.test_context() as cx:
assert cx.app is app
| def test_context_has_app():
| app = Flak(__name__)
with app.test_context() as cx:
assert cx.app is app
| rv = cx.url_for('index')
assert rv == 'https://localhost/'
def test_url_generation_requires_server_name():
app = Flak(__name__)
with app.new_context() as cx:
with pytest.raises(RuntimeError):
cx.url_for('index')
def test_context_has_app():
| 64 | 64 | 30 | 6 | 58 | avdd/flak | test/test_context.py | Python | test_context_has_app | test_context_has_app | 26 | 29 | 26 | 26 | e7174884678635d1a33e977013d48a536eaa49ff | bigcode/the-stack | train |
1ed9dd69d728f8795c1a5902 | train | function | def test_app_tearing_down_with_previous_exception():
cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.new_context():
pass
asse... | def test_app_tearing_down_with_previous_exception():
| cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.new_context():
pass
assert cleanup_stuff == [None]
| _down():
cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
pass
assert cleanup_stuff == [None]
def test_app_tearing_down_with_previous_exception():
| 64 | 64 | 78 | 10 | 54 | avdd/flak | test/test_context.py | Python | test_app_tearing_down_with_previous_exception | test_app_tearing_down_with_previous_exception | 48 | 63 | 48 | 48 | f954ab07f139e53420401649de2a2aa683bd842c | bigcode/the-stack | train |
b32335dec39b4ed87be92744 | train | function | def test_proper_test_context():
app = flak.Flak(__name__)
app.config.update(SERVER_NAME='localhost.localdomain:5000')
@app.route('/')
def index(cx):
return None
@app.route('/', subdomain='foo')
def sub(cx):
return None
with app.test_context() as cx:
assert cx.url_f... | def test_proper_test_context():
| app = flak.Flak(__name__)
app.config.update(SERVER_NAME='localhost.localdomain:5000')
@app.route('/')
def index(cx):
return None
@app.route('/', subdomain='foo')
def sub(cx):
return None
with app.test_context() as cx:
assert cx.url_for('index', _external=True) == \... | _teardown_with_handled_exception():
capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
with app.test_context():
assert capture == []
try:
raise Exception('dummy')
except Exception:
... | 82 | 82 | 276 | 7 | 75 | avdd/flak | test/test_context.py | Python | test_proper_test_context | test_proper_test_context | 170 | 206 | 170 | 170 | 7b8382a731bf598a0fc803abeba3fec0a0de465a | bigcode/the-stack | train |
e5446e94d69d59506362071c | train | function | def test_teardown_with_handled_exception():
capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
with app.test_context():
assert capture == []
try:
raise Exception('dummy')
except Exception:
... | def test_teardown_with_handled_exception():
| capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
with app.test_context():
assert capture == []
try:
raise Exception('dummy')
except Exception:
pass
assert capture == [None]
| __)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.test_context():
assert capture == []
assert capture == [None]
def test_teardown_with_handled_exception():
| 64 | 64 | 77 | 9 | 55 | avdd/flak | test/test_context.py | Python | test_teardown_with_handled_exception | test_teardown_with_handled_exception | 154 | 167 | 154 | 154 | 449ee7b068ec445e2cb4626bc03026e804502339 | bigcode/the-stack | train |
59bb9f5f84782fcb2a2b25dc | train | function | def test_context_refcounts():
called = []
app = Flak(__name__)
@app.teardown
def teardown_app(cx, error=None):
called.append('teardown app')
@app.teardown
def teardown_req(cx, error=None):
called.append('teardown request')
@app.route('/')
def index(cx):
env = cx.r... | def test_context_refcounts():
| called = []
app = Flak(__name__)
@app.teardown
def teardown_app(cx, error=None):
called.append('teardown app')
@app.teardown
def teardown_req(cx, error=None):
called.append('teardown request')
@app.route('/')
def index(cx):
env = cx.request.environ
assert ... | ') == 'the cake is a lie'
with pytest.raises(KeyError):
cx.globals.pop('bar')
assert cx.globals.pop('bar', 'more cake') == 'more cake'
# __iter__
assert list(cx.globals) == ['foo']
def test_context_refcounts():
| 64 | 64 | 140 | 6 | 58 | avdd/flak | test/test_context.py | Python | test_context_refcounts | test_context_refcounts | 102 | 120 | 102 | 102 | b6184f66925a7c2b8a559885d3b0027c2d7eb573 | bigcode/the-stack | train |
924157838d6a298609832a5f | train | function | def test_context_binding():
app = flak.Flak(__name__)
@app.route('/')
def index(cx):
return 'Hello %s!' % cx.request.args['name']
@app.route('/meh')
def meh(cx):
return cx.request.url
with app.test_context('/?name=World') as cx:
assert index(cx) == 'Hello World!'
wit... | def test_context_binding():
| app = flak.Flak(__name__)
@app.route('/')
def index(cx):
return 'Hello %s!' % cx.request.args['name']
@app.route('/meh')
def meh(cx):
return cx.request.url
with app.test_context('/?name=World') as cx:
assert index(cx) == 'Hello World!'
with app.test_context('/meh') a... | ERVER_NAME='localhost')
with app.test_context(environ_overrides={'SERVER_NAME': 'localhost'}):
pass
app.config.update(SERVER_NAME='localhost:80')
with app.test_context(environ_overrides={'SERVER_NAME': 'localhost:80'}):
pass
def test_context_binding():
| 64 | 64 | 105 | 5 | 58 | avdd/flak | test/test_context.py | Python | test_context_binding | test_context_binding | 209 | 221 | 209 | 209 | 6ec681e39225c7924ccdfbb966b62718aa3ca1e6 | bigcode/the-stack | train |
f24961b68a9dde28d4cdadc5 | train | function | def test_url_generation_requires_server_name():
app = Flak(__name__)
with app.new_context() as cx:
with pytest.raises(RuntimeError):
cx.url_for('index')
| def test_url_generation_requires_server_name():
| app = Flak(__name__)
with app.new_context() as cx:
with pytest.raises(RuntimeError):
cx.url_for('index')
| '
app.config['PREFERRED_URL_SCHEME'] = 'https'
@app.route('/')
def index(cx):
pass
with app.new_context() as cx:
rv = cx.url_for('index')
assert rv == 'https://localhost/'
def test_url_generation_requires_server_name():
| 63 | 64 | 39 | 8 | 55 | avdd/flak | test/test_context.py | Python | test_url_generation_requires_server_name | test_url_generation_requires_server_name | 20 | 24 | 20 | 20 | 0990fbb3bb773513f56b30ee7255fdbeccf5873a | bigcode/the-stack | train |
dac4de0a708fb0bfee2d0b4f | train | function | def test_new_context():
app = Flak(__name__)
with app.new_context() as cx:
assert cx.app is app
| def test_new_context():
| app = Flak(__name__)
with app.new_context() as cx:
assert cx.app is app
| = Flak(__name__)
with app.new_context() as cx:
with pytest.raises(RuntimeError):
cx.url_for('index')
def test_context_has_app():
app = Flak(__name__)
with app.test_context() as cx:
assert cx.app is app
def test_new_context():
| 64 | 64 | 29 | 5 | 58 | avdd/flak | test/test_context.py | Python | test_new_context | test_new_context | 31 | 34 | 31 | 31 | 20eb7f3ec89a93e530b5a769651916e1d267fd9b | bigcode/the-stack | train |
f10288c5e4d4394e827e4136 | train | function | def test_teardown_on_pop():
capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
cx = app.test_context()
assert capture == []
cx.close()
assert capture == [None]
| def test_teardown_on_pop():
| capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
cx = app.test_context()
assert capture == []
cx.close()
assert capture == [None]
| ['werkzeug.request'] is not None
return u''
c = app.test_client()
res = c.get('/')
assert res.status_code == 200
assert res.data == b''
assert called == ['teardown request', 'teardown app']
def test_teardown_on_pop():
| 63 | 64 | 64 | 7 | 56 | avdd/flak | test/test_context.py | Python | test_teardown_on_pop | test_teardown_on_pop | 124 | 134 | 124 | 124 | 151b64382d410b87ddca87b24fb9ccfec4a38126 | bigcode/the-stack | train |
48fcba807bc94f0b56d7cfed | train | function | def test_app_tearing_down_with_handled_exception():
cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
try:
raise Exception('dummy')
except Exception:
pass
ass... | def test_app_tearing_down_with_handled_exception():
| cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
try:
raise Exception('dummy')
except Exception:
pass
assert cleanup_stuff == [None]
| @app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.new_context():
pass
assert cleanup_stuff == [None]
def test_app_tearing_down_with_handled_exception():
| 64 | 64 | 76 | 11 | 53 | avdd/flak | test/test_context.py | Python | test_app_tearing_down_with_handled_exception | test_app_tearing_down_with_handled_exception | 65 | 78 | 65 | 65 | 3a65125d2dd78badbea4c42c833a6f1cf73af895 | bigcode/the-stack | train |
f90dd03ef0a1bb0d49154b82 | train | function | def test_basic_url_generation():
app = Flak(__name__)
app.config['SERVER_NAME'] = 'localhost'
app.config['PREFERRED_URL_SCHEME'] = 'https'
@app.route('/')
def index(cx):
pass
with app.new_context() as cx:
rv = cx.url_for('index')
assert rv == 'https://localhost/'
| def test_basic_url_generation():
| app = Flak(__name__)
app.config['SERVER_NAME'] = 'localhost'
app.config['PREFERRED_URL_SCHEME'] = 'https'
@app.route('/')
def index(cx):
pass
with app.new_context() as cx:
rv = cx.url_for('index')
assert rv == 'https://localhost/'
| # -*- coding: utf-8 -*-
import pytest
import flak
from flak import Flak
def test_basic_url_generation():
| 28 | 64 | 79 | 6 | 21 | avdd/flak | test/test_context.py | Python | test_basic_url_generation | test_basic_url_generation | 7 | 18 | 7 | 7 | ecafb289514b264f2f424a81fc74fcc128a08092 | bigcode/the-stack | train |
dda8b9faefe5f6cd417d32d9 | train | function | def test_teardown_with_previous_exception():
capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.test_context():
assert capture == []
... | def test_teardown_with_previous_exception():
| capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
try:
raise Exception('dummy')
except Exception:
pass
with app.test_context():
assert capture == []
assert capture == [None]
| capture = []
app = flak.Flak(__name__)
@app.teardown
def end_of_request(cx, exception):
capture.append(exception)
cx = app.test_context()
assert capture == []
cx.close()
assert capture == [None]
def test_teardown_with_previous_exception():
| 64 | 64 | 76 | 8 | 56 | avdd/flak | test/test_context.py | Python | test_teardown_with_previous_exception | test_teardown_with_previous_exception | 137 | 151 | 137 | 137 | 66f0893a0945793620c83ac1fa9d5d655f82ee5d | bigcode/the-stack | train |
99f5d7a4cb13288b192a8617 | train | function | def test_manual_context_binding():
app = flak.Flak(__name__)
@app.route('/')
def index(cx):
return 'Hello %s!' % cx.request.args['name']
cx = app.test_context('/?name=World')
assert index(cx) == 'Hello World!'
cx.close()
| def test_manual_context_binding():
| app = flak.Flak(__name__)
@app.route('/')
def index(cx):
return 'Hello %s!' % cx.request.args['name']
cx = app.test_context('/?name=World')
assert index(cx) == 'Hello World!'
cx.close()
| def meh(cx):
return cx.request.url
with app.test_context('/?name=World') as cx:
assert index(cx) == 'Hello World!'
with app.test_context('/meh') as cx:
assert meh(cx) == 'http://localhost/meh'
def test_manual_context_binding():
| 64 | 64 | 66 | 6 | 58 | avdd/flak | test/test_context.py | Python | test_manual_context_binding | test_manual_context_binding | 224 | 232 | 224 | 224 | c41c765dd8c6022ef3d9d25bf689fb0907a0d91b | bigcode/the-stack | train |
42486f741699d4c4ad014820 | train | function | def test_app_tearing_down():
cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
pass
assert cleanup_stuff == [None]
| def test_app_tearing_down():
| cleanup_stuff = []
app = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
pass
assert cleanup_stuff == [None]
| _context_has_app():
app = Flak(__name__)
with app.test_context() as cx:
assert cx.app is app
def test_new_context():
app = Flak(__name__)
with app.new_context() as cx:
assert cx.app is app
def test_app_tearing_down():
| 64 | 64 | 59 | 7 | 56 | avdd/flak | test/test_context.py | Python | test_app_tearing_down | test_app_tearing_down | 36 | 46 | 36 | 36 | 1315c5dc761f0edab210fa3cca800d76347a6630 | bigcode/the-stack | train |
ce993fd80f616728fdf33528 | train | function | def test_app_context_globals_methods():
app = Flak(__name__)
with app.new_context() as cx:
# get
assert cx.globals.get('foo') is None
assert cx.globals.get('foo', 'bar') == 'bar'
# __contains__
assert 'foo' not in cx.globals
cx.globals.foo = 'bar'
assert '... | def test_app_context_globals_methods():
| app = Flak(__name__)
with app.new_context() as cx:
# get
assert cx.globals.get('foo') is None
assert cx.globals.get('foo', 'bar') == 'bar'
# __contains__
assert 'foo' not in cx.globals
cx.globals.foo = 'bar'
assert 'foo' in cx.globals
# setdefault
... | = Flak(__name__)
@app.teardown
def cleanup(cx, exception):
cleanup_stuff.append(exception)
with app.new_context():
try:
raise Exception('dummy')
except Exception:
pass
assert cleanup_stuff == [None]
def test_app_context_globals_methods():
| 64 | 64 | 207 | 7 | 57 | avdd/flak | test/test_context.py | Python | test_app_context_globals_methods | test_app_context_globals_methods | 80 | 100 | 80 | 80 | 65084ceccc73a180ff921cc216cf4c5a3878931b | bigcode/the-stack | train |
e8b4d31715c04e8987278ec7 | train | function | def _origin_url(url):
if url.startswith("http"):
url = url.split("//")[1]
return url
| def _origin_url(url):
| if url.startswith("http"):
url = url.split("//")[1]
return url
| creating bokeh Server instances.
"""
from __future__ import absolute_import, division, unicode_literals
import signal
import threading
import uuid
from functools import partial
from bokeh.server.server import Server
from .state import state
#---------------------------------------------------------------------
#... | 64 | 64 | 26 | 6 | 58 | kleavor/panel | panel/io/server.py | Python | _origin_url | _origin_url | 21 | 24 | 21 | 21 | 3b7ebbb1f50303346afc98ddb587aeaeb86ce8c1 | bigcode/the-stack | train |
3888d68ee70542fe087d6f04 | train | function | def get_server(panel, port=0, websocket_origin=None, loop=None,
show=False, start=False, **kwargs):
"""
Returns a Server instance with this panel attached as the root
app.
Arguments
---------
port: int (optional, default=0)
Allows specifying a specific port
websocket_or... | def get_server(panel, port=0, websocket_origin=None, loop=None,
show=False, start=False, **kwargs):
| """
Returns a Server instance with this panel attached as the root
app.
Arguments
---------
port: int (optional, default=0)
Allows specifying a specific port
websocket_origin: str or list(str) (optional)
A list of hosts that can connect to the websocket.
This is typically... | import Server
from .state import state
#---------------------------------------------------------------------
# Private API
#---------------------------------------------------------------------
def _origin_url(url):
if url.startswith("http"):
url = url.split("//")[1]
return url
def _server_url(u... | 146 | 146 | 489 | 26 | 120 | kleavor/panel | panel/io/server.py | Python | get_server | get_server | 37 | 107 | 37 | 38 | b287195623cd5faa3f2944d43bbfd691a575f327 | bigcode/the-stack | train |
be0639e75fab4355bf227261 | train | class | class StoppableThread(threading.Thread):
"""Thread class with a stop() method."""
def __init__(self, io_loop=None, timeout=1000, **kwargs):
from tornado import ioloop
super(StoppableThread, self).__init__(**kwargs)
self._stop_event = threading.Event()
self.io_loop = io_loop
... | class StoppableThread(threading.Thread):
| """Thread class with a stop() method."""
def __init__(self, io_loop=None, timeout=1000, **kwargs):
from tornado import ioloop
super(StoppableThread, self).__init__(**kwargs)
self._stop_event = threading.Event()
self.io_loop = io_loop
self._cb = ioloop.PeriodicCallback(se... | server.io_loop.add_callback_from_signal(do_stop)
def do_stop(*args, **kwargs):
server.io_loop.stop()
try:
signal.signal(signal.SIGINT, sig_exit)
except ValueError:
pass # Can't use signal on a thread
if start:
server.start()
try:
server.io_l... | 93 | 93 | 310 | 8 | 84 | kleavor/panel | panel/io/server.py | Python | StoppableThread | StoppableThread | 110 | 149 | 110 | 110 | b138d308475b02dd1210e7eb45ffe36cf272421f | bigcode/the-stack | train |
4d48a3547db813915982eb57 | train | function | def _server_url(url, port):
if url.startswith("http"):
return '%s:%d%s' % (url.rsplit(':', 1)[0], port, "/")
else:
return 'http://%s:%d%s' % (url.split(':')[0], port, "/")
| def _server_url(url, port):
| if url.startswith("http"):
return '%s:%d%s' % (url.rsplit(':', 1)[0], port, "/")
else:
return 'http://%s:%d%s' % (url.split(':')[0], port, "/")
|
from functools import partial
from bokeh.server.server import Server
from .state import state
#---------------------------------------------------------------------
# Private API
#---------------------------------------------------------------------
def _origin_url(url):
if url.startswith("http"):
ur... | 64 | 64 | 65 | 8 | 55 | kleavor/panel | panel/io/server.py | Python | _server_url | _server_url | 27 | 31 | 27 | 27 | 3fc289cf1ed839bb2e182f820ac55ef43b42ff07 | bigcode/the-stack | train |
8a4d0308f4410027e49dbc4f | train | class | class SplineFunctionClass(io.SayClass):
'''
Fit spline [and its inverse] to input function.
'''
def __init__(
self, func, x_limits=[0, 1], number=100, dtype=np.float64, make_inverse=True, **kwargs):
'''
Fit f(x) to spline, and fit x(f) if f is monotonic.
Parameters
... | class SplineFunctionClass(io.SayClass):
| '''
Fit spline [and its inverse] to input function.
'''
def __init__(
self, func, x_limits=[0, 1], number=100, dtype=np.float64, make_inverse=True, **kwargs):
'''
Fit f(x) to spline, and fit x(f) if f is monotonic.
Parameters
----------
func : function f... | array : ratio
'''
return frac / (1 - frac)
def assign_to_dict(self, indices, numer, denom):
'''
Assign fraction to self dictionary.
Parameters
----------
indices : array : index[s] to assign to in self dictionary
numer : int : subset count[s]
... | 163 | 163 | 545 | 10 | 153 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | SplineFunctionClass | SplineFunctionClass | 350 | 408 | 350 | 350 | b4df5c97628976cd0f1a86a63607c8e25d364586 | bigcode/the-stack | train |
dd49c12fcd64b577835e02de | train | class | class SplinePointClass(SplineFunctionClass):
'''
Fit spline [and its inverse] to input points.
'''
def __init__(self, x_values, f_values, dtype=np.float64, make_inverse=True):
'''
Fit f(x) to spline, and fit x(f) if f is monotonic.
Store to self.
Parameters
----... | class SplinePointClass(SplineFunctionClass):
| '''
Fit spline [and its inverse] to input points.
'''
def __init__(self, x_values, f_values, dtype=np.float64, make_inverse=True):
'''
Fit f(x) to spline, and fit x(f) if f is monotonic.
Store to self.
Parameters
----------
x_values : array : x values
... | self.spline_x_from_f, ext=ext).astype(self.dtype)
def derivative_inverse(self, f, ext=2):
return interpolate.splev(f, self.spline_x_from_f, der=1, ext=ext).astype(self.dtype)
class SplinePointClass(SplineFunctionClass):
| 64 | 64 | 191 | 10 | 54 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | SplinePointClass | SplinePointClass | 411 | 434 | 411 | 411 | a7eefb86770c1337f9d0cba1dc51f439c9bf9f61 | bigcode/the-stack | train |
59af5540364ac7e0ed9ec222 | train | function | def percentile_weighted(values, percentiles, weights=None):
'''
Compute weighted percentiles.
If weights are equal, this is the same as normal percentiles.
Elements of the C{data} and C{weights} arrays correspond to each other and must have
equal length (unless C{weights} is C{None}).
Parameter... | def percentile_weighted(values, percentiles, weights=None):
| '''
Compute weighted percentiles.
If weights are equal, this is the same as normal percentiles.
Elements of the C{data} and C{weights} arrays correspond to each other and must have
equal length (unless C{weights} is C{None}).
Parameters
----------
values : array (1-D)
percentiles : ... | values : array
Returns
-------
values : array
'''
if np.isscalar(values):
if values <= 0:
values = -np.Inf
else:
values = np.log10(values)
else:
if not isinstance(values, np.ndarray):
values = np.array(values, np.float32)
else... | 202 | 202 | 674 | 12 | 189 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | percentile_weighted | percentile_weighted | 58 | 126 | 58 | 58 | 8dd74b902745c961a23f1ff320e185b6c81c9ad8 | bigcode/the-stack | train |
a45ce50b69d4b1c18473905b | train | function | def sample_random_reject(func, params, x_limits, y_max, size):
'''
Use rejection method to sample distribution and return as array, assuming minimum of func is 0.
Parameters
----------
func : function
params : list : function's parameters
x_limits : list : min and max limits for function's ... | def sample_random_reject(func, params, x_limits, y_max, size):
| '''
Use rejection method to sample distribution and return as array, assuming minimum of func is 0.
Parameters
----------
func : function
params : list : function's parameters
x_limits : list : min and max limits for function's x-range
y_max : list : min and max limits for function's y-... | ] * f1 + values_sorted[ii] * f2)
if len(values_at_percents) == 1:
values_at_percents = values_at_percents[0]
return values_at_percents
def sample_random_reject(func, params, x_limits, y_max, size):
| 66 | 66 | 222 | 17 | 48 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | sample_random_reject | sample_random_reject | 129 | 154 | 129 | 129 | 08e77d8cf15ee3ef9f48f771312be6f14fde9edb | bigcode/the-stack | train |
c496093270468018ce4dacd9 | train | function | def convert_luminosity(kind, luminosities):
'''
Convert luminosity to magnitude, or vice-versa.
Parameters
----------
kind : str : luminosity kind: 'luminosity', 'mag.r'
luminosities : array : value[s] (if luminosity, in Solar luminosity)
Returns
-------
values : array : luminosity... | def convert_luminosity(kind, luminosities):
| '''
Convert luminosity to magnitude, or vice-versa.
Parameters
----------
kind : str : luminosity kind: 'luminosity', 'mag.r'
luminosities : array : value[s] (if luminosity, in Solar luminosity)
Returns
-------
values : array : luminosity[s] or magnitude[s]
'''
assert kind ... | y_it = y_it * ndimage.filters.gaussian_filter1d(ratio, scatter / x_width)
# this is part of lucy's routine, but seems less stable
#y_it = y_it * ratio
return y_it
def convert_luminosity(kind, luminosities):
| 64 | 64 | 185 | 11 | 52 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | convert_luminosity | convert_luminosity | 182 | 204 | 182 | 182 | e4c957143e67b83eabeb7eeda8fdfc0c272a4422 | bigcode/the-stack | train |
a707128fc05289f135305567 | train | class | class FractionClass(dict, io.SayClass):
'''
Compute fraction safely, convert from fraction to ratio, store fractions in self dictionary.
'''
def __init__(self, array_shape=None, error_kind=''):
'''
Initialize dictionary to store fraction values and uncertainties.
Parameters
... | class FractionClass(dict, io.SayClass):
| '''
Compute fraction safely, convert from fraction to ratio, store fractions in self dictionary.
'''
def __init__(self, array_shape=None, error_kind=''):
'''
Initialize dictionary to store fraction values and uncertainties.
Parameters
----------
array_shape : in... | y_it = y_it * ndimage.filters.gaussian_filter1d(ratio, scatter / x_width)
# this is part of lucy's routine, but seems less stable
#y_it = y_it * ratio
return y_it
def convert_luminosity(kind, luminosities):
'''
Convert luminosity to magnitude, or vice-versa.
Parameters
---------... | 256 | 256 | 1,024 | 10 | 246 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | FractionClass | FractionClass | 210 | 341 | 210 | 210 | 5596d4f64fbb470d65781374a88a2a3c29c66f5b | bigcode/the-stack | train |
c3f70ed82dc02ca774b8fbed | train | function | def get_chisq_reduced(values_test, values_ref, values_ref_err, param_number=1):
'''
Get reduced chi ^ 2, excising reference values with 0 uncertainty.
Parameters
----------
values_test : array : value[s] to test
values_ref : array : reference value[s]
values_ref_err : array : reference unce... | def get_chisq_reduced(values_test, values_ref, values_ref_err, param_number=1):
| '''
Get reduced chi ^ 2, excising reference values with 0 uncertainty.
Parameters
----------
values_test : array : value[s] to test
values_ref : array : reference value[s]
values_ref_err : array : reference uncertainties (can be asymmetric)
param_number : int : number of free parameters... | 20):
'''
Get cumulative number density above m.
Parameters
----------
m : float : (stellar) mass
params : list : parameters (0 = amplitude, 1 = m_char, 2 = slope)
m_max : float : maximum mass for integration
'''
return integrate.quad(self.m_functi... | 121 | 121 | 406 | 22 | 99 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | get_chisq_reduced | get_chisq_reduced | 526 | 568 | 526 | 526 | 812f6de9b81af3864c68b3c1b442cbb6a3e65ecd | bigcode/the-stack | train |
504a13fb76fd7ca798287169 | train | class | class FunctionClass:
'''
Collection of functions, for fitting.
'''
def get_ave(self, func, params, x_limits=[0, 1]):
def integrand_func_ave(x, func, params):
return x * func(x, params)
return integrate.quad(integrand_func_ave, x_limits[0], x_limits[1], (func, params))[0]
... | class FunctionClass:
| '''
Collection of functions, for fitting.
'''
def get_ave(self, func, params, x_limits=[0, 1]):
def integrand_func_ave(x, func, params):
return x * func(x, params)
return integrate.quad(integrand_func_ave, x_limits[0], x_limits[1], (func, params))[0]
def gaussian(self... | ).astype(self.dtype)
def derivative_inverse(self, f, ext=2):
return interpolate.splev(f, self.spline_x_from_f, der=1, ext=ext).astype(self.dtype)
class SplinePointClass(SplineFunctionClass):
'''
Fit spline [and its inverse] to input points.
'''
def __init__(self, x_values, f_values, dtyp... | 249 | 249 | 830 | 4 | 245 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | FunctionClass | FunctionClass | 440 | 517 | 440 | 440 | 48047d4370c76e1ba37783982415757e0ec6965b | bigcode/the-stack | train |
54d506af6d7c8ccc98750019 | train | function | def get_log(values):
'''
Safely get log of values.
Values = 0 is ok, but print warning if values < 0.
Parameters
----------
values : array
Returns
-------
values : array
'''
if np.isscalar(values):
if values <= 0:
values = -np.Inf
else:
... | def get_log(values):
| '''
Safely get log of values.
Values = 0 is ok, but print warning if values < 0.
Parameters
----------
values : array
Returns
-------
values : array
'''
if np.isscalar(values):
if values <= 0:
values = -np.Inf
else:
values = np.log10(... | @gmail.com>
'''
# system ----
from __future__ import absolute_import, division, print_function
import numpy as np
from scipy import integrate, interpolate, ndimage, special, stats
# local ----
from . import array, constant, io
#=========================================================================================... | 68 | 68 | 228 | 5 | 63 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | get_log | get_log | 18 | 55 | 18 | 18 | 41891742685b80fbf60efdb3944194ab248eb6ca | bigcode/the-stack | train |
cacd2e4fa34d16662cebb3f2 | train | function | def deconvolve(ys_conv, scatter, x_width, iter_number=10):
'''
Get Gaussian-deconvolved values via Lucy routine.
Parameters
----------
ys_conv : array : y-values that already are convolved with gaussian
scatter : float : gaussian scatter
x_width : float : bin width
iter_number : int : n... | def deconvolve(ys_conv, scatter, x_width, iter_number=10):
| '''
Get Gaussian-deconvolved values via Lucy routine.
Parameters
----------
ys_conv : array : y-values that already are convolved with gaussian
scatter : float : gaussian scatter
x_width : float : bin width
iter_number : int : number of iterations to do
Returns
-------
y_it... | xs_rand.size
if x_number < size:
xs_rand = np.append(
xs_rand, sample_random_reject(func, params, x_limits, y_max, size - x_number))
return xs_rand
def deconvolve(ys_conv, scatter, x_width, iter_number=10):
| 64 | 64 | 190 | 18 | 45 | astrofyz/PH482_582 | students_final_projects/group-f/utilities/basic/math.py | Python | deconvolve | deconvolve | 157 | 179 | 157 | 157 | 84294119f314a08f599b9d9205a9911feefeecfa | bigcode/the-stack | train |
449733fb296163be9bdb41c7 | train | function | def test_preprocess():
def preprocess(x):
x[:] = 1
return x[:, :, 0]
with random_images(4, (2, 3, 4)) as globstring:
im = da_imread(globstring, preprocess=preprocess)
assert (im.compute() == np.ones((4, 2, 3), dtype='u1')).all()
| def test_preprocess():
| def preprocess(x):
x[:] = 1
return x[:, :, 0]
with random_images(4, (2, 3, 4)) as globstring:
im = da_imread(globstring, preprocess=preprocess)
assert (im.compute() == np.ones((4, 2, 3), dtype='u1')).all()
| , (5, 6, 3)) as globstring:
im = da_imread(globstring, imread=imread2)
assert (im.compute() == np.ones((4, 2, 3, 4), dtype='u1')).all()
def test_preprocess():
| 64 | 64 | 85 | 5 | 59 | ihnorton/dask | dask/array/tests/test_image.py | Python | test_preprocess | test_preprocess | 43 | 49 | 43 | 43 | da74ee549f468b5c1835af8ac289381b38d8a8a9 | bigcode/the-stack | train |
17a8d7f88862188992535c41 | train | function | def test_imread():
with random_images(4, (5, 6, 3)) as globstring:
im = da_imread(globstring)
assert im.shape == (4, 5, 6, 3)
assert im.chunks == ((1, 1, 1, 1), (5,), (6,), (3,))
assert im.dtype == 'uint8'
assert im.compute().shape == (4, 5, 6, 3)
assert im.compute()... | def test_imread():
| with random_images(4, (5, 6, 3)) as globstring:
im = da_imread(globstring)
assert im.shape == (4, 5, 6, 3)
assert im.chunks == ((1, 1, 1, 1), (5,), (6,), (3,))
assert im.dtype == 'uint8'
assert im.compute().shape == (4, 5, 6, 3)
assert im.compute().dtype == 'uint8'
| in range(n):
fn = os.path.join(dirname, 'image.%d.png' % i)
x = np.random.randint(0, 255, size=shape).astype('u1')
imsave(fn, x)
yield os.path.join(dirname, '*.png')
def test_imread():
| 64 | 64 | 118 | 5 | 59 | ihnorton/dask | dask/array/tests/test_image.py | Python | test_imread | test_imread | 24 | 32 | 24 | 24 | c624b17ee2c766949a075c1b2a56dae70c9b9fb9 | bigcode/the-stack | train |
837c212a6692c76da15c387c | train | function | def test_imread_with_custom_function():
def imread2(fn):
return np.ones((2, 3, 4), dtype='i1')
with random_images(4, (5, 6, 3)) as globstring:
im = da_imread(globstring, imread=imread2)
assert (im.compute() == np.ones((4, 2, 3, 4), dtype='u1')).all()
| def test_imread_with_custom_function():
| def imread2(fn):
return np.ones((2, 3, 4), dtype='i1')
with random_images(4, (5, 6, 3)) as globstring:
im = da_imread(globstring, imread=imread2)
assert (im.compute() == np.ones((4, 2, 3, 4), dtype='u1')).all()
| 1, 1, 1), (5,), (6,), (3,))
assert im.dtype == 'uint8'
assert im.compute().shape == (4, 5, 6, 3)
assert im.compute().dtype == 'uint8'
def test_imread_with_custom_function():
| 64 | 64 | 98 | 8 | 56 | ihnorton/dask | dask/array/tests/test_image.py | Python | test_imread_with_custom_function | test_imread_with_custom_function | 35 | 40 | 35 | 35 | 17c5f2f3f7a85104151e3bef532403b2c04c2520 | bigcode/the-stack | train |
5fa2e87c27a9ecb663d9e68d | train | function | @contextmanager
def random_images(n, shape):
with tmpdir() as dirname:
for i in range(n):
fn = os.path.join(dirname, 'image.%d.png' % i)
x = np.random.randint(0, 255, size=shape).astype('u1')
imsave(fn, x)
yield os.path.join(dirname, '*.png')
| @contextmanager
def random_images(n, shape):
| with tmpdir() as dirname:
for i in range(n):
fn = os.path.join(dirname, 'image.%d.png' % i)
x = np.random.randint(0, 255, size=shape).astype('u1')
imsave(fn, x)
yield os.path.join(dirname, '*.png')
| lib import contextmanager
import os
import pytest
pytest.importorskip('skimage')
from dask.array.image import imread as da_imread
import numpy as np
from skimage.io import imsave
from dask.utils import tmpdir
@contextmanager
def random_images(n, shape):
| 64 | 64 | 81 | 11 | 52 | ihnorton/dask | dask/array/tests/test_image.py | Python | random_images | random_images | 13 | 21 | 13 | 14 | 0652cb7c213b26e319a2c236f0f035767b6992ca | bigcode/the-stack | train |
1c586738ac0f2afbb3a707b9 | train | class | class Migration(migrations.Migration):
dependencies = [
('tickets_handler', '0031_employer_supervisor_password'),
('territory', '0007_auto_20200617_1404'),
]
operations = [
migrations.AddField(
model_name='promouter',
name='bank_detail',
field=mo... | class Migration(migrations.Migration):
| dependencies = [
('tickets_handler', '0031_employer_supervisor_password'),
('territory', '0007_auto_20200617_1404'),
]
operations = [
migrations.AddField(
model_name='promouter',
name='bank_detail',
field=models.IntegerField(default=0),
... | # Generated by Django 2.2.1 on 2020-06-17 19:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 134 | 7 | 37 | ChanTerelLy/partnerweb3 | territory/migrations/0008_auto_20200617_2200.py | Python | Migration | Migration | 7 | 27 | 7 | 8 | 97d12e125050ebd88f2441016a1a0ff555f6fb8f | bigcode/the-stack | train |
1f2116c0ed6e509ca79b6169 | train | class | class VarnishCache(object):
def __init__(self, config):
self.configurations = config
self.connection = None
def metric_collector(self):
data = {
'plugin_version': PLUGIN_VERSION, 'heartbeat_required': HEARTBEAT
}
varnish_command = ['varnishstat', '-1', ... | class VarnishCache(object):
| def __init__(self, config):
self.configurations = config
self.connection = None
def metric_collector(self):
data = {
'plugin_version': PLUGIN_VERSION, 'heartbeat_required': HEARTBEAT
}
varnish_command = ['varnishstat', '-1', '-j']
if VARNISH_IN... | new metrics are added, make an entry here for its unit if needed.
METRICS_UNITS_V3 = {'cache_hit': 'units', 'cache_miss': 'units', 'n_wrk_create': 'units', 'n_wrk_lqueue': 'units',
'sess_pipe_overflow': 'units'}
METRICS_UNITS_V4 = {'cache_hit': 'units', 'cache_miss': 'units', 'threads_created': 'unit... | 122 | 122 | 409 | 7 | 115 | Sriram21/plugins | varnish_cache/varnish_cache.py | Python | VarnishCache | VarnishCache | 29 | 66 | 29 | 29 | d5cf952e8ed4ec92ada7d94e5abbe3c0d1b9b150 | bigcode/the-stack | train |
8287a615c50989f62b03b067 | train | class | class NcpSupportMixin():
""" The mixin to check whether a test case supports NCP.
"""
SUPPORT_NCP = True
def __init__(self, *args, **kwargs):
if os.getenv('NODE_TYPE', 'sim') == 'ncp-sim' and not self.SUPPORT_NCP:
# 77 means skip this test case in automake tests
sys.exi... | class NcpSupportMixin():
| """ The mixin to check whether a test case supports NCP.
"""
SUPPORT_NCP = True
def __init__(self, *args, **kwargs):
if os.getenv('NODE_TYPE', 'sim') == 'ncp-sim' and not self.SUPPORT_NCP:
# 77 means skip this test case in automake tests
sys.exit(77)
super().__... | ': None,
'version': ENV_THREAD_VERSION,
}
"""Default configurations when creating nodes."""
EXTENDED_ADDRESS_BASE = 0x166e0a0000000000
"""Extended address base to keep U/L bit 1. The value is borrowed from Thread Test Harness."""
class NcpSupportMixin():
| 63 | 64 | 99 | 6 | 57 | kkasperczyk-no/sdk-openthread | tests/scripts/thread-cert/thread_cert.py | Python | NcpSupportMixin | NcpSupportMixin | 73 | 84 | 73 | 73 | 3dde76ca596ee80f5c5d1da0e033a011a8c1fe9e | bigcode/the-stack | train |
799422aa6f20af9a69d85ce8 | train | class | class TestCase(NcpSupportMixin, unittest.TestCase):
"""The base class for all thread certification test cases.
The `topology` member of sub-class is used to create test topology.
"""
USE_MESSAGE_FACTORY = True
TOPOLOGY = None
CASE_WIRESHARK_PREFS = None
SUPPORT_THREAD_1_1 = True
def _... | class TestCase(NcpSupportMixin, unittest.TestCase):
| """The base class for all thread certification test cases.
The `topology` member of sub-class is used to create test topology.
"""
USE_MESSAGE_FACTORY = True
TOPOLOGY = None
CASE_WIRESHARK_PREFS = None
SUPPORT_THREAD_1_1 = True
def __init__(self, *args, **kwargs):
super().__in... | Verifier
PORT_OFFSET = int(os.getenv('PORT_OFFSET', "0"))
ENV_THREAD_VERSION = os.getenv('THREAD_VERSION', '1.1')
DEFAULT_PARAMS = {
'is_mtd': False,
'is_bbr': False,
'is_otbr': False,
'is_host': False,
'mode': 'rdn',
'panid': 0xface,
'allowlist': None,
'version': ENV_THREAD_VERSION,
... | 256 | 256 | 3,513 | 12 | 244 | kkasperczyk-no/sdk-openthread | tests/scripts/thread-cert/thread_cert.py | Python | TestCase | TestCase | 87 | 522 | 87 | 87 | e824bd098e2ea3839ba5bc05a6dbda1b949573c3 | bigcode/the-stack | train |
d18885e53eb280173bf9ed1d | train | class | class SimulatedDataset(Dataset):
"""
A simulated dataset
"""
def __init__(
self, localId, referenceSet, randomSeed=0,
numVariantSets=1, numCalls=1, variantDensity=0.5,
numReadGroupSets=1, numReadGroupsPerReadGroupSet=1,
numAlignments=1, numFeatureSets=1, n... | class SimulatedDataset(Dataset):
| """
A simulated dataset
"""
def __init__(
self, localId, referenceSet, randomSeed=0,
numVariantSets=1, numCalls=1, variantDensity=0.5,
numReadGroupSets=1, numReadGroupsPerReadGroupSet=1,
numAlignments=1, numFeatureSets=1, numContinuousSets=1,
n... | return [self._rnaQuantificationSetIdMap[id_] for
id_ in self._rnaQuantificationSetIds]
def getRnaQuantificationSetByIndex(self, index):
"""
Returns the rna quantification set at the specified index in this
dataset.
"""
return self._rnaQuantificationSe... | 256 | 256 | 864 | 7 | 248 | dcolligan/ga4gh-server | ga4gh/server/datamodel/datasets.py | Python | SimulatedDataset | SimulatedDataset | 421 | 507 | 421 | 421 | 9e810ba758a4a8ba0e0b0fbc23b307381b97db95 | bigcode/the-stack | train |
9da1ac6001e084dadd935eb6 | train | class | class Dataset(datamodel.DatamodelObject):
"""
The base class of datasets containing variants and reads
"""
compoundIdClass = datamodel.DatasetCompoundId
def __init__(self, localId):
super(Dataset, self).__init__(None, localId)
self._description = None
self._variantSetIds = [... | class Dataset(datamodel.DatamodelObject):
| """
The base class of datasets containing variants and reads
"""
compoundIdClass = datamodel.DatasetCompoundId
def __init__(self, localId):
super(Dataset, self).__init__(None, localId)
self._description = None
self._variantSetIds = []
self._variantSetIdMap = {}
... | """
Dataset objects
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import ga4gh.server.datamodel as datamodel
import ga4gh.server.datamodel.reads as reads
import ga4gh.server.datamodel.sequence_annotations as sequence_annotations
import ga4gh.server.da... | 171 | 256 | 3,032 | 8 | 162 | dcolligan/ga4gh-server | ga4gh/server/datamodel/datasets.py | Python | Dataset | Dataset | 22 | 418 | 22 | 22 | e350b3ffa0fa319818bf45be1c3b9f551a23d519 | bigcode/the-stack | train |
6eee0d845b04a154aa7dcb6d | train | function | def say_bye_after_operation(req, resp, resource):
logging.info('Bye there at ' + str(time.time()) + ' and api_key=' + req.params.get('api_key'))
| def say_bye_after_operation(req, resp, resource):
| logging.info('Bye there at ' + str(time.time()) + ' and api_key=' + req.params.get('api_key'))
| if key is None:
raise falcon.HTTPForbidden(
description='API KEY is required')
def is_admin(req, resp, resource, params):
# Good place to check the user role
logging.info(req.context['auth_user'])
def say_bye_after_operation(req, resp, resource):
| 63 | 64 | 39 | 12 | 51 | tjwebb/community | tutorials/appengine-python-api-firebase-auth/api/hooks.py | Python | say_bye_after_operation | say_bye_after_operation | 26 | 28 | 26 | 27 | dd60c64b01df84c4ffc3ec15642b2d3b417cf8b3 | bigcode/the-stack | train |
51e935c6c94b0edb4fccc2af | train | function | def is_admin(req, resp, resource, params):
# Good place to check the user role
logging.info(req.context['auth_user'])
| def is_admin(req, resp, resource, params):
# Good place to check the user role
| logging.info(req.context['auth_user'])
|
def api_key(req, resp, resource, params):
key = req.get_param('api_key')
if key is None:
raise falcon.HTTPForbidden(
description='API KEY is required')
def is_admin(req, resp, resource, params):
# Good place to check the user role
| 64 | 64 | 30 | 21 | 43 | tjwebb/community | tutorials/appengine-python-api-firebase-auth/api/hooks.py | Python | is_admin | is_admin | 21 | 23 | 21 | 22 | 9c1cebeeac33a521646c3c32e004da4512b0a86b | bigcode/the-stack | train |
3cbf111ebabe74e15c43742b | train | function | def api_key(req, resp, resource, params):
key = req.get_param('api_key')
if key is None:
raise falcon.HTTPForbidden(
description='API KEY is required')
| def api_key(req, resp, resource, params):
| key = req.get_param('api_key')
if key is None:
raise falcon.HTTPForbidden(
description='API KEY is required')
| """Hooks Submodule"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import time
import falcon
def api_key(req, resp, resource, params):
| 49 | 64 | 42 | 11 | 37 | tjwebb/community | tutorials/appengine-python-api-firebase-auth/api/hooks.py | Python | api_key | api_key | 13 | 18 | 13 | 14 | 4cf51ed62c63ccce0acde59f8b1bec097e32d1c8 | bigcode/the-stack | train |
18c1008e74675501bb33affd | train | function | def post():
""" RESTful CRUD controller """
tablename = "cms_post"
# Filter out those posts which are part of a series
#table = s3db[tablename]
#s3.filter = (table.series_id == None)
# Custom Method to add Comments
s3db.set_method("cms", "post",
method = "discuss",
... | def post():
| """ RESTful CRUD controller """
tablename = "cms_post"
# Filter out those posts which are part of a series
#table = s3db[tablename]
#s3.filter = (table.series_id == None)
# Custom Method to add Comments
s3db.set_method("cms", "post",
method = "discuss",
... | = lambda body: XML(s3_URLise(body))
table.body.widget = None
# Titles do show up
table.name.comment = ""
return True
s3.prep = prep
return s3_rest_controller(rheader=s3db.cms_rheader)
# ---------------------------------------------------------------------------... | 256 | 256 | 1,332 | 3 | 253 | whanderley/eden | controllers/cms.py | Python | post | post | 103 | 255 | 103 | 103 | b5f54d2d155abf5db7b4084701d306d524c8b1a6 | bigcode/the-stack | train |
b84495d52362cd108fbe13a5 | train | function | def index_alt():
"""
Module homepage for non-Admin users when no CMS content found
"""
# Just redirect to the list of Posts
s3_redirect_default(URL(f="post"))
| def index_alt():
| """
Module homepage for non-Admin users when no CMS content found
"""
# Just redirect to the list of Posts
s3_redirect_default(URL(f="post"))
| .controller
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
from datetime import timedelta
# =============================================================================
def index():
""" Module homepage """
return s3db.cms_index(module, alt_function="index_alt")... | 64 | 64 | 42 | 4 | 60 | whanderley/eden | controllers/cms.py | Python | index_alt | index_alt | 23 | 29 | 23 | 23 | 8222d958f6088f6ebbe0c46caa5394b22d888616 | bigcode/the-stack | train |
73f347b740797273d6476030 | train | function | def series():
""" RESTful CRUD controller """
# Pre-process
def prep(r):
if r.component:
# Settings are defined at the series level
table = s3db.cms_post
_avatar = table.avatar
_avatar.readable = _avatar.writable = False
_avatar.default = ... | def series():
| """ RESTful CRUD controller """
# Pre-process
def prep(r):
if r.component:
# Settings are defined at the series level
table = s3db.cms_post
_avatar = table.avatar
_avatar.readable = _avatar.writable = False
_avatar.default = r.record.avata... | from datetime import timedelta
# =============================================================================
def index():
""" Module homepage """
return s3db.cms_index(module, alt_function="index_alt")
# -----------------------------------------------------------------------------
def index_alt():
"""
... | 82 | 82 | 274 | 3 | 79 | whanderley/eden | controllers/cms.py | Python | series | series | 32 | 63 | 32 | 32 | 057c875cda970de30eb1469d40f727caa7f6ffdd | bigcode/the-stack | train |
32882560bffd86c2a3ae47d0 | train | function | def posts():
"""
Function accessed by AJAX to handle a Series of Posts
"""
try:
series_id = request.args[0]
except:
raise HTTP(400)
try:
recent = request.args[1]
except:
recent = 5
table = s3db.cms_post
# List of Posts in this Series
query ... | def posts():
| """
Function accessed by AJAX to handle a Series of Posts
"""
try:
series_id = request.args[0]
except:
raise HTTP(400)
try:
recent = request.args[1]
except:
recent = 5
table = s3db.cms_post
# List of Posts in this Series
query = (table.seri... | imageshow:img_path+'arrow-right.png',defaulthide:false})
$('#cms_comment_parent__row1').hide()
$('#cms_comment_parent__row').hide()
$('#cms_comment_body').ckeditor(ck_config)
$('#submit_record__row input').click(function(){
$('#comment-form').hide()
$('#cms_comment_body').ckeditorGet().destroy()
return true
})'''
... | 151 | 151 | 505 | 3 | 148 | whanderley/eden | controllers/cms.py | Python | posts | posts | 903 | 980 | 903 | 903 | 0b06fba480d0b8ec1fa73b8dc25943949c503cc3 | bigcode/the-stack | train |
b619398a77356ec113a81e41 | train | function | def comment():
""" RESTful CRUD controller """
return s3_rest_controller()
| def comment():
| """ RESTful CRUD controller """
return s3_rest_controller()
| None
response.view = s3base.S3CRUD._view(r, "cms/newsfeed.html")
return output
s3.postp = postp
output = s3_rest_controller("cms", "post")
return output
# =============================================================================
# Comments
# ==================================... | 64 | 64 | 17 | 3 | 60 | whanderley/eden | controllers/cms.py | Python | comment | comment | 730 | 733 | 730 | 730 | 85f8cf1d77f4dee1f8328288b9ce70f5140a460b | bigcode/the-stack | train |
fdc4e958573145f237aa2a0b | train | function | def comment_parse(comment, comments, post_id=None):
"""
Parse a Comment
@param: comment - a gluon.sql.Row: the current comment
@param: comments - a gluon.sql.Rows: full list of comments
@param: post_id - a reference ID: optional post commented on
"""
author = B(T("Anonymous... | def comment_parse(comment, comments, post_id=None):
| """
Parse a Comment
@param: comment - a gluon.sql.Row: the current comment
@param: comments - a gluon.sql.Rows: full list of comments
@param: post_id - a reference ID: optional post commented on
"""
author = B(T("Anonymous"))
if comment.created_by:
utable = s3db... | iley','-','Source','Maximize']],toolbarCanCollapse:false,removePlugins:'elementspath'}
function comment_reply(id){
$('#cms_comment_post_id__row').hide()
$('#cms_comment_post_id__row1').hide()
$('#comment-title').html(i18n.reply)
$('#cms_comment_body').ckeditorGet().destroy()
$('#cms_comment_body').ckeditor(ck_conf... | 166 | 166 | 556 | 11 | 155 | whanderley/eden | controllers/cms.py | Python | comment_parse | comment_parse | 774 | 839 | 774 | 774 | 77b6ef806af6559e59b822b747a4809f3061cd76 | bigcode/the-stack | train |
7a69f611dec9d53e0f5b1d66 | train | function | def tag():
""" RESTful CRUD controller """
return s3_rest_controller()
| def tag():
| """ RESTful CRUD controller """
return s3_rest_controller()
| Titles do show up
table.name.comment = ""
return True
s3.prep = prep
return s3_rest_controller(rheader=s3db.cms_rheader)
# -----------------------------------------------------------------------------
def status():
""" RESTful CRUD controller """
return s3_rest_controller()
# --... | 64 | 64 | 17 | 3 | 61 | whanderley/eden | controllers/cms.py | Python | tag | tag | 72 | 75 | 72 | 72 | 61d51af8407c59a377f872abd0fcacedbb919cef | bigcode/the-stack | train |
4e58c2ff3b4eee41824c4200 | train | function | def blog():
"""
RESTful CRUD controller for display of a series of posts as a full-page
read-only showing last 5 items in reverse time order
@ToDo: Convert to dataList
"""
# Pre-process
def prep(r):
s3db.configure(r.tablename, listadd=False)
return True
s3.p... | def blog():
| """
RESTful CRUD controller for display of a series of posts as a full-page
read-only showing last 5 items in reverse time order
@ToDo: Convert to dataList
"""
# Pre-process
def prep(r):
s3db.configure(r.tablename, listadd=False)
return True
s3.prep = prep
... | = prep
return s3_rest_controller(rheader=s3db.cms_rheader)
# -----------------------------------------------------------------------------
def status():
""" RESTful CRUD controller """
return s3_rest_controller()
# -----------------------------------------------------------------------------
def tag():... | 64 | 64 | 149 | 3 | 61 | whanderley/eden | controllers/cms.py | Python | blog | blog | 78 | 100 | 78 | 78 | a48ffb0e449cfce5ee715ddcd9de673fba3e54b0 | bigcode/the-stack | train |
8b440f52214059b2def24102 | train | function | def status():
""" RESTful CRUD controller """
return s3_rest_controller()
| def status():
| """ RESTful CRUD controller """
return s3_rest_controller()
| = lambda body: XML(s3_URLise(body))
table.body.widget = None
# Titles do show up
table.name.comment = ""
return True
s3.prep = prep
return s3_rest_controller(rheader=s3db.cms_rheader)
# ---------------------------------------------------------------------------... | 64 | 64 | 17 | 3 | 61 | whanderley/eden | controllers/cms.py | Python | status | status | 66 | 69 | 66 | 66 | 0d664d698078ff28b6410e3fb2f1c3d95b68936c | bigcode/the-stack | train |
c5ae572a6a4337c27313f653 | train | function | def page():
"""
RESTful CRUD controller for display of a post as a full-page read-only
- with optional Comments
"""
found = True
get_vars = request.get_vars
if "name" in get_vars:
table = s3db.cms_post
query = (table.name == get_vars.name) & \
(table.... | def page():
| """
RESTful CRUD controller for display of a post as a full-page read-only
- with optional Comments
"""
found = True
get_vars = request.get_vars
if "name" in get_vars:
table = s3db.cms_post
query = (table.name == get_vars.name) & \
(table.deleted != T... | = table.expired.writable = False
_crud = s3.crud_strings[tablename]
_crud.label_create = T("Add Metadata")
_crud.title_update = T("Edit Metadata")
if r.component_name == "module":
modules = {}
_modules ... | 169 | 169 | 565 | 3 | 166 | whanderley/eden | controllers/cms.py | Python | page | page | 258 | 319 | 258 | 258 | beb97e81d3a6342e657c56fc2ef44637ac6f6473 | bigcode/the-stack | train |
2d611ddc05181c60d7df5a3f | train | function | def discuss(r, **attr):
""" Custom Method to manage the discussion of a Post """
id = r.id
# Add the RHeader to maintain consistency with the other pages
rheader = s3db.cms_rheader(r)
ckeditor = URL(c="static", f="ckeditor", args="ckeditor.js")
s3.scripts.append(ckeditor)
adapter = URL(c=... | def discuss(r, **attr):
| """ Custom Method to manage the discussion of a Post """
id = r.id
# Add the RHeader to maintain consistency with the other pages
rheader = s3db.cms_rheader(r)
ckeditor = URL(c="static", f="ckeditor", args="ckeditor.js")
s3.scripts.append(ckeditor)
adapter = URL(c="static", f="ckeditor", ... | .representation != "dl":
# Hide side menu
current.menu.options = None
response.view = s3base.S3CRUD._view(r, "cms/newsfeed.html")
return output
s3.postp = postp
output = s3_rest_controller("cms", "post")
return output
# =============================... | 105 | 105 | 353 | 7 | 98 | whanderley/eden | controllers/cms.py | Python | discuss | discuss | 736 | 771 | 736 | 736 | f07dd4027c70ebe1fea8c6bd93de3dd88aa73547 | bigcode/the-stack | train |
e7cf19de50a65d72d094c75b | train | function | def index():
""" Module homepage """
return s3db.cms_index(module, alt_function="index_alt")
| def index():
| """ Module homepage """
return s3db.cms_index(module, alt_function="index_alt")
| # -*- coding: utf-8 -*-
"""
CMS
Simple Content Management System
"""
module = request.controller
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
from datetime import timedelta
# =============================================================================
def i... | 59 | 64 | 23 | 3 | 55 | whanderley/eden | controllers/cms.py | Python | index | index | 17 | 20 | 17 | 17 | 7a84d33045522080a8a0d8be774280363f4fc7e7 | bigcode/the-stack | train |
615b9bb832f2f130a1a3f663 | train | function | def cms_post_age(row):
"""
The age of the post
- used for colour-coding markers of Alerts & Incidents
"""
if hasattr(row, "cms_post"):
row = row.cms_post
try:
date = row.date
except:
# not available
return messages["NONE"]
now = request.utcnow
... | def cms_post_age(row):
| """
The age of the post
- used for colour-coding markers of Alerts & Incidents
"""
if hasattr(row, "cms_post"):
row = row.cms_post
try:
date = row.date
except:
# not available
return messages["NONE"]
now = request.utcnow
age = now - date
... | ('post_id')
$('#cms_comment_post_id').val(post_id)
}'''))
s3.js_global.append(js)
return output
s3.postp = postp
output = s3_rest_controller("cms", "post")
return output
# -----------------------------------------------------------------------------
def cms_post_age(row):
| 64 | 64 | 119 | 6 | 58 | whanderley/eden | controllers/cms.py | Python | cms_post_age | cms_post_age | 322 | 343 | 322 | 322 | a6f390842afea9ae2e88021fc9cd09f847430ef1 | bigcode/the-stack | train |
77a6c20ac28552ef569cae4b | train | function | def newsfeed():
"""
RESTful CRUD controller for display of posts as a filterable dataList
(use with /datalist method)
"""
# Load Model
table = s3db.cms_post
stable = db.cms_series
# Hide Posts linked to Modules and Maps & Expired Posts
s3.filter = (FS("post_module.module") ... | def newsfeed():
| """
RESTful CRUD controller for display of posts as a filterable dataList
(use with /datalist method)
"""
# Load Model
table = s3db.cms_post
stable = db.cms_series
# Hide Posts linked to Modules and Maps & Expired Posts
s3.filter = (FS("post_module.module") == None) & \
... | hide()
$('#cms_comment_post_id__row1').hide()
$('#comment-title').html(i18n.reply)
$('#cms_comment_body').ckeditorGet().destroy()
$('#cms_comment_body').ckeditor(ck_config)
$('#comment-form').insertAfter($('#comment-'+id))
$('#cms_comment_parent').val(id)
var post_id = $('#comment-'+id).attr('post_id')
$('#cms_... | 256 | 256 | 2,989 | 4 | 252 | whanderley/eden | controllers/cms.py | Python | newsfeed | newsfeed | 346 | 725 | 346 | 346 | b5d85506bbff3ea6a81196efa686157818d978bf | bigcode/the-stack | train |
0f26a96e4fb937e2b87f66dc | train | function | def comments():
"""
Function accessed by AJAX to handle Comments
- for discuss(() & page()
"""
try:
post_id = request.args[0]
except:
raise HTTP(400)
table = s3db.cms_comment
# Form to add a new Comment
from gluon.tools import Crud
crud = Crud()
tab... | def comments():
| """
Function accessed by AJAX to handle Comments
- for discuss(() & page()
"""
try:
post_id = request.args[0]
except:
raise HTTP(400)
table = s3db.cms_comment
# Form to add a new Comment
from gluon.tools import Crud
crud = Crud()
table.post_id.defau... | comment-%i" % comment.id,
_post_id=post_id,
_class="comment-box"))
# Add the children of this thread
children = UL(_class="children")
id = comment.id
count = 0
for comment in comments:
if comment.parent == id:
count = 1
child =... | 114 | 114 | 383 | 3 | 111 | whanderley/eden | controllers/cms.py | Python | comments | comments | 842 | 900 | 842 | 842 | d50fe6000afc5b4db407bd3af2492d90307d2c0d | bigcode/the-stack | train |
3f3447d4a19e793e381fa421 | train | class | class PacketDumper:
options = None
writeFile = None
def onEnable(self, parser, pluginloader):
parser.add_option("-d", "--dump-packets",
action="store_true", dest="dumpPackets", default=False,
help="run with this argument to dump packets")
... | class PacketDumper:
| options = None
writeFile = None
def onEnable(self, parser, pluginloader):
parser.add_option("-d", "--dump-packets",
action="store_true", dest="dumpPackets", default=False,
help="run with this argument to dump packets")
parser.add_option("... | import string
import copy
import base64
class PacketDumper:
| 15 | 81 | 271 | 5 | 9 | eagleapex/pyCraft | plugins/PacketDumper.py | Python | PacketDumper | PacketDumper | 6 | 35 | 6 | 6 | acd73d58ceab01a3ab9a6b7613cd41f1589cc691 | bigcode/the-stack | train |
e74a2607465d1494cc2b563a | train | class | class _ResourceDecoratorCallable(object):
def __init__(self, config=None, description=None):
self.config = check_user_facing_opt_config_param(config, 'config')
self.description = check.opt_str_param(description, 'description')
def __call__(self, fn):
check.callable_param(fn, 'fn')
... | class _ResourceDecoratorCallable(object):
| def __init__(self, config=None, description=None):
self.config = check_user_facing_opt_config_param(config, 'config')
self.description = check.opt_str_param(description, 'description')
def __call__(self, fn):
check.callable_param(fn, 'fn')
resource_def = ResourceDefinition(
... | ):
return ResourceDefinition(resource_fn=lambda _init_context: value, description=description)
@staticmethod
def string_resource(description=None):
return ResourceDefinition(
resource_fn=lambda init_context: init_context.resource_config,
config=str,
descripti... | 64 | 64 | 106 | 7 | 57 | hspak/dagster | python_modules/dagster/dagster/core/definitions/resource.py | Python | _ResourceDecoratorCallable | _ResourceDecoratorCallable | 90 | 104 | 90 | 90 | be89d234953424534f1fb029e9f57864f4a36ed6 | bigcode/the-stack | train |
b92d21ef6c22cc2c72208290 | train | class | class ScopedResourcesBuilder(namedtuple('ScopedResourcesBuilder', 'resource_instance_dict')):
'''There are concepts in the codebase (e.g. solids, system storage) that receive
only the resources that they have specified in required_resource_keys.
ScopedResourcesBuilder is responsible for dynamically building... | class ScopedResourcesBuilder(namedtuple('ScopedResourcesBuilder', 'resource_instance_dict')):
| '''There are concepts in the codebase (e.g. solids, system storage) that receive
only the resources that they have specified in required_resource_keys.
ScopedResourcesBuilder is responsible for dynamically building a class with
only those required resources and returning an instance of that class.'''
... | instance of :py:class:`~dagster.Field`.
description(Optional[str]): A human-readable description of the resource.
'''
# This case is for when decorator is used bare, without arguments.
# E.g. @resource versus @resource()
if callable(config) and not is_callable_valid_config_arg(config):
... | 120 | 120 | 400 | 16 | 103 | hspak/dagster | python_modules/dagster/dagster/core/definitions/resource.py | Python | ScopedResourcesBuilder | ScopedResourcesBuilder | 157 | 201 | 157 | 157 | 681572bc1e6e813ba49be1d6d5221d8f8825fa15 | bigcode/the-stack | train |
73bdfed6463bd67180f940d6 | train | class | class ResourceDefinition(object):
'''Core class for defining resources.
Resources are scoped ways to make external resources (like database connections) available to
solids during pipeline execution and to clean up after execution resolves.
If resource_fn yields once rather than returning (in the mann... | class ResourceDefinition(object):
| '''Core class for defining resources.
Resources are scoped ways to make external resources (like database connections) available to
solids during pipeline execution and to clean up after execution resolves.
If resource_fn yields once rather than returning (in the manner of functions decorable with
... | from collections import namedtuple
from functools import update_wrapper
from dagster import check
from dagster.config.field_utils import check_user_facing_opt_config_param
from dagster.core.definitions.config import is_callable_valid_config_arg
from dagster.core.errors import DagsterUnknownResourceError
class Resource... | 64 | 222 | 742 | 5 | 58 | hspak/dagster | python_modules/dagster/dagster/core/definitions/resource.py | Python | ResourceDefinition | ResourceDefinition | 10 | 87 | 10 | 10 | 7cec4aa781312a66fc2ea2836afd97247d8535e7 | bigcode/the-stack | train |
1ebc59be0150a17aa7abd735 | train | function | def resource(config=None, description=None):
'''Define a resource.
The decorated function should accept an :py:class:`InitResourceContext` and return an instance of
the resource. This function will become the ``resource_fn`` of an underlying
:py:class:`ResourceDefinition`.
If the decorated functio... | def resource(config=None, description=None):
| '''Define a resource.
The decorated function should accept an :py:class:`InitResourceContext` and return an instance of
the resource. This function will become the ``resource_fn`` of an underlying
:py:class:`ResourceDefinition`.
If the decorated function yields once rather than returning (in the m... | Definition(resource_fn=lambda _init_context: value, description=description)
@staticmethod
def string_resource(description=None):
return ResourceDefinition(
resource_fn=lambda init_context: init_context.resource_config,
config=str,
description=description,
)
... | 167 | 167 | 557 | 8 | 158 | hspak/dagster | python_modules/dagster/dagster/core/definitions/resource.py | Python | resource | resource | 107 | 154 | 107 | 107 | d296538ef4170d43695094cd2a3061cece802091 | bigcode/the-stack | train |
433214b5042bcb0b6b369b57 | train | class | class TestChannelsRoutes:
@pytest.mark.asyncio
async def test_create_dm_channel(
self, app: FastAPI, db: Database, current_user: User, authorized_client: AsyncClient
):
members = []
for x in range(3):
user = User(wallet_address=f"0x{x}")
await user.commit()
... | class TestChannelsRoutes:
@pytest.mark.asyncio
| async def test_create_dm_channel(
self, app: FastAPI, db: Database, current_user: User, authorized_client: AsyncClient
):
members = []
for x in range(3):
user = User(wallet_address=f"0x{x}")
await user.commit()
members.append(user)
data = {"ki... | import pytest
from fastapi import FastAPI
from httpx import AsyncClient
from pymongo.database import Database
from app.models.channel import Channel
from app.models.server import Server
from app.models.user import User
from app.schemas.servers import ServerCreateSchema
from app.services.servers import create_server
cl... | 76 | 256 | 1,433 | 12 | 63 | kalaspuff/newshades-api | app/tests/routers/test_channels.py | Python | TestChannelsRoutes | TestChannelsRoutes | 13 | 172 | 13 | 14 | ca042ca904bd1a6c7990afc862040df262be91b2 | bigcode/the-stack | train |
ecd9f750e93fc1217614789f | train | function | @callback
def async_register_signal_handling(hass):
"""Register system signal handler for core."""
if sys.platform != 'win32':
@callback
def async_signal_handle(exit_code):
"""Wrap signal handling."""
hass.async_add_job(hass.async_stop(exit_code))
try:
... | @callback
def async_register_signal_handling(hass):
| """Register system signal handler for core."""
if sys.platform != 'win32':
@callback
def async_signal_handle(exit_code):
"""Wrap signal handling."""
hass.async_add_job(hass.async_stop(exit_code))
try:
hass.loop.add_signal_handler(
sign... | """Signal handling related helpers."""
import logging
import signal
import sys
from homeassistant.core import callback
from homeassistant.const import RESTART_EXIT_CODE
_LOGGER = logging.getLogger(__name__)
@callback
def async_register_signal_handling(hass):
| 53 | 64 | 143 | 12 | 41 | EmitKiwi/home-assistant | homeassistant/helpers/signal.py | Python | async_register_signal_handling | async_register_signal_handling | 12 | 31 | 12 | 13 | e25e57ff9a08fc975c3833f1fd6df397108972b4 | bigcode/the-stack | train |
e7dbfa1748ed5118eb15ac10 | train | function | def binary_search(number_list, number_to_find):
left_index = 0
right_index = len(number_list) - 1
mid_index = 0
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = number_list[mid_index]
if mid_number == number_to_find:
... | def binary_search(number_list, number_to_find):
| left_index = 0
right_index = len(number_list) - 1
mid_index = 0
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = number_list[mid_index]
if mid_number == number_to_find:
return mid_index
if mid_number <= nu... | def binary_search(number_list, number_to_find):
| 10 | 64 | 119 | 10 | 0 | shruti-bt/Algorithm-python | exercise_binary_search.py | Python | binary_search | binary_search | 1 | 18 | 1 | 1 | 1f2c6da3e0d45085dfa22021a4d9fe93ac3f2fbf | bigcode/the-stack | train |
3b4da5b792f18cc55fc2b1a2 | train | function | def find_all_occurances(number, number_to_find):
index = binary_search(number, number_to_find)
indices = [index]
i = index - 1
while i >= 0:
if number[i] == number_to_find:
indices.append(i)
else:
break
i = i - 1
while i < len(number):
... | def find_all_occurances(number, number_to_find):
| index = binary_search(number, number_to_find)
indices = [index]
i = index - 1
while i >= 0:
if number[i] == number_to_find:
indices.append(i)
else:
break
i = i - 1
while i < len(number):
if number[i] == number_to_find:
... | ]
if mid_number == number_to_find:
return mid_index
if mid_number <= number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1
return -1
def find_all_occurances(number, number_to_find):
| 64 | 64 | 114 | 12 | 51 | shruti-bt/Algorithm-python | exercise_binary_search.py | Python | find_all_occurances | find_all_occurances | 19 | 37 | 19 | 19 | fef0a88d1fde7be7f34cd0c9323da78cfc2b9002 | bigcode/the-stack | train |
065ac73485b67049cc494a57 | train | function | def detectBarCode(filename):
with open(filename, 'rb') as f: # 以二进制读取图片
data = f.read()
encodestr = base64.b64encode(data) # 得到 byte 编码的数据
img_base64 = str(encodestr, 'utf-8')
# print(ret) # 重新编码数据
try:
cred = credential.Credential(
"AKIDifTjkYFTYNxYu8tQ4f... | def detectBarCode(filename):
| with open(filename, 'rb') as f: # 以二进制读取图片
data = f.read()
encodestr = base64.b64encode(data) # 得到 byte 编码的数据
img_base64 = str(encodestr, 'utf-8')
# print(ret) # 重新编码数据
try:
cred = credential.Credential(
"AKIDifTjkYFTYNxYu8tQ4f4E9pRp2INEKSnl", "4KtGQN5YmmX... | # This Python file uses the following encoding: utf-8
import json
import base64
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception ... | 91 | 96 | 323 | 6 | 84 | WangShuoran/barCodeDetector | tencentsdk.py | Python | detectBarCode | detectBarCode | 11 | 44 | 11 | 11 | 46d42e34badb741e8e599c118c7eaf5d200f6c80 | bigcode/the-stack | train |
68cde9609a6e1e6a11aa515b | train | function | def test_launch_url_get(rp_logger, rp_launch_id, rp_endpoint, rp_project):
"""
This is a test which gets Launch ID, Report Portal endpoint and Project
Name from fixtures in `conftest.py` and prints the result in logs, both: in
console and on Report Portal
"""
rp_logger.info("Got launch ID: %s", ... | def test_launch_url_get(rp_logger, rp_launch_id, rp_endpoint, rp_project):
| """
This is a test which gets Launch ID, Report Portal endpoint and Project
Name from fixtures in `conftest.py` and prints the result in logs, both: in
console and on Report Portal
"""
rp_logger.info("Got launch ID: %s", rp_launch_id)
rp_logger.info("Launch URL: %s/ui/#%s/launches/all/%s", r... | def test_launch_url_get(rp_logger, rp_launch_id, rp_endpoint, rp_project):
| 19 | 64 | 122 | 19 | 0 | reportportal/examples-python | pytest/tests/test_launch_url_get.py | Python | test_launch_url_get | test_launch_url_get | 2 | 11 | 2 | 2 | 9a94745682706b78f93001f6ae411c9a00831118 | bigcode/the-stack | train |
b9b961aeab5eb7db025b2b12 | train | class | class BitFieldTest(unittest.TestCase):
def test_longlong(self):
class X(Structure):
_fields_ = [("a", c_longlong, 1),
("b", c_longlong, 62),
("c", c_longlong, 1)]
self.failUnlessEqual(sizeof(X), sizeof(c_longlong))
x = X()
... | class BitFieldTest(unittest.TestCase):
| def test_longlong(self):
class X(Structure):
_fields_ = [("a", c_longlong, 1),
("b", c_longlong, 62),
("c", c_longlong, 1)]
self.failUnlessEqual(sizeof(X), sizeof(c_longlong))
x = X()
x.a, x.b, x.c = -1, 7, -1
self.... | ypes_test.__file__).unpack_bitfields
func.argtypes = POINTER(BITS), c_char
##for n in "ABCDEFGHIMNOPQRS":
## print n, hex(getattr(BITS, n).size), getattr(BITS, n).offset
class C_Test(unittest.TestCase):
def test_ints(self):
for i in range(512):
for name in "ABCDEFGHI":
b = ... | 256 | 256 | 1,902 | 8 | 247 | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/ctypes/test/test_bitfields.py | Python | BitFieldTest | BitFieldTest | 53 | 241 | 53 | 54 | 70ef6ee0ff8da41c36c2874bab695bda8d0defbb | bigcode/the-stack | train |
b6902f5e7286eaf6518bb36c | train | class | class BITS(Structure):
_fields_ = [("A", c_int, 1),
("B", c_int, 2),
("C", c_int, 3),
("D", c_int, 4),
("E", c_int, 5),
("F", c_int, 6),
("G", c_int, 7),
("H", c_int, 8),
("I", c_int, 9),
... | class BITS(Structure):
| _fields_ = [("A", c_int, 1),
("B", c_int, 2),
("C", c_int, 3),
("D", c_int, 4),
("E", c_int, 5),
("F", c_int, 6),
("G", c_int, 7),
("H", c_int, 8),
("I", c_int, 9),
("M", ... | from ctypes import *
import unittest
import os
import ctypes
import _ctypes_test
class BITS(Structure):
| 25 | 64 | 171 | 6 | 18 | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/ctypes/test/test_bitfields.py | Python | BITS | BITS | 8 | 25 | 8 | 8 | 37922f3aa39cb0ea11d58241de47b2042c9512d2 | bigcode/the-stack | train |
c4666937ea8d7b6db09d02e1 | train | class | class C_Test(unittest.TestCase):
def test_ints(self):
for i in range(512):
for name in "ABCDEFGHI":
b = BITS()
setattr(b, name, i)
self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))
def test_shorts(self):
... | class C_Test(unittest.TestCase):
| def test_ints(self):
for i in range(512):
for name in "ABCDEFGHI":
b = BITS()
setattr(b, name, i)
self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))
def test_shorts(self):
for i in range(256):
... | ctypes_test.__file__).unpack_bitfields
func.argtypes = POINTER(BITS), c_char
##for n in "ABCDEFGHIMNOPQRS":
## print n, hex(getattr(BITS, n).size), getattr(BITS, n).offset
class C_Test(unittest.TestCase):
| 64 | 64 | 136 | 7 | 56 | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/ctypes/test/test_bitfields.py | Python | C_Test | C_Test | 33 | 47 | 33 | 34 | 7830d9f8ab60c407787ddcb8f5c17419b6365341 | bigcode/the-stack | train |
5788e273a20e1b1d5f68fe88 | train | class | class Requests:
def __init__(self, verify):
self._verify = verify
@property
def verify(self):
return self._verify
def __getattr__(self, name):
def decorate(callble):
def func(*args, **kwargs):
return callble(*args, **kwargs, verify=self._verify)
... | class Requests:
| def __init__(self, verify):
self._verify = verify
@property
def verify(self):
return self._verify
def __getattr__(self, name):
def decorate(callble):
def func(*args, **kwargs):
return callble(*args, **kwargs, verify=self._verify)
return f... | import requests
import urllib3
# SSLでの検証を無効化した場合に Warning を非表示にする
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Requests:
| 44 | 64 | 88 | 3 | 41 | az-takano/dialogapi | dialogapi/requests.py | Python | Requests | Requests | 8 | 22 | 8 | 8 | 477f2aadfbebc7351c34f231d5ca78e99848560b | bigcode/the-stack | train |
627719c6eec5d8836a39ad08 | train | function | def test_get_level_number_integer(idx):
idx.names = [1, 0]
assert idx._get_level_number(1) == 0
assert idx._get_level_number(0) == 1
msg = "Too many levels: Index has only 2 levels, not 3"
with pytest.raises(IndexError, match=msg):
idx._get_level_number(2)
with pytest.raises(KeyError, ma... | def test_get_level_number_integer(idx):
| idx.names = [1, 0]
assert idx._get_level_number(1) == 0
assert idx._get_level_number(0) == 1
msg = "Too many levels: Index has only 2 levels, not 3"
with pytest.raises(IndexError, match=msg):
idx._get_level_number(2)
with pytest.raises(KeyError, match='Level fourth not found'):
i... | # as much as possible
assert len(actual) == len(expected)
for act, exp in zip(actual, expected):
act = np.asarray(act)
exp = np.asarray(exp)
tm.assert_numpy_array_equal(act, exp, check_dtype=check_dtype)
def test_get_level_number_integer(idx):
| 64 | 64 | 109 | 8 | 56 | kpflugshaupt/pandas | pandas/tests/indexes/multi/test_get_set.py | Python | test_get_level_number_integer | test_get_level_number_integer | 22 | 30 | 22 | 22 | a29f15a2af978f312e7c47d1833665720167628b | bigcode/the-stack | train |
370b3222d23879bff3ce76ef | train | function | def test_get_level_values_int_with_na():
# GH 17924
arrays = [['a', 'b', 'b'], [1, np.nan, 2]]
index = pd.MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = Index([1, np.nan, 2])
tm.assert_index_equal(result, expected)
arrays = [['a', 'b', 'b'], [np.nan, np.nan, 2]... | def test_get_level_values_int_with_na():
# GH 17924
| arrays = [['a', 'b', 'b'], [1, np.nan, 2]]
index = pd.MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = Index([1, np.nan, 2])
tm.assert_index_equal(result, expected)
arrays = [['a', 'b', 'b'], [np.nan, np.nan, 2]]
index = pd.MultiIndex.from_arrays(arrays)
resu... | 64)
tm.assert_index_equal(result, expected)
result = index.get_level_values(1)
expected = pd.Index(['a', np.nan, 1], dtype=object)
tm.assert_index_equal(result, expected)
def test_get_level_values_int_with_na():
# GH 17924
| 64 | 64 | 146 | 16 | 48 | kpflugshaupt/pandas | pandas/tests/indexes/multi/test_get_set.py | Python | test_get_level_values_int_with_na | test_get_level_values_int_with_na | 82 | 94 | 82 | 83 | 26f6d61bd24005c3cb39883d60bc69d0dbe0dde8 | bigcode/the-stack | train |
6013a3be54b07cb9ea7fa995 | train | function | @pytest.mark.parametrize('inplace', [True, False])
def test_set_names_with_nlevel_1(inplace):
# GH 21149
# Ensure that .set_names for MultiIndex with
# nlevels == 1 does not raise any errors
expected = pd.MultiIndex(levels=[[0, 1]],
codes=[[0, 1]],
... | @pytest.mark.parametrize('inplace', [True, False])
def test_set_names_with_nlevel_1(inplace):
# GH 21149
# Ensure that .set_names for MultiIndex with
# nlevels == 1 does not raise any errors
| expected = pd.MultiIndex(levels=[[0, 1]],
codes=[[0, 1]],
names=['first'])
m = pd.MultiIndex.from_product([[0, 1]])
result = m.set_names('first', level=0, inplace=inplace)
if inplace:
result = m
tm.assert_index_equal(result, expecte... | idx.set_names(names, level=0)
@pytest.mark.parametrize('inplace', [True, False])
def test_set_names_with_nlevel_1(inplace):
# GH 21149
# Ensure that .set_names for MultiIndex with
# nlevels == 1 does not raise any errors
| 64 | 64 | 131 | 55 | 9 | kpflugshaupt/pandas | pandas/tests/indexes/multi/test_get_set.py | Python | test_set_names_with_nlevel_1 | test_set_names_with_nlevel_1 | 392 | 406 | 392 | 396 | 45a0b2eb7c6de5d16b8083ea03d830b28f229118 | bigcode/the-stack | train |
f6f2f0d11b316519d753f942 | train | function | def test_get_level_values_na():
arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]]
index = pd.MultiIndex.from_arrays(arrays)
result = index.get_level_values(0)
expected = pd.Index([np.nan, np.nan, np.nan])
tm.assert_index_equal(result, expected)
result = index.get_level_values(1)
expecte... | def test_get_level_values_na():
| arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]]
index = pd.MultiIndex.from_arrays(arrays)
result = index.get_level_values(0)
expected = pd.Index([np.nan, np.nan, np.nan])
tm.assert_index_equal(result, expected)
result = index.get_level_values(1)
expected = pd.Index(['a', np.nan, 1])
... | ', 'b', 'b'], [np.nan, np.nan, 2]]
index = pd.MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = Index([np.nan, np.nan, 2])
tm.assert_index_equal(result, expected)
def test_get_level_values_na():
| 68 | 68 | 227 | 7 | 61 | kpflugshaupt/pandas | pandas/tests/indexes/multi/test_get_set.py | Python | test_get_level_values_na | test_get_level_values_na | 97 | 118 | 97 | 97 | 033646d936b2ef34110d00bb7850f772bc90e586 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.