language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | astropy__astropy | astropy/tests/runner.py | {
"start": 11850,
"end": 21884
} | class ____(TestRunnerBase):
"""
A test runner for astropy tests.
"""
def packages_path(self, packages, base_path, error=None, warning=None):
"""
Generates the path for multiple packages.
Parameters
----------
packages : str
Comma separated string of ... | TestRunner |
python | getsentry__sentry | tests/sentry/snuba/test_tasks.py | {
"start": 4527,
"end": 12605
} | class ____(BaseSnubaTaskTest):
expected_status = QuerySubscription.Status.CREATING
task = create_subscription_in_snuba # type: ignore[assignment]
def test_already_created(self) -> None:
sub = self.create_subscription(
QuerySubscription.Status.CREATING, subscription_id=uuid4().hex
... | CreateSubscriptionInSnubaTest |
python | neetcode-gh__leetcode | python/0349-intersection-of-two-arrays.py | {
"start": 0,
"end": 275
} | class ____:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
seen = set(nums1)
res = []
for n in nums2:
if n in seen:
res.append(n)
seen.remove(n)
return res
| Solution |
python | numba__numba | numba/tests/test_random.py | {
"start": 53194,
"end": 55403
} | class ____(BaseTest):
"""
Test np.random.multinomial.
"""
# A biased dice
pvals = np.array([1, 1, 1, 2, 3, 1], dtype=np.float64)
pvals /= pvals.sum()
def _check_sample(self, n, pvals, sample):
"""
Check distribution of some samples.
"""
self.assertIsInstance(... | TestRandomMultinomial |
python | kamyu104__LeetCode-Solutions | Python/can-convert-string-in-k-moves.py | {
"start": 48,
"end": 520
} | class ____(object):
def canConvertString(self, s, t, k):
"""
:type s: str
:type t: str
:type k: int
:rtype: bool
"""
if len(s) != len(t):
return False
cnt = [0]*26
for a, b in itertools.izip(s, t):
diff = (ord(b)-ord(a))... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/annotated1.py | {
"start": 1369,
"end": 2027
} | class ____:
x: Annotated[InitVar[int], "metadata"]
d1 = B(x=4)
# This should generate an error because x is not an actual member.
d1.x
Alias1 = Annotated[_T, ""]
Alias2 = str
Alias3 = Alias1[Alias2]
reveal_type(Alias3, expected_text="type[str]")
x2: Annotated[str, [*(1, 2)]]
x3: Annotated[str, (temp := 1)]
... | B |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 1649,
"end": 1697
} | class ____(Mixin7, Protocol7):
pass
| Concrete7B |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/base.py | {
"start": 11691,
"end": 12242
} | class ____:
"""Column statistics collector."""
__slots__ = ("column_stats", "join_info", "row_count")
row_count: dict[IR, ColumnStat[int]]
"""Estimated row count for each IR node."""
column_stats: dict[IR, dict[str, ColumnStats]]
"""Column statistics for each IR node."""
join_info: JoinInf... | StatsCollector |
python | ray-project__ray | rllib/utils/replay_buffers/tests/test_multi_agent_prioritized_replay_buffer.py | {
"start": 368,
"end": 8439
} | class ____(unittest.TestCase):
batch_id = 0
alpha = 1.0
beta = 1.0
def _generate_data(self):
self.batch_id += 1
return SampleBatch(
{
SampleBatch.T: [0, 1],
SampleBatch.ACTIONS: 2 * [np.random.choice([0, 1])],
SampleBatch.REWAR... | TestMultiAgentPrioritizedReplayBuffer |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_redshift_data.py | {
"start": 1239,
"end": 5309
} | class ____:
def test_redshift_data_trigger_serialization(self):
"""
Asserts that the RedshiftDataTrigger correctly serializes its arguments
and classpath.
"""
trigger = RedshiftDataTrigger(
statement_id=[],
task_id=TEST_TASK_ID,
aws_conn_id... | TestRedshiftDataTrigger |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 375043,
"end": 381633
} | class ____(SequenceNode):
# Tuple constructor.
type = tuple_type
is_partly_literal = False
gil_message = "Constructing Python tuple"
def infer_type(self, env):
if self.mult_factor or not self.args:
return tuple_type
arg_types = [arg.infer_type(env) for arg in self.arg... | TupleNode |
python | coleifer__peewee | tests/base.py | {
"start": 4578,
"end": 4808
} | class ____(logging.Handler):
def __init__(self, *args, **kwargs):
self.queries = []
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.queries.append(record)
| QueryLogHandler |
python | kennethreitz__tablib | src/tablib/packages/dbfpy/fields.py | {
"start": 1578,
"end": 6732
} | class ____:
"""Abstract field definition.
Child classes must override ``type`` class attribute to provide datatype
information of the field definition. For more info about types visit
`http://www.clicketyclick.dk/databases/xbase/format/data_types.html`
Also child classes must override ``defaultVal... | DbfFieldDef |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/shim_components/sensor.py | {
"start": 226,
"end": 552
} | class ____(ShimScaffolder):
def get_text(self, request: ScaffoldRequest) -> str:
return f"""import dagster as dg
@dg.sensor(target=None)
def {request.target_path.stem}(context: dg.SensorEvaluationContext) -> dg.SensorResult:
return dg.SensorResult()
"""
scaffold_with(SensorScaffolder)(sensor)
| SensorScaffolder |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/qual_names.py | {
"start": 1131,
"end": 1227
} | class ____(collections.namedtuple('Symbol', ['name'])):
"""Represents a Python symbol."""
| Symbol |
python | numpy__numpy | numpy/f2py/tests/test_docs.py | {
"start": 826,
"end": 1930
} | class ____(util.F2PyTest):
# options = ['--debug-capi', '--build-dir', '/tmp/build-f2py']
sources = [_path('asterisk1.f90'), _path('asterisk2.f90'),
_path('ftype.f')]
def test_asterisk1(self):
foo = self.module.foo1
assert_equal(foo(), b'123456789A12')
def test_asterisk2... | TestDocAdvanced |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 15869,
"end": 16582
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(sel... | RoCBertSelfOutput |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 171179,
"end": 174346
} | class ____:
def test_compare_t(self):
# Verify that jf_skew_t with a=b recovers the t distribution with 2a
# degrees of freedom
a = b = 5
df = a * 2
x = [-1.0, 0.0, 1.0, 2.0]
q = [0.0, 0.1, 0.25, 0.75, 0.90, 1.0]
jf = stats.jf_skew_t(a, b)
t = stats.t... | TestJFSkewT |
python | docker__docker-py | docker/context/api.py | {
"start": 208,
"end": 6326
} | class ____:
"""Context API.
Contains methods for context management:
create, list, remove, get, inspect.
"""
DEFAULT_CONTEXT = Context("default", "swarm")
@classmethod
def create_context(
cls, name, orchestrator=None, host=None, tls_cfg=None,
default_namespace=None, ... | ContextAPI |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 179521,
"end": 192762
} | class ____:
def _series(self, v, z, n=100):
"""Compute Struve function & error estimate from its power series."""
k = arange(0, n)
r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5)
err = abs(r).max() * finfo(double).eps * n
return r.sum(), err
d... | TestStruve |
python | ray-project__ray | python/ray/autoscaler/_private/gcp/node.py | {
"start": 4221,
"end": 5176
} | class ____(UserDict, metaclass=abc.ABCMeta):
"""Abstraction around compute and tpu nodes"""
NON_TERMINATED_STATUSES = None
RUNNING_STATUSES = None
STATUS_FIELD = None
def __init__(self, base_dict: dict, resource: "GCPResource", **kwargs) -> None:
super().__init__(base_dict, **kwargs)
... | GCPNode |
python | pola-rs__polars | py-polars/src/polars/expr/struct.py | {
"start": 379,
"end": 11015
} | class ____:
"""Namespace for struct related expressions."""
_accessor = "struct"
def __init__(self, expr: Expr) -> None:
self._pyexpr = expr._pyexpr
def __getitem__(self, item: str | int) -> Expr:
if isinstance(item, str):
return self.field(item)
elif isinstance(it... | ExprStructNameSpace |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/selection.py | {
"start": 530,
"end": 1941
} | class ____(Expr):
__slots__ = ()
_non_child = ("dtype",)
def __init__(self, dtype: DataType, values: Expr, indices: Expr) -> None:
self.dtype = dtype
self.children = (values, indices)
self.is_pointwise = False
def do_evaluate(
self, df: DataFrame, *, context: ExecutionC... | Gather |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec4.py | {
"start": 284,
"end": 2511
} | class ____: ...
def with_request(f: Callable[Concatenate[Request, P], R]) -> Callable[P, R]:
def inner(*args: P.args, **kwargs: P.kwargs) -> R:
return f(Request(), *args, **kwargs)
return inner
@with_request
def takes_int_str(request: Request, x: int, y: str) -> int:
# use request
return x ... | Request |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 13464,
"end": 14716
} | class ____:
"""Base class for explicit indexer objects.
ExplicitIndexer objects wrap a tuple of values given by their ``tuple``
property. These tuples should always have length equal to the number of
dimensions on the indexed array.
Do not instantiate BaseIndexer objects directly: instead, use one... | ExplicitIndexer |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/identity_output_test.py | {
"start": 1279,
"end": 2010
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Testing engine with the same tensor repeated as output via identity."""
def GraphFn(self, x):
x1 = math_ops.exp(x)
x1 = x1 + x
out1 = array_ops.identity(x1, name='output_0')
out2 = array_ops.identity(x1, name='output_1')
iden1 = array_ops.ident... | IdentityTest |
python | pytorch__pytorch | test/functorch/test_control_flow.py | {
"start": 331425,
"end": 335354
} | class ____(torch.nn.Module):
def forward(self, L_t_: "f32[2, 3]"):
l_t_ = L_t_
sum_1: "f32[]" = l_t_.sum()
to: "i64[]" = sum_1.to(torch.int64); sum_1 = None
item: "Sym(u0)" = to.item(); to = None
sin: "f32[2, 3]" = l_t_.sin()
cond_fn_0 = self.cond_fn_0
bod... | GraphModule |
python | getsentry__sentry | src/sentry/sentry_apps/api/bases/sentryapps.py | {
"start": 10763,
"end": 11538
} | class ____(IntegrationPlatformEndpoint):
def convert_args(
self, request: Request, sentry_app_id_or_slug: int | str, *args: Any, **kwargs: Any
):
if str(sentry_app_id_or_slug).isdecimal():
sentry_app = app_service.get_sentry_app_by_id(id=int(sentry_app_id_or_slug))
else:
... | RegionSentryAppBaseEndpoint |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2userfunc.py | {
"start": 6140,
"end": 6350
} | class ____(TestNodeMatch_Graph):
def setup_method(self):
TestNodeMatch_Graph.setup_method(self)
self.g1 = nx.DiGraph()
self.g2 = nx.DiGraph()
self.build()
| TestEdgeMatch_DiGraph |
python | scipy__scipy | benchmarks/benchmarks/stats_sampling.py | {
"start": 5192,
"end": 6072
} | class ____(Benchmark):
param_names = ['dist']
params = [allcontdists]
def setup(self, dist):
self.urng = np.random.default_rng(0xb235b58c1f616c59c18d8568f77d44d1)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
try:
s... | NumericalInversePolynomial |
python | doocs__leetcode | solution/0300-0399/0335.Self Crossing/Solution.py | {
"start": 0,
"end": 611
} | class ____:
def isSelfCrossing(self, distance: List[int]) -> bool:
d = distance
for i in range(3, len(d)):
if d[i] >= d[i - 2] and d[i - 1] <= d[i - 3]:
return True
if i >= 4 and d[i - 1] == d[i - 3] and d[i] + d[i - 4] >= d[i - 2]:
return True... | Solution |
python | openai__gym | gym/core.py | {
"start": 712,
"end": 10073
} | class ____(Generic[ObsType, ActType]):
r"""The main OpenAI Gym class.
It encapsulates an environment with arbitrary behind-the-scenes dynamics.
An environment can be partially or fully observed.
The main API methods that users of this class need to know are:
- :meth:`step` - Takes a step in the e... | Env |
python | doocs__leetcode | solution/1700-1799/1701.Average Waiting Time/Solution.py | {
"start": 0,
"end": 229
} | class ____:
def averageWaitingTime(self, customers: List[List[int]]) -> float:
tot = t = 0
for a, b in customers:
t = max(t, a) + b
tot += t - a
return tot / len(customers)
| Solution |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_ticker.py | {
"start": 23339,
"end": 23736
} | class ____:
def test_set_params(self):
"""
Create index locator with 3 base, 4 offset. and change it to something
else. See if change was successful.
Should not exception.
"""
index = mticker.IndexLocator(base=3, offset=4)
index.set_params(base=7, offset=7)
... | TestIndexLocator |
python | jazzband__django-oauth-toolkit | oauth2_provider/exceptions.py | {
"start": 1301,
"end": 1418
} | class ____(InvalidRequestFatalError):
description = "Invalid post logout redirect URI."
| InvalidOIDCRedirectURIError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess2.py | {
"start": 898,
"end": 995
} | class ____(TypedDict):
a: Callable[[int], int]
foo3 = Foo3(a=lambda a: a)
g = foo3["a"](3)
| Foo3 |
python | scipy__scipy | scipy/optimize/_zeros_py.py | {
"start": 43169,
"end": 56659
} | class ____:
"""Solve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi.
"""
_MU = 0.5
_K_MIN = 1
_K_MAX = 100 # A very high value for real usage. Expect 1, 2, maybe 3.
def __init__(self):
self.f = None
self.args = None
self.function_calls = 0
self.iter... | TOMS748Solver |
python | prabhupant__python-ds | data_structures/circular_linked_list/check_circular_linked_list.py | {
"start": 58,
"end": 487
} | class ____():
def __init__(self, val):
self.val = val
self.next = None
def check(head):
if not head:
return True
curr = head
while curr:
if curr.next == head:
return True
elif curr.next == None:
return False
curr = curr.next
fi... | Node |
python | kubernetes-client__python | kubernetes/client/api/scheduling_api.py | {
"start": 543,
"end": 5193
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | SchedulingApi |
python | getsentry__sentry | tests/sentry/issues/test_issue_occurrence.py | {
"start": 291,
"end": 2741
} | class ____(OccurrenceTestMixin, TestCase):
def test(self) -> None:
occurrence = self.build_occurrence()
self.assert_occurrences_identical(
occurrence, IssueOccurrence.from_dict(occurrence.to_dict())
)
def test_level_default(self) -> None:
occurrence_data = self.build... | IssueOccurrenceSerializeTest |
python | kamyu104__LeetCode-Solutions | Python/find-if-path-exists-in-graph.py | {
"start": 1241,
"end": 2239
} | class ____(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
def bfs(adj, start, target):
q = [start]
lookup = set(q)
s... | Solution2 |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 178182,
"end": 179123
} | class ____(SocketPairTest):
def __init__(self, methodName='runTest'):
SocketPairTest.__init__(self, methodName=methodName)
def _check_defaults(self, sock):
self.assertIsInstance(sock, socket.socket)
if hasattr(socket, 'AF_UNIX'):
self.assertEqual(sock.family, socket.AF_UNIX... | BasicSocketPairTest |
python | keras-team__keras | keras/src/ops/math.py | {
"start": 7727,
"end": 9104
} | class ____(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
self.axis = axis
self.keepdims = keepdims
def compute_output_spec(self, x):
output_shape = reduce_shape(x.shape, self.axis, self.keepdims)
return KerasTensor(s... | Logsumexp |
python | sqlalchemy__sqlalchemy | test/orm/test_of_type.py | {
"start": 1337,
"end": 9196
} | class ____:
__dialect__ = "default"
def test_any_one(self):
sess = fixture_session()
any_ = Company.employees.of_type(Engineer).any(
Engineer.primary_language == "cobol"
)
eq_(sess.query(Company).filter(any_).one(), self.c2)
def test_any_two(self):
sess ... | _PolymorphicTestBase |
python | sphinx-doc__sphinx | sphinx/builders/latex/transforms.py | {
"start": 803,
"end": 1217
} | class ____(SphinxTransform):
"""Add docname to footnote and footnote_reference nodes."""
default_priority = 700
TARGET_NODES = (nodes.footnote, nodes.footnote_reference)
def apply(self, **kwargs: Any) -> None:
matcher = NodeMatcher(*self.TARGET_NODES)
for node in matcher.findall(self.d... | FootnoteDocnameUpdater |
python | kamyu104__LeetCode-Solutions | Python/combination-sum-ii.py | {
"start": 39,
"end": 898
} | class ____(object):
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combinat... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-interval-to-include-each-query.py | {
"start": 68,
"end": 826
} | class ____(object):
def minInterval(self, intervals, queries):
"""
:type intervals: List[List[int]]
:type queries: List[int]
:rtype: List[int]
"""
intervals.sort()
queries = [(q, i) for i, q in enumerate(queries)]
queries.sort()
min_heap = []
... | Solution |
python | google__jax | tests/monitoring_test.py | {
"start": 845,
"end": 5722
} | class ____(absltest.TestCase):
def tearDown(self):
monitoring.clear_event_listeners()
super().tearDown()
def test_record_event(self):
events = []
counters = {} # Map event names to frequency.
def increment_event_counter(event):
if event not in counters:
counters[event] = 0
... | MonitoringTest |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/checkpoint_test.py | {
"start": 2049,
"end": 24542
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
def tearDown(self):
prefix = self._iterator_checkpoint_prefix()
pattern = prefix + "*"
files = gfile.Glob(pattern)
map(gfile.Remove, files)
super(CheckpointTest, self).tearDown()
def _iterator_checkpoint_prefix(self):
return os... | CheckpointTest |
python | walkccc__LeetCode | solutions/1324. Print Words Vertically/1324.py | {
"start": 0,
"end": 332
} | class ____:
def printVertically(self, s: str) -> list[str]:
ans = []
words = s.split()
maxLength = max(len(word) for word in words)
for i in range(maxLength):
row = []
for word in words:
row.append(word[i] if i < len(word) else ' ')
ans.append(''.join(row).rstrip())
ret... | Solution |
python | huggingface__transformers | src/transformers/models/glm46v/modeling_glm46v.py | {
"start": 24726,
"end": 26056
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | Glm46VCausalLMOutputWithPast |
python | pandas-dev__pandas | setup.py | {
"start": 7780,
"end": 8577
} | class ____(build_ext):
"""
Subclass build_ext to get clearer report if Cython is necessary.
"""
def check_cython_extensions(self, extensions) -> None:
for ext in extensions:
for src in ext.sources:
if not os.path.exists(src):
print(f"{ext.name}: -... | CheckingBuildExt |
python | tornadoweb__tornado | tornado/ioloop.py | {
"start": 31102,
"end": 32169
} | class ____:
"""An IOLoop timeout, a UNIX timestamp and a callback"""
# Reduce memory overhead when there are lots of pending callbacks
__slots__ = ["deadline", "callback", "tdeadline"]
def __init__(
self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
) -> None:
if ... | _Timeout |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_rds.py | {
"start": 28529,
"end": 29905
} | class ____:
@classmethod
def setup_class(cls):
cls.dag = DAG(
dag_id="test_dag",
schedule=None,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
)
cls.hook = RdsHook(aws_conn_id=AWS_CONN, region_name="us-east-1")
_patch_hook_get_c... | TestRdsDeleteEventSubscriptionOperator |
python | numba__numba | numba/cuda/cudadrv/devices.py | {
"start": 522,
"end": 1705
} | class ____(object):
def __getattr__(self, attr):
# First time looking at "lst" attribute.
if attr == "lst":
# Device list is not initialized.
# Query all CUDA devices.
numdev = driver.get_device_count()
gpus = [_DeviceContextManager(driver.get_device(d... | _DeviceList |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 1494,
"end": 1825
} | class ____(unittest.TestCase):
def test_https_server_raises_runtime_error(self):
with import_helper.isolated_modules():
sys.modules['ssl'] = None
certfile = certdata_file("keycert.pem")
with self.assertRaises(RuntimeError):
create_https_server(certfile)
| TestSSLDisabled |
python | openai__openai-python | src/openai/types/eval_create_response.py | {
"start": 2256,
"end": 2635
} | class ____(ScoreModelGrader):
__test__ = False
pass_threshold: Optional[float] = None
"""The threshold for the score."""
TestingCriterion: TypeAlias = Union[
LabelModelGrader,
StringCheckGrader,
TestingCriterionEvalGraderTextSimilarity,
TestingCriterionEvalGraderPython,
TestingCriterio... | TestingCriterionEvalGraderScoreModel |
python | numpy__numpy | numpy/f2py/tests/util.py | {
"start": 9761,
"end": 12112
} | class ____:
code = None
sources = None
options = []
skip = []
only = []
suffix = ".f"
module = None
_has_c_compiler = None
_has_f77_compiler = None
_has_f90_compiler = None
@property
def module_name(self):
cls = type(self)
return f'_{cls.__module__.rsplit... | F2PyTest |
python | lepture__authlib | authlib/oidc/core/errors.py | {
"start": 2424,
"end": 2572
} | class ____(OAuth2Error):
"""The OP does not support use of the request parameter."""
error = "request_not_supported"
| RequestNotSupportedError |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-weaviate/llama_index/vector_stores/weaviate/_exceptions.py | {
"start": 0,
"end": 551
} | class ____(Exception):
"""Exception raised when no synchronous weaviate client was provided via the `weaviate_client` parameter."""
def __init__(
self,
message="Sync method called without a synchronous WeaviateClient provided. Either switch to using async methods together with a provided Weavi... | SyncClientNotProvidedError |
python | keras-team__keras | keras/src/layers/convolutional/conv_test.py | {
"start": 9082,
"end": 26432
} | class ____(testing.TestCase):
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
"input_shape": (3, 5, ... | ConvBasicTest |
python | kamyu104__LeetCode-Solutions | Python/smallest-number-in-infinite-set.py | {
"start": 124,
"end": 797
} | class ____(object):
def __init__(self):
self.__n = 1
self.__lookup = set()
self.__min_heap = []
def popSmallest(self):
"""
:rtype: int
"""
if self.__min_heap:
result = heapq.heappop(self.__min_heap)
self.__lookup.remove(result)
... | SmallestInfiniteSet |
python | dask__distributed | distributed/tests/test_worker_memory.py | {
"start": 25043,
"end": 37193
} | class ____(UserDict):
"""A MutableMapping which implements distributed.spill.ManualEvictProto"""
def __init__(self):
super().__init__()
self.evicted = set()
@property
def fast(self):
# Any Sized of bool will do
return self.keys() - self.evicted
def evict(self):
... | ManualEvictDict |
python | getsentry__sentry-python | sentry_sdk/_queue.py | {
"start": 3634,
"end": 11250
} | class ____:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquir... | Queue |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 2535,
"end": 2597
} | class ____(RestartAnalysis):
pass
| SpeculationRestartAnalysis |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 585614,
"end": 586044
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("EnterpriseAdministratorIn... | EnterpriseAdministratorInvitationEdge |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 45635,
"end": 45982
} | class ____(backend_tools.ToolCopyToClipboardBase):
def trigger(self, *args, **kwargs):
pixmap = self.canvas.grab()
QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap)
FigureManagerQT._toolbar2_class = NavigationToolbar2QT
FigureManagerQT._toolmanager_toolbar_class = ToolbarQt
@_Backe... | ToolCopyToClipboardQT |
python | bokeh__bokeh | src/bokeh/models/widgets/groups.py | {
"start": 2444,
"end": 3039
} | class ____(AbstractGroup):
''' Abstract base class for groups with items rendered as check/radio
boxes.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
inline = Bool(False, help="""
Should ... | ToggleInputGroup |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 22427,
"end": 22874
} | class ____(models.Model):
state = models.CharField(max_length=100, default="new")
position = models.IntegerField()
something = models.IntegerField()
class Meta:
constraints = [
models.UniqueConstraint(
name="unique_constraint_%(class)s",
fields=("posi... | UniqueConstraintReadOnlyFieldModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 10629,
"end": 12646
} | class ____(IncrementalRkiCovidStream):
"""Docs: https://api.corona-zahlen.org/germany/germany/history/recovered/:days"""
primary_key = None
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.start_date = config.get("start_date")
@property
def source_defined_curs... | GermanHistoryRecovered |
python | django__django | tests/decorators/test_clickjacking.py | {
"start": 1470,
"end": 2654
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = xframe_options_sameorigin(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_funct... | XFrameOptionsSameoriginTests |
python | Netflix__metaflow | metaflow/lint.py | {
"start": 167,
"end": 15335
} | class ____(object):
def __init__(self):
self.require_static_graph = True
self.require_fundamentals = True
self.require_acyclicity = True
self.require_non_nested_foreach = False
self._checks = []
def _decorate(self, setting, f):
f.attrs.append(setting)
ret... | FlowLinter |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_reappeared_event_handler.py | {
"start": 381,
"end": 1786
} | class ____(ConditionTestCase):
condition = Condition.REAPPEARED_EVENT
payload = {"id": ReappearedEventCondition.id}
def test_dual_write(self) -> None:
dcg = self.create_data_condition_group()
dc = self.translate_to_data_condition(self.payload, dcg)
assert dc.type == self.condition
... | TestReappearedEventCondition |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/utils/field_validator.py | {
"start": 8888,
"end": 22404
} | class ____(LoggingMixin):
"""
Validates correctness of request body according to specification.
The specification can describe various type of
fields including custom validation, and union of fields. This validator is
to be reusable by various operators. See the EXAMPLE_VALIDATION_SPECIFICATION
... | GcpBodyFieldValidator |
python | google__jax | jax/_src/hijax.py | {
"start": 1333,
"end": 2239
} | class ____(core.Primitive):
def __init__(self, name):
self.name = name
ad.primitive_jvps[self] = self.jvp
ad.primitive_transposes[self] = self.transpose
def is_high(self, *avals, **params) -> bool:
return True
def is_effectful(self, params) -> bool: # type: ignore
return False # default im... | HiPrimitive |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_close.py | {
"start": 232,
"end": 1217
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return reverse("sentry-auth-close")
def test_renders_auth_close_view(self) -> None:
self.login_as(self.user)
resp = self.client.get(self.path)
assert resp.status_code == 200
self.assertTemplateUsed("sentr... | AuthClose |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 10801,
"end": 12696
} | class ____(TestCase, BaseIncidentsTest):
def test_projects(self) -> None:
incident = self.create_incident(
date_started=self.now - timedelta(minutes=5), query="", projects=[self.project]
)
self.create_event(self.now - timedelta(minutes=1))
self.create_event(self.now - tim... | GetMetricIssueAggregatesTest |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/schemas/test_role_and_permission_schema.py | {
"start": 1176,
"end": 2477
} | class ____:
@pytest.fixture(scope="class")
def role(self, minimal_app_for_auth_api):
with minimal_app_for_auth_api.app_context():
yield create_role(
minimal_app_for_auth_api,
name="Test",
permissions=[
(permissions.ACTION_CA... | TestRoleCollectionItemSchema |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 14207,
"end": 16202
} | class ____(xxxx.xxxxxxxxxxxxx):
def xxxxxxx_xxxxxx(xxxx):
assert xxxxxxx_xxxx in [
x.xxxxx.xxxxxx.xxxxx.xxxxxx,
x.xxxxx.xxxxxx.xxxxx.xxxx,
], ("xxxxxxxxxxx xxxxxxx xxxx (xxxxxx xxxx) %x xxx xxxxx" % xxxxxxx_xxxx)
value.__dict__[
key
] = "test" # set some Thrift field to... | xxxxxxxxxxxxxxxxxxxxx |
python | pytorch__pytorch | test/inductor/test_provenance_tracing.py | {
"start": 36609,
"end": 36921
} | class ____(TestCase):
device = "cpu"
copy_tests(
ProvenanceTracingKernelContextTemplate,
TestProvenanceTracingKernelContextCpu,
"cpu",
)
@unittest.skipIf(sys.platform == "darwin", "No CUDA on MacOS")
@unittest.skipIf(not torch.cuda.is_available(), "No CUDA")
| TestProvenanceTracingKernelContextCpu |
python | ray-project__ray | rllib/core/models/torch/heads.py | {
"start": 3104,
"end": 6137
} | class ____(TorchModel):
"""An MLPHead that implements floating log stds for Gaussian distributions."""
def __init__(self, config: FreeLogStdMLPHeadConfig) -> None:
super().__init__(config)
assert config.output_dims[0] % 2 == 0, "output_dims must be even for free std!"
self._half_output... | TorchFreeLogStdMLPHead |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectors.py | {
"start": 76417,
"end": 77372
} | class ____:
@staticmethod
def update(
*,
name: Optional[str] = None,
vector_index_config: Union[
_VectorIndexConfigHNSWUpdate,
_VectorIndexConfigFlatUpdate,
_VectorIndexConfigDynamicUpdate,
],
) -> _VectorConfigUpdate:
"""Update the... | _VectorsUpdate |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/reader_ops_test.py | {
"start": 24857,
"end": 26500
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testNoDeadlockFromQueue(self):
"""Tests that reading does not block main execution threads."""
config = config_pb2.ConfigProto(
inter_op_parallelism_threads=1, intra_op_parallelism_threads=1)
with self.session(config=config) as sess:
... | AsyncReaderTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_glue_crawler.py | {
"start": 1189,
"end": 2603
} | class ____:
def test_serialization(self):
crawler_name = "test_crawler"
poll_interval = 10
aws_conn_id = "aws_default"
trigger = GlueCrawlerCompleteTrigger(
crawler_name=crawler_name,
waiter_delay=poll_interval,
aws_conn_id=aws_conn_id,
)
... | TestGlueCrawlerCompleteTrigger |
python | getlogbook__logbook | tests/test_queues.py | {
"start": 5827,
"end": 11347
} | class ____:
def __init__(self, message, queue):
self.message = message
self.queue = queue
def __call__(self):
from logbook.queues import MultiProcessingHandler
with MultiProcessingHandler(self.queue):
logbook.warning(self.message)
@require_module("multiprocessing"... | SubscriberGroupSendBack |
python | walkccc__LeetCode | solutions/1516. Move Sub-Tree of N-Ary Tree/1516.py | {
"start": 0,
"end": 883
} | class ____:
def moveSubTree(self, root: 'Node', p: 'Node', q: 'Node') -> 'Node':
if p in q.children:
return root
# Create a dummy Node for the case when root == p
dummy = Node(None, [root])
# Get each parent of p and q
pParent = self._getParent(dummy, p)
qParent = self._getParent(p, q)... | Solution |
python | gevent__gevent | src/gevent/_fileobjectposix.py | {
"start": 737,
"end": 7303
} | class ____(RawIOBase):
# Internal, undocumented, class. All that's documented is that this
# is a IOBase object. Constructor is private.
# Note that RawIOBase has a __del__ method that calls
# self.close(). (In C implementations like CPython, this is
# the type's tp_dealloc slot; prior to Python 3,... | GreenFileDescriptorIO |
python | encode__starlette | starlette/responses.py | {
"start": 5868,
"end": 5935
} | class ____(Response):
media_type = "text/plain"
| PlainTextResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 167193,
"end": 168157
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ConvertProjectCardNoteToIssue"""
__schema__ = github_schema
__field_names__ = ("project_card_id", "repository_id", "title", "body", "client_mutation_id")
project_card_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectCard... | ConvertProjectCardNoteToIssueInput |
python | encode__django-rest-framework | tests/test_validation.py | {
"start": 2786,
"end": 3071
} | class ____(serializers.Serializer):
foo = serializers.CharField()
def validate_foo(self, attrs, source):
raise serializers.ValidationError("foo invalid")
def validate(self, attrs):
raise serializers.ValidationError("serializer invalid")
| ValidationSerializer |
python | davidhalter__jedi | jedi/inference/imports.py | {
"start": 1321,
"end": 5225
} | class ____:
def __init__(self):
self._name_cache = {}
def add(self, string_names, value_set):
if string_names is not None:
self._name_cache[string_names] = value_set
def get(self, string_names):
return self._name_cache.get(string_names)
# This memoization is needed, b... | ModuleCache |
python | GoogleCloudPlatform__python-docs-samples | pubsub/streaming-analytics/PubSubToGCS.py | {
"start": 2477,
"end": 5156
} | class ____(DoFn):
def __init__(self, output_path):
self.output_path = output_path
def process(self, key_value, window=DoFn.WindowParam):
"""Write messages in a batch to Google Cloud Storage."""
ts_format = "%H:%M"
window_start = window.start.to_utc_datetime().strftime(ts_format... | WriteToGCS |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_finder.py | {
"start": 28309,
"end": 29019
} | class ____(_AnsibleCollectionPkgLoaderBase):
def _validate_args(self):
super(_AnsibleCollectionNSPkgLoader, self)._validate_args()
if len(self._split_name) != 2:
raise ImportError('this loader can only load collections namespace packages, not {0}'.format(self._fullname))
def _valida... | _AnsibleCollectionNSPkgLoader |
python | jupyterlab__jupyterlab | jupyterlab/handlers/announcements.py | {
"start": 4545,
"end": 5948
} | class ____(APIHandler):
"""Check for Updates API handler.
Args:
update_check: The class checking for a new version
"""
def initialize(
self,
update_checker: Optional[CheckForUpdate] = None,
) -> None:
super().initialize()
self.update_checker = (
... | CheckForUpdateHandler |
python | pypa__pip | src/pip/_vendor/truststore/_windows.py | {
"start": 937,
"end": 1135
} | class ____(Structure):
_fields_ = (
("cUsageIdentifier", DWORD),
("rgpszUsageIdentifier", POINTER(LPSTR)),
)
PCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE)
| CERT_ENHKEY_USAGE |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_bic.py | {
"start": 1433,
"end": 3257
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid BIC (Business Identifier Code)."""
map_metric = "column_values.valid_bic"
success_keys = ("mostly",)
default_kwarg_values = {}
library_metadata = {
"maturity": "experimental",
"tags": [
"hackathon-2... | ExpectColumnValuesToBeValidBic |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 42310,
"end": 44178
} | class ____(test_lib.TestCase):
def testValues(self):
np_values = np.array(
[np.linspace(-7.0, 0.0, 100),
np.linspace(0.0, 7.0, 100)],
dtype=np.float32)
tf_values = constant_op.constant(np_values)
actual_tf_outputs = nn_impl.swish(tf_values)
expected_tf_outputs = tf_values * m... | SwishTest |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/basetypes.py | {
"start": 14497,
"end": 15594
} | class ____(Parameter):
"""
Group parameters are used mainly as a generic parent item that holds (and groups!) a set
of child parameters.
It also provides a simple mechanism for displaying a button or combo
that can be used to add new parameters to the group. To enable this, the group
must be in... | GroupParameter |
python | Netflix__metaflow | metaflow/client/core.py | {
"start": 83425,
"end": 86935
} | class ____(object):
"""
Entry point to all objects in the Metaflow universe.
This object can be used to list all the flows present either through the explicit property
or by iterating over this object.
Attributes
----------
flows : List[Flow]
Returns the list of all `Flow` objects ... | Metaflow |
python | automl__auto-sklearn | autosklearn/pipeline/components/feature_preprocessing/truncatedSVD.py | {
"start": 377,
"end": 2229
} | class ____(AutoSklearnPreprocessingAlgorithm):
def __init__(self, target_dim, random_state=None):
self.target_dim = target_dim
self.random_state = random_state
self.preprocessor = None
def fit(self, X, Y):
import sklearn.decomposition
self.target_dim = int(self.target_d... | TruncatedSVD |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.