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 | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py | {
"start": 173,
"end": 277
} | class ____(Endpoint):
pass
# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV)
@ray.remote
| EndpointActor |
python | django__django | tests/model_fields/models.py | {
"start": 5123,
"end": 5236
} | class ____(models.Model):
modelname = models.IntegerField(name="fieldname", choices=((1, "One"),))
| RenamedField |
python | mahmoud__boltons | boltons/iterutils.py | {
"start": 44503,
"end": 49886
} | class ____(KeyError, IndexError, TypeError):
"""An amalgamation of KeyError, IndexError, and TypeError,
representing what can occur when looking up a path in a nested
object.
"""
def __init__(self, exc, seg, path):
self.exc = exc
self.seg = seg
self.path = path
def __re... | PathAccessError |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 12753,
"end": 13118
} | class ____(BaseSafeMigrationTest):
app = "bad_flow_delete_field_double_pending_app"
migrate_from = "0001"
migrate_to = "0003"
def test(self) -> None:
with pytest.raises(
FieldDoesNotExist,
match="TestTable has no field named 'field'",
):
self.run_migr... | DeletionFieldBadDeleteDoublePendingTest |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_login.py | {
"start": 1458,
"end": 20746
} | class ____(TestCase, HybridCloudTestMixin):
@cached_property
def path(self) -> str:
return reverse("sentry-login")
def allow_registration(self):
return self.options({"auth.allow-registration": True})
def test_renders_correct_template(self) -> None:
resp = self.client.get(self.p... | AuthLoginTest |
python | scrapy__scrapy | tests/test_spiderloader/test_spiders/spider1.py | {
"start": 36,
"end": 133
} | class ____(Spider):
name = "spider1"
allowed_domains = ["scrapy1.org", "scrapy3.org"]
| Spider1 |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 185584,
"end": 198292
} | class ____(PyrexType):
"""
A C lock type that can be used in with statements
(within Cython - it can't be returned to Python) and
safely acquired while holding the GIL.
"""
is_cython_lock_type = True
has_attributes = True
exception_value = None
scope = None
# Create a reference... | CythonLockType |
python | doocs__leetcode | solution/1300-1399/1301.Number of Paths with Max Score/Solution.py | {
"start": 0,
"end": 927
} | class ____:
def pathsWithMaxScore(self, board: List[str]) -> List[int]:
def update(i, j, x, y):
if x >= n or y >= n or f[x][y] == -1 or board[i][j] in "XS":
return
if f[x][y] > f[i][j]:
f[i][j] = f[x][y]
g[i][j] = g[x][y]
el... | Solution |
python | doocs__leetcode | solution/0200-0299/0268.Missing Number/Solution2.py | {
"start": 0,
"end": 135
} | class ____:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
return (1 + n) * n // 2 - sum(nums)
| Solution |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_workflow_fire_history.py | {
"start": 298,
"end": 2088
} | class ____(BaseWorkflowTest):
def setUp(self) -> None:
(
self.workflow,
self.detector,
self.detector_workflow,
self.workflow_triggers,
) = self.create_detector_and_workflow()
self.action_group, self.action = self.create_workflow_action(workflo... | TestWorkflowFireHistory |
python | spack__spack | lib/spack/spack/test/concretization/core.py | {
"start": 6118,
"end": 6616
} | class ____(Package):
homepage = "http://www.example.com"
url = "http://www.example.com/root-1.0.tar.gz"
version("1.0", sha256="abcde")
depends_on("middle")
depends_on("changing")
conflicts("^changing~foo")
"""
package_py = packages_dir / "root" / "package.py"
package_py.parent.mkd... | Root |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 6347,
"end": 7219
} | class ____(dict):
"""
plotly.graph_objs.ErrorX is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter.ErrorX
- plotly.graph_objs.histogram.ErrorX
- etc.
"""
def __init__(self, *args, **kwargs):
"""
pl... | ErrorX |
python | scikit-learn__scikit-learn | sklearn/ensemble/_voting.py | {
"start": 1242,
"end": 6142
} | class ____(TransformerMixin, _BaseHeterogeneousEnsemble):
"""Base class for voting.
Warning: This class should not be used directly. Use derived classes
instead.
"""
_parameter_constraints: dict = {
"estimators": [list],
"weights": ["array-like", None],
"n_jobs": [None, Int... | _BaseVoting |
python | pytorch__pytorch | test/inductor/test_triton_kernels.py | {
"start": 97341,
"end": 126212
} | class ____(torch._inductor.test_case.TestCase):
# Tests injected below
@make_mutation_test
def test_out_of_order_kernel():
@triton.jit
def add_kernel_out_of_order(
in_ptr0,
n_elements,
in_ptr1,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
... | MutationTests |
python | pytorch__pytorch | torchgen/code_template.py | {
"start": 678,
"end": 3211
} | class ____:
substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})"
substitution = re.compile(substitution_str, re.MULTILINE)
pattern: str
filename: str
@staticmethod
def from_file(filename: str) -> CodeTemplate:
with open(filename) as f:
return CodeTemplate(f.r... | CodeTemplate |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/asyncio.py | {
"start": 14151,
"end": 14362
} | class ____(EmulatedDBAPIException):
"""Provide for the base of DBAPI ``Error`` base class for dialects
that need to emulate the DBAPI exception hierarchy.
.. versionadded:: 2.1
"""
| AsyncAdapt_Error |
python | tartley__colorama | colorama/ansi.py | {
"start": 489,
"end": 930
} | class ____:
def __init__(self):
# the subclasses declare class attributes which are numbers.
# Upon instantiation we define instance attributes, which are the same
# as the class attributes but wrapped with the ANSI escape sequence
for name in dir(self):
if not name.start... | AnsiCodes |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 6049,
"end": 6157
} | class ____(InvalidRequestError):
description = 'Missing response_type parameter.'
| MissingResponseTypeError |
python | pytorch__pytorch | torch/_functorch/autograd_function.py | {
"start": 27174,
"end": 28787
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("autograd_function_apply")
def __call__(self, fwd, bwd, *fwd_args, **fwd_kwargs):
saved_values = None
args_tensor_mask = fwd_kwargs["args_tensor_mask"]
non_differentiable_idx = fwd_kwargs["non_differen... | AutogradFunctionApply |
python | apache__airflow | providers/slack/tests/unit/slack/utils/test_utils.py | {
"start": 4145,
"end": 6391
} | class ____:
SUPPORTED_FORMAT = ("so", "dll", "exe", "sh")
def test_error_parse_without_extension(self):
with pytest.raises(ValueError, match="No file extension specified in filename"):
assert parse_filename("Untitled File", self.SUPPORTED_FORMAT)
@pytest.mark.parametrize(
("fil... | TestParseFilename |
python | gevent__gevent | src/gevent/_config.py | {
"start": 11547,
"end": 11781
} | class ____(Setting):
name = 'libev_backend'
environment_key = 'GEVENT_BACKEND'
desc = """\
The backend for libev, such as 'select'
"""
default = None
validate = staticmethod(validate_anything)
| LibevBackend |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 4432,
"end": 235297
} | class ____(OrganizationEventsEndpointTestBase, PerformanceIssueTestCase):
def test_no_projects(self) -> None:
response = self.do_request({})
assert response.status_code == 200, response.content
assert response.data["data"] == []
assert response.data["meta"] == {
"tips": ... | OrganizationEventsEndpointTest |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 29188,
"end": 29522
} | class ____(ExprNode):
__slots__ = ("elements",)
_translated_fields = {"elts": "elements"}
@property
def is_literal_value(self):
return all(e.is_literal_value for e in self.elements)
def validate(self):
if not self.elements:
raise InvalidLiteral("Cannot have an empty tup... | Tuple |
python | PrefectHQ__prefect | tests/workers/test_base_worker.py | {
"start": 69431,
"end": 75461
} | class ____:
async def test_worker_heartbeat_sends_integrations(
self, work_pool, hosted_api_server
):
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
await worker.start(run_once=True)
with (
mock.patch(
"prefect.work... | TestBaseWorkerHeartbeat |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 2285,
"end": 2471
} | class ____(TypedDict):
by: GroupKeyDict
series: dict[SessionsQueryFunction, list[SessionsQueryValue]]
totals: dict[SessionsQueryFunction, SessionsQueryValue]
| SessionsQueryGroup |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/assets/registry_entry.py | {
"start": 1796,
"end": 2210
} | class ____(str, Enum, metaclass=CaseInsensitveKeys):
SOURCE = "sourceDefinitionId"
DESTINATION = "destinationDefinitionId"
PolymorphicRegistryEntry = Union[ConnectorRegistrySourceDefinition, ConnectorRegistryDestinationDefinition]
TaggedRegistryEntry = Tuple[ConnectorTypes, PolymorphicRegistryEntry]
metadata... | ConnectorTypePrimaryKey |
python | getsentry__sentry | src/sentry/api/endpoints/debug_files.py | {
"start": 15776,
"end": 20955
} | class ____(ProjectEndpoint):
owner = ApiOwner.OWNERS_INGEST
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectReleasePermission,)
# Legacy endpoint, kept for backwards compatibility
def post(self, request: Request, project: Project) -> Response:
... | AssociateDSymFilesEndpoint |
python | protocolbuffers__protobuf | python/google/protobuf/internal/unknown_fields_test.py | {
"start": 1338,
"end": 6116
} | class ____(unittest.TestCase):
def setUp(self):
self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
self.all_fields = unittest_pb2.TestAllTypes()
test_util.SetAllFields(self.all_fields)
self.all_fields_data = self.all_fields.SerializeToString()
self.empty_message = unittest_pb2.TestEmptyMessag... | UnknownFieldsTest |
python | milvus-io__pymilvus | pymilvus/client/abstract.py | {
"start": 5048,
"end": 6159
} | class ____:
def __init__(self, raw: Any):
self._raw = raw
self.name = None
self.fields = []
self.description = None
self.params = {}
self.__pack(self._raw)
def __pack(self, raw: Any):
self.name = raw.name
self.field_id = raw.fieldID
self... | StructArrayFieldSchema |
python | django__django | tests/db_functions/math/test_sqrt.py | {
"start": 269,
"end": 2346
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_sqrt=Sqrt("normal")).first()
self.assertIsNone(obj.null_sqrt)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6"))
obj ... | SqrtTests |
python | xlwings__xlwings | xlwings/conversion/standard.py | {
"start": 6604,
"end": 7706
} | class ____(Accessor):
@staticmethod
def reader(options):
return (
BaseAccessor.reader(options)
.append_stage(ReadValueFromRangeStage(options))
.append_stage(Ensure2DStage())
.append_stage(CleanDataFromReadStage(options))
.append_stage(Transpose... | ValueAccessor |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/table_metrics/table_columns.py | {
"start": 725,
"end": 3028
} | class ____(TableMetricProvider):
metric_name = "table.columns"
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine: PandasExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_confi... | TableColumns |
python | pydantic__pydantic | pydantic/root_model.py | {
"start": 1135,
"end": 6311
} | class ____(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetaclass):
"""!!! abstract "Usage Documentation"
[`RootModel` and Custom Root Types](../concepts/models.md#rootmodel-and-custom-root-types)
A Pydantic `BaseModel` for the root object of the model.
Attributes:
root: The ... | RootModel |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_callbacks.py | {
"start": 3872,
"end": 6067
} | class ____(Callback):
def __init__(self, state):
self.state = state
@property
def state_key(self):
return type(self)
def state_dict(self):
return {"state": self.state}
def load_state_dict(self, state_dict) -> None:
self.state = state_dict["state"]
@patch("lightni... | OldStatefulCallback |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 30310,
"end": 31281
} | class ____(nn.Module):
"""
DeepLabv3 architecture: https://huggingface.co/papers/1706.05587
"""
def __init__(self, config: MobileViTConfig) -> None:
super().__init__()
self.aspp = MobileViTASPP(config)
self.dropout = nn.Dropout2d(config.classifier_dropout_prob)
self.cl... | MobileViTDeepLabV3 |
python | keras-team__keras | keras/src/metrics/confusion_metrics_test.py | {
"start": 35620,
"end": 41099
} | class ____(testing.TestCase):
def test_config(self):
s_obj = metrics.RecallAtPrecision(
0.4, num_thresholds=100, class_id=12, name="recall_at_precision_1"
)
self.assertEqual(s_obj.name, "recall_at_precision_1")
self.assertLen(s_obj.variables, 4)
self.assertEqual(s... | RecallAtPrecisionTest |
python | davidhalter__jedi | jedi/inference/recursion.py | {
"start": 2791,
"end": 4932
} | class ____:
"""
Catches recursions of executions.
"""
def __init__(self, inference_state):
self._inference_state = inference_state
self._recursion_level = 0
self._parent_execution_funcs = []
self._funcdef_execution_counts = {}
self._execution_count = 0
def p... | ExecutionRecursionDetector |
python | doocs__leetcode | solution/1200-1299/1219.Path with Maximum Gold/Solution.py | {
"start": 0,
"end": 519
} | class ____:
def getMaximumGold(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if not (0 <= i < m and 0 <= j < n and grid[i][j]):
return 0
v = grid[i][j]
grid[i][j] = 0
ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)... | Solution |
python | python-markdown__markdown | markdown/blockparser.py | {
"start": 2519,
"end": 5728
} | class ____:
""" Parse Markdown blocks into an `ElementTree` object.
A wrapper class that stitches the various `BlockProcessors` together,
looping through them and creating an `ElementTree` object.
"""
def __init__(self, md: Markdown):
""" Initialize the block parser.
Arguments:
... | BlockParser |
python | django__django | django/contrib/admin/filters.py | {
"start": 17497,
"end": 21446
} | class ____(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = "%s__" % field_path
self.date_params = {
k: v[-1] for k, v in params.items() if k.startswith(self.field_generic)
}
now = timezone.now()
#... | DateFieldListFilter |
python | getsentry__sentry | tests/snuba/tagstore/test_tagstore_backend.py | {
"start": 46459,
"end": 47296
} | class ____(TestCase, SnubaTestCase):
__test__ = Abstract(__module__, __qualname__)
KEY: str
def setUp(self) -> None:
super().setUp()
self.ts = SnubaTagStorage()
def run_test(self, query, expected_versions, environment=None, project=None):
if project is None:
projec... | BaseSemverTest |
python | modin-project__modin | modin/config/envvars.py | {
"start": 28881,
"end": 29066
} | class ____(EnvironmentVariable, type=ExactStr):
"""Allows to override default size of data (shapes)."""
varname = "MODIN_ASV_DATASIZE_CONFIG"
default = None
| AsvDataSizeConfig |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_either.py | {
"start": 1474,
"end": 3749
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpe.Either() # type: ignore
def test_valid(self) -> None:
prop = bcpe.Either(Interval(Int, 0, 100), Regex("^x*$"), List(Int))
assert prop.is_valid(0)
assert prop.is_valid(1)
assert pro... | Test_Either |
python | facebook__pyre-check | client/tests/find_directories_test.py | {
"start": 2042,
"end": 6209
} | class ____(testslide.TestCase):
def assert_find_parent_directory_containing_file(
self, files: Iterable[str], base: str, target: str, expected: Optional[str]
) -> None:
depth = len(base.split("/"))
with tempfile.TemporaryDirectory() as outer_root:
with tempfile.TemporaryDirec... | FindParentDirectoryContainingFileTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 847252,
"end": 848000
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for ProjectV2Field."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("ProjectV2FieldEdge"), graphql_name="edges")
"""A list of edges."""
... | ProjectV2FieldConnection |
python | mwaskom__seaborn | seaborn/axisgrid.py | {
"start": 43514,
"end": 62164
} | class ____(Grid):
"""Subplot grid for plotting pairwise relationships in a dataset.
This object maps each variable in a dataset onto a column and row in a
grid of multiple axes. Different axes-level plotting functions can be
used to draw bivariate plots in the upper and lower triangles, and the
mar... | PairGrid |
python | agronholm__apscheduler | src/apscheduler/_structures.py | {
"start": 866,
"end": 3056
} | class ____:
"""
Represents a callable and its surrounding configuration parameters.
:var str id: the unique identifier of this task
:var ~collections.abc.Callable func: the callable that is called when this task is
run
:var str job_executor: name of the job executor that will run this task
... | Task |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/pandas_data_frame.py | {
"start": 548,
"end": 1289
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "pandas-data-frame"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.unit
@override
def create_batch_setup(
self,
request: pytest.Fi... | PandasDataFrameDatasourceTestConfig |
python | pytorch__pytorch | torch/_inductor/fx_passes/micro_pipeline_tp.py | {
"start": 6159,
"end": 12679
} | class ____:
match: Match
input_node: torch.fx.Node
reduce_scatter_node: torch.fx.Node
wait_tensor_node: torch.fx.Node
reduce_op: str
scatter_dim: int
group_name: str
def replace_with(self, new_node: torch.fx.Node) -> None:
# Replace all uses of the result node (wait_tensor) with... | _ReduceScatterMatch |
python | fluentpython__example-code | 20-descriptor/descriptorkinds.py | {
"start": 5579,
"end": 5798
} | class ____: # <5>
over = Overriding()
over_no_get = OverridingNoGet()
non_over = NonOverriding()
def spam(self): # <6>
print('-> Managed.spam({})'.format(display(self)))
# END DESCR_KINDS
| Managed |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/linux/mkl/set-build-env.py | {
"start": 7267,
"end": 7901
} | class ____(IntelPlatform):
def __init__(self):
IntelPlatform.__init__(self, 8, 4)
def get_bazel_gcc_flags(self):
ICELAKE_ARCH_OLD = "skylake-avx512"
ICELAKE_ARCH_NEW = "icelake-server"
AVX512_FLAGS = ["avx512f", "avx512cd"]
if IntelPlatform.use_old_arch_names(self, 8, 4):
ret_val = self.... | IcelakeServerPlatform |
python | doocs__leetcode | solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py | {
"start": 0,
"end": 727
} | class ____:
def countPairs(
self, n: int, edges: List[List[int]], queries: List[int]
) -> List[int]:
cnt = [0] * n
g = defaultdict(int)
for a, b in edges:
a, b = a - 1, b - 1
a, b = min(a, b), max(a, b)
cnt[a] += 1
cnt[b] += 1
... | Solution |
python | viewflow__viewflow | tests/json/test_json__nullboolean.py | {
"start": 223,
"end": 1013
} | class ____(TestCase):
def test_crud(self):
model = NullBooleanFieldModel(nullboolean_field=False)
self.assertIsInstance(
model._meta.get_field('nullboolean_field'),
models.NullBooleanField
)
self.assertEqual(model.data, {
'nullboolean_field': False... | Test |
python | apache__airflow | providers/elasticsearch/src/airflow/providers/elasticsearch/log/es_response.py | {
"start": 3430,
"end": 6046
} | class ____(AttributeDict):
"""
The ElasticSearchResponse class is used to manage and access the response from an Elasticsearch search.
This class can be iterated over directly to access hits in the response. Indexing the class instance
with an integer or slice will also access the hits. The class also ... | ElasticSearchResponse |
python | aio-libs__aiohttp | docs/code/client_middleware_cookbook.py | {
"start": 4642,
"end": 5072
} | class ____(TCPConnector):
async def _resolve_host(
self, host: str, port: int, traces: Sequence[Trace] | None = None
) -> list[ResolveResult]:
res = await super()._resolve_host(host, port, traces)
# WARNING: This is a simplified example - should also check ::1, private ranges, etc.
... | SSRFConnector |
python | sphinx-doc__sphinx | sphinx/directives/__init__.py | {
"start": 1196,
"end": 13224
} | class ____(SphinxDirective, Generic[ObjDescT]):
"""Directive to describe a class, function or similar object.
Not used directly, but subclassed (in domain-specific directives)
to add custom behaviour.
"""
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_w... | ObjectDescription |
python | huggingface__transformers | src/transformers/models/mistral/modeling_mistral.py | {
"start": 9498,
"end": 11290
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MistralConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MistralAttention(config=config, layer_idx=layer_idx)
self.mlp = MistralMLP(config)
self.input_layernorm... | MistralDecoderLayer |
python | huggingface__transformers | tests/models/flex_olmo/test_modeling_flex_olmo.py | {
"start": 1283,
"end": 1915
} | class ____(CausalLMModelTest, unittest.TestCase):
test_all_params_have_gradient = False
model_tester_class = FlexOlmoModelTester
# Need to use `0.8` instead of `0.9` for `test_cpu_offload`
# This is because we are hitting edge cases with the causal_mask buffer
model_split_percents = [0.5, 0.7, 0.8]... | FlexOlmoModelTest |
python | realpython__materials | python-magic-methods/factorial.py | {
"start": 0,
"end": 242
} | class ____:
def __init__(self):
self._cache = {0: 1, 1: 1}
def __call__(self, number):
if number not in self._cache:
self._cache[number] = number * self(number - 1)
return self._cache[number]
| Factorial |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 3396,
"end": 5138
} | class ____(unittest.TestCase):
"""Tests person in the ar locale"""
def setUp(self):
self.fake = Faker("ar")
Faker.seed(0)
def test_first_name(self):
# General first name
name = self.fake.first_name()
assert name
self.assertIsInstance(name, str)
asser... | TestAr |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py | {
"start": 58405,
"end": 60001
} | class ____(TestQueuedEventEndpoint):
def test_delete_should_respond_204(self, test_client, session, create_dummy_dag):
dag, _ = create_dummy_dag()
dag_id = dag.dag_id
(asset,) = self.create_assets(session=session, num=1)
self._create_asset_dag_run_queues(dag_id, asset.id, session)
... | TestDeleteDagAssetQueuedEvent |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 4482,
"end": 5192
} | class ____(models.Model):
my_id = models.AutoField(primary_key=True)
if django.VERSION >= (5, 0, 0):
import math
class Pizza(models.Model):
AREA = math.pi * models.F("radius") ** 2
radius = models.IntegerField(validators=[MinValueValidator(1)])
slices = models.PositiveIntegerFiel... | UserSpecifiedAutoId |
python | getsentry__sentry-python | sentry_sdk/integrations/spark/spark_driver.py | {
"start": 349,
"end": 3844
} | class ____(Integration):
identifier = "spark"
@staticmethod
def setup_once():
# type: () -> None
_setup_sentry_tracing()
def _set_app_properties():
# type: () -> None
"""
Set properties in driver that propagate to worker processes, allowing for workers to have access to those ... | SparkIntegration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 663645,
"end": 664383
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for GistComment."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("GistCommentEdge"), graphql_name="edges")
"""A list of edges."""
nodes ... | GistCommentConnection |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 3651,
"end": 3758
} | class ____(metaclass=HorribleMetaclass):
pass
class_list = [WithHorrible | DefaultMetaclass]
| WithHorrible |
python | huggingface__transformers | tests/models/mpnet/test_modeling_mpnet.py | {
"start": 1234,
"end": 7547
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=99,
hidden_size=64,
num_hidden_layers=2,
num_attention_hea... | MPNetModelTester |
python | huggingface__transformers | tests/models/nystromformer/test_modeling_nystromformer.py | {
"start": 8958,
"end": 11554
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
... | NystromformerModelTest |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 19014,
"end": 19334
} | class ____(BuiltinFunction):
"""For debugging. reveal_type(x) prints the type of "x"."""
_NAME = "reveal_type"
def call(self, node, func, args, alias_map=None):
for a in args.posargs:
self.ctx.errorlog.reveal_type(self.ctx.vm.frames, node, a)
return node, self.ctx.convert.build_none(node)
| RevealType |
python | apache__airflow | airflow-core/tests/integration/cli/commands/test_celery_command.py | {
"start": 1154,
"end": 3193
} | class ____:
@classmethod
def setup_class(cls):
with conf_vars({("core", "executor"): "CeleryExecutor"}):
# The cli_parser module is loaded during test collection. Reload it here with the
# executor overridden so that we get the expected commands loaded.
reload(executo... | TestWorkerServeLogs |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_deployments.py | {
"start": 45861,
"end": 51265
} | class ____:
@pytest.fixture
async def deployment_id_1(self):
return uuid4()
@pytest.fixture
async def deployment_id_2(self):
return uuid4()
@pytest.fixture
async def deployments(
self,
session,
deployment_id_1,
deployment_id_2,
flow,
... | TestReadDeployments |
python | conda__conda | conda/activate.py | {
"start": 1767,
"end": 33505
} | class ____(metaclass=abc.ABCMeta):
# Activate and deactivate have three tasks
# 1. Set and unset environment variables
# 2. Execute/source activate.d/deactivate.d scripts
# 3. Update the command prompt
#
# Shells should also use 'reactivate' following conda's install, update, and
# r... | _Activator |
python | tensorflow__tensorflow | tensorflow/python/ops/critical_section_ops.py | {
"start": 1432,
"end": 3861
} | class ____(
collections.namedtuple("_ExecutionSignature",
("op", "handle",
"resources", "exclusive_resource_access"))):
"""A class storing an `ExecuteInCriticalResource` op and associated attrs."""
pass
def _identity(x):
"""Identity op that recognizes `... | _ExecutionSignature |
python | dagster-io__dagster | python_modules/libraries/create-dagster/create_dagster/version_check.py | {
"start": 502,
"end": 3094
} | class ____:
timestamp: float
raw_versions: list[str]
@property
def datetime(self) -> datetime.datetime:
return datetime.datetime.fromtimestamp(self.timestamp)
@cached_property
def versions(self) -> list[Version]:
return sorted(Version(v) for v in self.raw_versions)
def check_... | _PyPiVersionInfo |
python | viewflow__viewflow | tests/workflow/test_lock.py | {
"start": 454,
"end": 3694
} | class ____(TransactionTestCase):
class TestFlow(flow.Flow):
start = flow.StartHandle().Next(this.end)
end = flow.End()
def setUp(self):
self.finished = False
self.locked = False
self.process = Test.TestFlow.process_class.objects.create(flow_class=Test.TestFlow)
s... | Test |
python | kamyu104__LeetCode-Solutions | Python/palindrome-pairs.py | {
"start": 125,
"end": 1459
} | class ____(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def is_palindrome(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/feedly/provider.py | {
"start": 343,
"end": 899
} | class ____(OAuth2Provider):
id = "feedly"
name = "Feedly"
account_class = FeedlyAccount
oauth2_adapter_class = FeedlyOAuth2Adapter
def get_default_scope(self):
return ["https://cloud.feedly.com/subscriptions"]
def extract_uid(self, data):
return str(data["id"])
def extract... | FeedlyProvider |
python | pytorch__pytorch | torch/distributed/tensor/_random.py | {
"start": 4153,
"end": 5302
} | class ____:
"""
Convenience accessor for interpreting the packed bits of (seed: uint64, offset: uint64) in the philox state,
which for some reason is actually exposed as a size-16 uint8 tensor.
The state is always moved to .cpu since it is necessary for it to be on CPU before applying it back to a gene... | _PhiloxState |
python | dagster-io__dagster | python_modules/dagster/dagster/_scheduler/scheduler.py | {
"start": 6054,
"end": 32264
} | class ____(NamedTuple):
"""Timestamp information returned by each scheduler iteration that the core scheduler
loop can use to intelligently schedule the next tick.
last_iteration_timestamp is used by subsequent evaluations of this schedule to ensure that we
don't accidentally create incorrect runs afte... | ScheduleIterationTimes |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-array-values-equal-to-k.py | {
"start": 67,
"end": 309
} | class ____(object):
def minOperations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
mn = min(nums)
return len(set(nums))-int(mn == k) if mn >= k else -1
| Solution |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 1258,
"end": 2805
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_hidden_st... | SegGptEncoderOutput |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 4424,
"end": 7348
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
... | TestEnvInclude |
python | huggingface__transformers | src/transformers/models/llava_onevision/modular_llava_onevision.py | {
"start": 9386,
"end": 26480
} | class ____(LlavaNextVideoModel):
def __init__(self, config):
super().__init__(config)
del self.vision_resampler
def pack_image_features(self, image_features, image_sizes, image_newline=None, vision_aspect_ratio="anyres_max_9"):
"""
Reshape, unpad and then pack each image_feature... | LlavaOnevisionModel |
python | facebook__pyre-check | tools/upgrade/errors.py | {
"start": 768,
"end": 7498
} | class ____(libcst.CSTTransformer):
def leave_SimpleWhitespace(
self,
original_node: libcst.SimpleWhitespace,
updated_node: libcst.SimpleWhitespace,
) -> Union[libcst.SimpleWhitespace, libcst.ParenthesizedWhitespace]:
whitespace = original_node.value.replace("\\", "")
if "... | LineBreakTransformer |
python | euske__pdfminer | pdfminer/pdffont.py | {
"start": 20869,
"end": 22215
} | class ____(PDFSimpleFont):
def __init__(self, rsrcmgr, spec):
try:
self.basefont = literal_name(spec['BaseFont'])
except KeyError:
if STRICT:
raise PDFFontError('BaseFont is missing')
self.basefont = 'unknown'
try:
(descriptor,... | PDFType1Font |
python | numba__numba | numba/tests/test_func_lifetime.py | {
"start": 3931,
"end": 4908
} | class ____(TestCase):
def test_double_free(self):
from numba import njit
import numpy as np
# This is the function that causes the crash
@njit
def is_point_in_polygons(point, polygons):
num_polygons = polygons.shape[0]
if num_polygons != 0:
... | TestLifeTimeIssue |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 1163,
"end": 1229
} | class ____(models.Model):
customish = CustomishField()
| Customish |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 827963,
"end": 828685
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Package."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PackageEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.... | PackageConnection |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/transaction.py | {
"start": 923,
"end": 1053
} | class ____(BaseModel):
billing_period_end_date: Optional[date]
billing_period_start_date: Optional[date]
| SubscriptionDetails |
python | getsentry__sentry | src/sentry/integrations/github/webhook.py | {
"start": 12387,
"end": 20811
} | class ____(GitHubWebhook):
"""https://developer.github.com/v3/activity/events/types/#pushevent"""
@property
def event_type(self) -> IntegrationWebhookEventType:
return IntegrationWebhookEventType.PUSH
def should_ignore_commit(self, commit: Mapping[str, Any]) -> bool:
return GitHubRepos... | PushEventWebhook |
python | getsentry__sentry | src/sentry/conduit/endpoints/organization_conduit_demo.py | {
"start": 608,
"end": 780
} | class ____(serializers.Serializer):
token = serializers.CharField()
channel_id = serializers.UUIDField()
url = serializers.URLField()
| ConduitCredentialsSerializer |
python | huggingface__transformers | src/transformers/models/janus/configuration_janus.py | {
"start": 1333,
"end": 5678
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`JanusVisionModel`]. It is used to instantiate a
`JanusVisionModel` according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can ... | JanusVisionConfig |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 40018,
"end": 56879
} | class ____(WebTestCase):
# The expected SHA-512 hash of robots.txt, used in tests that call
# StaticFileHandler.get_version
robots_txt_hash = (
b"63a36e950e134b5217e33c763e88840c10a07d80e6057d92b9ac97508de7fb1f"
b"a6f0e9b7531e169657165ea764e8963399cb6d921ffe6078425aaafe54c04563"
)
st... | StaticFileTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramType1.py | {
"start": 1227,
"end": 1295
} | class ____(type):
def m1(self: type[_T]) -> Iterator[_T]: ...
| MyMeta |
python | kubernetes-client__python | kubernetes/base/config/kube_config.py | {
"start": 23659,
"end": 25970
} | class ____(object):
"""Remembers each config key's path and construct a relevant exception
message in case of missing keys. The assumption is all access keys are
present in a well-formed kube-config."""
def __init__(self, name, value, path=None):
self.name = name
self.value = value
... | ConfigNode |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_except.py | {
"start": 399,
"end": 1383
} | class ____(Executor):
@requests
def foo(self, **kwargs):
raise NotImplementedError
@pytest.mark.parametrize('protocol', ['http', 'grpc', 'websocket'])
def test_bad_flow(mocker, protocol):
def validate(req):
bad_routes = [
r for r in req.routes if r.status.code == jina_pb2.Statu... | BadExecutor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with1.py | {
"start": 141,
"end": 345
} | class ____(object):
def __exit__(
self,
t: Optional[type] = None,
exc: Optional[BaseException] = None,
tb: Optional[Any] = None,
) -> bool:
return True
| Class1 |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_use_orig_params.py | {
"start": 47344,
"end": 54739
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(2)
def test_no_sync_correctness(self):
"""
Tests a basic ``no_sync()`` setup by comparing ``use_orig_params=True``
against ``use_orig_params=False``.
"""
self.run_subt... | TestFSDPUseOrigParamsNoSync |
python | spack__spack | lib/spack/spack/build_environment.py | {
"start": 5268,
"end": 9197
} | class ____(Executable):
"""Special callable executable object for make so the user can specify parallelism options
on a per-invocation basis.
"""
def __init__(self, name: str, *, jobs: int, supports_jobserver: bool = True) -> None:
super().__init__(name)
self.supports_jobserver = suppor... | MakeExecutable |
python | ansible__ansible | test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/vyos.py | {
"start": 240,
"end": 446
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'vyos'
return result
| ActionModule |
python | PrefectHQ__prefect | tests/test_task_engine.py | {
"start": 99276,
"end": 103936
} | class ____:
async def test_task_transitions_to_rolled_back_on_transaction_rollback(
self,
events_pipeline,
prefect_client,
):
task_run_state = None
@task
def foo():
pass
@foo.on_rollback
def rollback(txn):
pass
@f... | TestTransactionHooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.