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
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 8991, "end": 9198 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("FAILURE", "PENDING", "SUCCESS")
EnterpriseServerUserAccountsUploadSyncState
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_select.py
{ "start": 64104, "end": 65806 }
class ____(fixtures.TablesTest): __backend__ = True run_inserts = run_deletes = "once" inserted_data = [{"a": i, "b": i + 1} for i in range(10)] @classmethod def define_tables(cls, metadata): Table("bitwise", metadata, Column("a", Integer), Column("b", Integer)) @classmethod def i...
BitwiseTest
python
kubernetes-client__python
kubernetes/client/models/v1beta2_resource_claim.py
{ "start": 383, "end": 7590 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1beta2ResourceClaim
python
pytorch__pytorch
torchgen/api/autograd.py
{ "start": 1191, "end": 2153 }
class ____: # The formula string (legit C++ expression). # Note that expressions against input arguments have been replaced with the # corresponding saved attributes. # E.g.: # raw formula: `mul_tensor_backward(grad, self, other.scalar_type())` # here: `mul_tensor_backward(grad, self, o...
Derivative
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict3.py
{ "start": 179, "end": 1024 }
class ____(Movie, total=True): based_on: str movie1 = Movie(year=1982, name="Blade Runner") # This should generate an error because # the type is incorrect. movie2 = Movie(name="Blade Runner", year="1982") movie3 = Movie(name="Blade Runner") # This should generate an error because # the key name is not support...
BookBasedMovie
python
jazzband__django-oauth-toolkit
tests/test_django_checks.py
{ "start": 213, "end": 829 }
class ____(TestCase): def test_checks_pass(self): call_command("check") # CrossDatabaseRouter claims AccessToken is in beta while everything else is in alpha. # This will cause the database checks to fail. @override_settings( DATABASE_ROUTERS=["tests.db_router.CrossDatabaseRouter", "tes...
DjangoChecksTestCase
python
pytorch__pytorch
test/onnx/test_onnxscript_no_runtime.py
{ "start": 306, "end": 6410 }
class ____(common_utils.TestCase): # opset version is # 1. local function is supported after opset 15 # 2. onnx-script requires users to determine opset in local function opset_version = 15 def test_onnxscript_registration_with_multiple_models(self): from onnxscript.onnx_opset import opset1...
TestONNXScriptExport
python
huggingface__transformers
tests/models/layoutlmv2/test_processing_layoutlmv2.py
{ "start": 1328, "end": 5701 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = LayoutLMv2Processor @classmethod def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class( do_resize=True, s...
LayoutLMv2ProcessorTest
python
getsentry__sentry
src/sentry/integrations/api/endpoints/external_team_details.py
{ "start": 1119, "end": 3937 }
class ____(TeamEndpoint, ExternalActorEndpointMixin): publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } owner = ApiOwner.ENTERPRISE def convert_args( self, request: Request, organization_id_or_slug: int | str, team_id...
ExternalTeamDetailsEndpoint
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_bulk_operations.py
{ "start": 17966, "end": 22134 }
class ____(BulkTest): class DeleteBookResource(resources.ModelResource): def for_delete(self, row, instance): return True class Meta: model = Book use_bulk = True # there are errors when diffing with mocks # therefore disable diff with thi...
BulkDeleteTest
python
doocs__leetcode
solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/Solution.py
{ "start": 0, "end": 821 }
class ____: def magnificentSets(self, n: int, edges: List[List[int]]) -> int: g = [[] for _ in range(n)] for a, b in edges: g[a - 1].append(b - 1) g[b - 1].append(a - 1) d = defaultdict(int) for i in range(n): q = deque([i]) dist = [0] ...
Solution
python
ray-project__ray
python/ray/train/tests/test_torch_predictor.py
{ "start": 417, "end": 521 }
class ____(torch.nn.Module): def forward(self, input): return input * 2
DummyModelSingleTensor
python
getsentry__sentry
src/sentry/similarity/backends/redis.py
{ "start": 466, "end": 7589 }
class ____(AbstractIndexBackend): def __init__( self, cluster, namespace, signature_builder, bands, interval, retention, candidate_set_limit ): self.cluster = cluster self.namespace = namespace self.signature_builder = signature_builder self.bands = bands self.int...
RedisScriptMinHashIndexBackend
python
google__jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
{ "start": 7045, "end": 8530 }
class ____(nn.Module): """A simple Multilayer perceptron with 1 hidden layer. Attributes: hidden_size: The size of the hidden layer. output_size: The size of the output. activation: The activation function to apply to the hidden layer. dropout_rate: The dropout rate applied to the hidden layer. ...
MLP
python
euske__pdfminer
pdfminer/pdffont.py
{ "start": 2267, "end": 2413 }
class ____: @classmethod def get_metrics(klass, fontname): return FONT_METRICS[fontname] ## Type1FontHeaderParser ##
FontMetricsDB
python
ijl__orjson
test/test_enum.py
{ "start": 592, "end": 773 }
class ____(enum.Enum): A = "a" B = 1 C = FloatEnum.ONE D = {"d": IntEnum.ONE} # noqa: RUF012 E = Custom("c") F = datetime.datetime(1970, 1, 1)
UnspecifiedEnum
python
doocs__leetcode
solution/2100-2199/2179.Count Good Triplets in an Array/Solution.py
{ "start": 449, "end": 889 }
class ____: def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int: pos = {v: i for i, v in enumerate(nums2, 1)} ans = 0 n = len(nums1) tree = BinaryIndexedTree(n) for num in nums1: p = pos[num] left = tree.query(p) right = n - p...
Solution
python
fluentpython__example-code-2e
06-obj-ref/bus.py
{ "start": 284, "end": 609 }
class ____: def __init__(self, passengers=None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name) # end::BUS_CL...
Bus
python
wandb__wandb
wandb/automations/_generated/fragments.py
{ "start": 1713, "end": 1879 }
class ____(GQLResult): typename__: Typename[Literal["NoOpTriggeredAction"]] = "NoOpTriggeredAction" no_op: Optional[bool] = Field(alias="noOp")
NoOpActionFields
python
getsentry__sentry
tests/sentry/api/test_paginator.py
{ "start": 34659, "end": 36469 }
class ____(APITestCase, SnubaTestCase): cls = CallbackPaginator def setUp(self) -> None: super().setUp() self.now = timezone.now() self.project.date_added = self.now - timedelta(minutes=5) for i in range(8): self.store_event( project_id=self.project.i...
CallbackPaginatorTest
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 10353, "end": 10491 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): include_text: Optional[bool] = None @dataclasses.dataclass(frozen=True)
SaveOptions
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 66938, "end": 66998 }
class ____(BasePlugin[_FakePluginConfig]): pass
FakePlugin
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 97657, "end": 98792 }
class ____(Response): """ Response of models.make_public endpoint. :param updated: Number of models updated :type updated: int """ _service = "models" _action = "make_public" _version = "2.13" _schema = { "definitions": {}, "properties": { "updated": { ...
MakePublicResponse
python
pypa__warehouse
tests/unit/manage/test_views.py
{ "start": 187256, "end": 210727 }
class ____: @pytest.fixture def organization(self, _enable_organizations, pyramid_user): organization = OrganizationFactory.create() OrganizationRoleFactory.create( organization=organization, user=pyramid_user, role_name=OrganizationRoleType.Owner, ) ...
TestManageProjectRoles
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/optimization/filter_parallelization_test.py
{ "start": 9418, "end": 12004 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def enableFilterParallelization(self, dataset): options = options_lib.Options() options.experimental_optimization.filter_parallelization = True return dataset.with_options(options) def _build_filter...
FilterCheckpointTest
python
huggingface__transformers
src/transformers/models/lxmert/modeling_lxmert.py
{ "start": 27747, "end": 28247 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.transform = LxmertPredictionHeadTransform(config) self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) def forward(self, hid...
LxmertLMPredictionHead
python
ray-project__ray
python/ray/tune/progress_reporter.py
{ "start": 23918, "end": 47467 }
class ____(TuneReporterBase): """Command-line reporter Args: metric_columns: Names of metrics to include in progress table. If this is a dict, the keys should be metric names and the values should be the displayed names. If this is a list, the metric name is used dir...
CLIReporter
python
pytorch__pytorch
benchmarks/functional_autograd_benchmark/torchaudio_models.py
{ "start": 8593, "end": 12789 }
class ____(nn.Module): def __init__( self, rnn_type, labels, rnn_hidden_size, nb_layers, audio_conf, bidirectional, context=20, ): super().__init__() self.hidden_size = rnn_hidden_size self.hidden_layers = nb_layers ...
DeepSpeech
python
apache__airflow
helm-tests/tests/helm_tests/airflow_aux/test_create_user_job.py
{ "start": 914, "end": 17339 }
class ____: """Tests create user job.""" def test_should_run_by_default(self): docs = render_chart(show_only=["templates/jobs/create-user-job.yaml"]) assert docs[0]["kind"] == "Job" assert jmespath.search("spec.template.spec.containers[0].name", docs[0]) == "create-user" assert ...
TestCreateUserJob
python
huggingface__transformers
src/transformers/utils/import_utils.py
{ "start": 59020, "end": 59608 }
class ____(type): """ Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by `requires_backend` each time a user tries to access any method of that class. """ is_dummy = True def __getattribute__(cls, key): if (key.startswith("_") and key...
DummyObject
python
streamlit__streamlit
lib/tests/streamlit/runtime/caching/cache_resource_api_test.py
{ "start": 7899, "end": 9969 }
class ____(unittest.TestCase): def setUp(self) -> None: # Caching functions rely on an active script run ctx add_script_run_ctx(threading.current_thread(), create_mock_script_run_ctx()) def tearDown(self): st.cache_resource.clear() # Some of these tests reach directly into _cach...
CacheResourceValidateTest
python
modin-project__modin
modin/core/execution/ray/common/deferred_execution.py
{ "start": 19659, "end": 28258 }
class ____: """Remote functions for DeferredExecution.""" @staticmethod def exec_func(fn: Callable, obj: Any, args: Tuple, kwargs: Dict) -> Any: """ Execute the specified function. Parameters ---------- fn : Callable obj : Any args : Tuple kw...
_RemoteExecutor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI013.py
{ "start": 101, "end": 143 }
class ____: ... ...
TwoEllipsesClass
python
redis__redis-py
redis/commands/search/reducers.py
{ "start": 2592, "end": 3775 }
class ____(Reducer): """ Selects the first value within the group according to sorting parameters """ NAME = "FIRST_VALUE" def __init__(self, field: str, *byfields: Union[Asc, Desc]) -> None: """ Selects the first value of the given field within the group. ### Parameter ...
first_value
python
django__django
tests/indexes/models.py
{ "start": 1282, "end": 1563 }
class ____(models.Model): headline = models.CharField(max_length=100, db_index=True) body = models.TextField(db_index=True) slug = models.CharField(max_length=40, unique=True) class Meta: required_db_features = {"supports_index_on_text_field"}
IndexedArticle
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints-frameworks-v2/iata/main.py
{ "start": 1023, "end": 1272 }
class ____(messages.Message): iata = messages.StringField(1, required=True) name = messages.StringField(2, required=True) IATA_AIRPORT_RESOURCE = endpoints.ResourceContainer( Airport, iata=messages.StringField(1, required=True) )
Airport
python
milvus-io__pymilvus
pymilvus/client/search_result.py
{ "start": 22418, "end": 25757 }
class ____(list): """List[Dict] Topk search result with pks, distances, and output fields. [ {"id": 1, "distance": 0.3, "entity": {"vector": [1, 2, 3]}}, {"id": 2, "distance": 0.2, "entity": {"vector": [4, 5, 6]}}, {"id": 3, "distance": 0.1, "entity": {"vector": [7, 8, 9...
Hits
python
simonw__datasette
datasette/views/special.py
{ "start": 12329, "end": 18302 }
class ____(BaseView): name = "permission_rules" has_json_alternate = False async def get(self, request): await self.ds.ensure_permission(action="view-instance", actor=request.actor) await self.ds.ensure_permission(action="permissions-debug", actor=request.actor) # Check if this is ...
PermissionRulesView
python
sphinx-doc__sphinx
sphinx/roles.py
{ "start": 1176, "end": 6340 }
class ____(ReferenceRole): """A generic cross-referencing role. To create a callable that can be used as a role function, create an instance of this class. The general features of this role are: * Automatic creation of a reference and a content node. * Optional separation of title and target with...
XRefRole
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 19218, "end": 20174 }
class ____(MaskedArraySetup): @pytest.mark.parametrize("n,axis", [(1, -1), (2, -1), (1, 0)]) def test_diff(self, n, axis): mda = np.diff(self.ma, n=n, axis=axis) expected_data = np.diff(self.a, n, axis) nan_mask = np.zeros_like(self.a) nan_mask[self.ma.mask] = np.nan expe...
TestMaskedArrayCalculation
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 49573, "end": 52499 }
class ____(FunnelPreTrainedModel): def __init__(self, config: FunnelConfig) -> None: super().__init__(config) self.funnel = FunnelBaseModel(config) self.classifier = FunnelClassificationHead(config, 1) # Initialize weights and apply final processing self.post_init() @au...
FunnelForMultipleChoice
python
huggingface__transformers
src/transformers/models/olmo2/modular_olmo2.py
{ "start": 9233, "end": 9609 }
class ____(OlmoRotaryEmbedding): pass def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) # Olmo2 attention is identical to OLMo attention except: # - Norm is applied to attention...
Olmo2RotaryEmbedding
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/conv2d_test.py
{ "start": 4663, "end": 5935 }
class ____(trt_test.TfTrtIntegrationTestBase): """Testing conversion of strided Conv2D (data_format=NCHW).""" def GraphFn(self, inp): np.random.seed(1234) num_filters = 5 output = inp output = conv2d_layer( output, num_filters, (3, 2), strides=(2, 2), padding="same",...
Conv2DStridedNCHWTest
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 184540, "end": 188778 }
class ____(test_util.TensorFlowTestCase): def testExisting(self): # Read some real PNGs, converting to different channel numbers prefix = "tensorflow/core/lib/png/testdata/" inputs = ((1, "lena_gray.png"), (4, "lena_rgba.png"), (3, "lena_palette.png"), (4, "lena_palette_trns.png")) for ...
PngTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1122219, "end": 1122596 }
class ____(sgqlc.types.Type, Contribution): """Represents the contribution a user made on GitHub by creating a repository. """ __schema__ = github_schema __field_names__ = ("repository",) repository = sgqlc.types.Field(sgqlc.types.non_null("Repository"), graphql_name="repository") """The re...
CreatedRepositoryContribution
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 2167, "end": 2386 }
class ____(JobFacet): failed: bool = field(default=False) FINISHED_FACETS: dict[str, JobFacet] = {"complete": CompleteRunFacet(True)} FAILED_FACETS: dict[str, JobFacet] = {"failure": FailRunFacet(True)}
FailRunFacet
python
dagster-io__dagster
python_modules/dagster/dagster/components/core/defs_module.py
{ "start": 7429, "end": 14061 }
class ____(Component): """A component that represents a directory containing multiple Dagster definition modules. DefsFolderComponent serves as a container for organizing and managing multiple subcomponents within a folder structure. It automatically discovers and loads components from subdirectories a...
DefsFolderComponent
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/models/anonymous_user.py
{ "start": 971, "end": 1947 }
class ____(AnonymousUserMixin, BaseUser): """User object used when no active user is logged in.""" _roles: set[tuple[str, str]] = set() _perms: set[tuple[str, str]] = set() first_name = "Anonymous" last_name = "" @property def roles(self): if not self._roles: public_ro...
AnonymousUser
python
django__django
tests/transactions/models.py
{ "start": 286, "end": 602 }
class ____(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Meta: ordering = ("first_name", "last_name") def __str__(self): return ("%s %s" % (self.first_name, self.last_name)).strip()
Reporter
python
openai__openai-python
src/openai/types/static_file_chunking_strategy_object_param.py
{ "start": 319, "end": 508 }
class ____(TypedDict, total=False): static: Required[StaticFileChunkingStrategyParam] type: Required[Literal["static"]] """Always `static`."""
StaticFileChunkingStrategyObjectParam
python
facebookresearch__faiss
tests/test_io.py
{ "start": 1399, "end": 6372 }
class ____(unittest.TestCase): def do_write_callback(self, bsz): d, n = 32, 1000 x = np.random.uniform(size=(n, d)).astype('float32') index = faiss.IndexFlatL2(d) index.add(x) f = io.BytesIO() # test with small block size writer = faiss.PyCallbackIOWriter(f....
TestCallbacks
python
getsentry__sentry
tests/sentry/preprod/api/endpoints/pull_request/test_organization_pullrequest_details.py
{ "start": 431, "end": 10360 }
class ____(TestCase): def setUp(self): super().setUp() self.factory = APIRequestFactory() self.integration = self.create_integration( organization=self.organization, provider="github", name="Test GitHub Integration", external_id="12345", ...
OrganizationPullRequestDetailsEndpointTest
python
django__django
tests/model_inheritance_regress/models.py
{ "start": 1821, "end": 1897 }
class ____(SelfRefParent): child_data = models.IntegerField()
SelfRefChild
python
numba__numba
numba/core/types/containers.py
{ "start": 13055, "end": 14474 }
class ____(Literal, ConstSized, Hashable): """A heterogeneous immutable list (basically a tuple with list semantics). """ mutable = False def __init__(self, literal_value): self.is_types_iterable(literal_value) self._literal_init(list(literal_value)) self.types = tuple(literal_...
LiteralList
python
FactoryBoy__factory_boy
tests/test_transformer.py
{ "start": 5650, "end": 6012 }
class ____(factory.Factory): class Meta: model = TestObject class Params: upper_two = factory.Trait( two=factory.Transformer("two", transform=str.upper) ) odds = factory.Trait( one="one", three="three", ) one = factory.Transformer(...
WithTraitFactory
python
jazzband__django-pipeline
tests/tests/test_forms.py
{ "start": 1169, "end": 6785 }
class ____(TestCase): """Unit tests for pipeline.forms.PipelineFormMedia.""" @pipeline_settings(PIPELINE_ENABLED=True) def test_css_packages_with_pipeline_enabled(self): """Testing PipelineFormMedia.css_packages with PIPELINE_ENABLED=True""" class MyMedia(PipelineFormMedia): cs...
PipelineFormMediaTests
python
doocs__leetcode
solution/0700-0799/0701.Insert into a Binary Search Tree/Solution.py
{ "start": 192, "end": 534 }
class ____: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return TreeNode(val) if root.val > val: root.left = self.insertIntoBST(root.left, val) else: root.right = self.insertIntoBST(root.right, val) ...
Solution
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 16484, "end": 22415 }
class ____(TimeSeriesBaseModel, ObjectBaseModel): name: str = Field( default_factory=lambda: generate_slug(2), description=( "The name of the flow run. Defaults to a random slug if not specified." ), examples=["my-flow-run"], ) flow_id: UUID = Field(default=..., d...
FlowRun
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 50067, "end": 53832 }
class ____(Fittable2DModel): """ Two-dimensional Lorentzian model. Parameters ---------- amplitude : float or `~astropy.units.Quantity`. Peak value. x_0 : float or `~astropy.units.Quantity`. Position of the peak in x. y_0 : float or `~astropy.units.Quantity`. Positio...
Lorentz2D
python
ray-project__ray
rllib/env/vector/vector_multi_agent_env.py
{ "start": 264, "end": 2910 }
class ____: metadata: Dict[str, Any] = {} spec: Optional[EnvSpec] = None render_mode: Optional[str] = None closed: bool = False envs: Optional[List] = None # TODO (simon, sven): We could think about enabling here different # spaces for different envs (e.g. different high/lows). In this ...
VectorMultiAgentEnv
python
getsentry__sentry
src/sentry/migrations/0001_squashed_0904_onboarding_task_project_id_idx.py
{ "start": 2032, "end": 383721 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/shell_tool.py
{ "start": 10488, "end": 11353 }
class ____(BaseModel): """Input schema for the persistent shell tool.""" command: str | None = None """The shell command to execute.""" restart: bool | None = None """Whether to restart the shell session.""" runtime: Annotated[Any, SkipJsonSchema()] = None """The runtime for the shell too...
_ShellToolInput
python
kamyu104__LeetCode-Solutions
Python/minimum-area-rectangle.py
{ "start": 90, "end": 992 }
class ____(object): def minAreaRect(self, points): """ :type points: List[List[int]] :rtype: int """ nx = len(set(x for x, y in points)) ny = len(set(y for x, y in points)) p = collections.defaultdict(list) if nx > ny: for x, y in points: ...
Solution
python
facebook__pyre-check
client/language_server/tests/connections_test.py
{ "start": 432, "end": 736 }
class ____(socketserver.StreamRequestHandler): def handle(self) -> None: try: while True: data = self.rfile.readline() self.wfile.write(data) self.wfile.flush() except BrokenPipeError: pass
EchoServerRequestHandler
python
huggingface__transformers
src/transformers/models/bridgetower/modeling_bridgetower.py
{ "start": 64569, "end": 65249 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.h...
BridgeTowerPredictionHeadTransform
python
tensorflow__tensorflow
tensorflow/compiler/tests/cast_ops_test.py
{ "start": 1226, "end": 2112 }
class ____(xla_test.XLATestCase): def testBitcastToLarger(self): with ops.device('device:{}:0'.format(self.device)): def f(x): t = array_ops.bitcast(x, dtypes.float32) return math_ops.reduce_sum(t, axis=1) compiled_f = def_function.function(f, jit_compile=True) x = random_ops...
CastOpsTest
python
apache__airflow
providers/google/tests/unit/google/firebase/hooks/test_firestore.py
{ "start": 1683, "end": 5654 }
class ____: hook: CloudFirestoreHook | None = None def setup_method(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = CloudFirestoreHook(gcp_conn_id="...
TestCloudFirestoreHookWithPassedProjectId
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v1.py
{ "start": 26784, "end": 29827 }
class ____(Optimizer, trackable.Trackable): """Wrapper class for native TensorFlow optimizers.""" def __init__(self, optimizer, iterations=None): # pylint: disable=super-init-not-called self.optimizer = optimizer self._track_trackable(optimizer, name='optimizer') if iterations is None: with back...
TFOptimizer
python
walkccc__LeetCode
solutions/2291. Maximum Profit From Trading Stocks/2291.py
{ "start": 0, "end": 574 }
class ____: def maximumProfit( self, present: list[int], future: list[int], budget: int, ) -> int: n = len(present) # dp[i][j] := the maximum profit of buying present[0..i) with j budget dp = [[0] * (budget + 1) for _ in range(n + 1)] for i in range(1, n + 1): profit =...
Solution
python
numba__llvmlite
llvmlite/ir/instructions.py
{ "start": 14274, "end": 14715 }
class ____(Instruction): def __init__(self, parent, op, val, typ, name=''): super(CastInstr, self).__init__(parent, typ, op, [val], name=name) def descr(self, buf): buf.append("{0} {1} {2} to {3} {4}\n".format( self.opname, self.operands[0].type, self.operand...
CastInstr
python
django-import-export__django-import-export
import_export/widgets.py
{ "start": 7818, "end": 10079 }
class ____(Widget): """ Widget for converting boolean fields. The widget assumes that ``True``, ``False``, and ``None`` are all valid values, as to match Django's `BooleanField <https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield>`_. That said, whether the database/Django will...
BooleanWidget
python
spack__spack
lib/spack/spack/subprocess_context.py
{ "start": 3306, "end": 3998 }
class ____: """Class to serialize and restore global state for child processes. Spack may modify state that is normally read from disk or command line in memory; this object is responsible for properly serializing that state to be applied to a subprocess. """ def __init__(self): self.confi...
GlobalStateMarshaler
python
coleifer__peewee
tests/signals.py
{ "start": 169, "end": 226 }
class ____(BaseSignalModel): a = TextField(default='')
A
python
PrefectHQ__prefect
tests/_internal/compatibility/test_async_dispatch.py
{ "start": 8685, "end": 10406 }
class ____: """Test that async_dispatch adds the .aio attribute for compatibility.""" def test_async_dispatch_adds_aio_attribute(self): """Test that the decorator adds an .aio attribute pointing to async implementation.""" async def async_impl(x: int) -> str: return f"async {x}" ...
TestAioAttribute
python
django__django
django/forms/fields.py
{ "start": 18219, "end": 19459 }
class ____(BaseTemporalField): widget = DateTimeInput input_formats = DateTimeFormatsIterator() default_error_messages = { "invalid": _("Enter a valid date/time."), } def prepare_value(self, value): if isinstance(value, datetime.datetime): value = to_current_timezone(val...
DateTimeField
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py
{ "start": 1629, "end": 4979 }
class ____(FilesRESTMixin, JupyterHandler): auth_resource = "spyder-services" def get_path_argument(self, name: str) -> str: """Get the path argument from the request. Args ---- name (str): Name of the argument to get. Returns ------- str: The p...
BaseFSHandler
python
bokeh__bokeh
src/bokeh/embed/util.py
{ "start": 7585, "end": 8353 }
class ____: """ Encapsulate data needed for embedding a Bokeh document root. Values for ``name`` or ``tags`` are optional. They may be useful for querying a collection of roots to find a specific one to embed. """ #: A unique ID to use for the DOM element elementid: ID #: The Bokeh model...
RenderRoot
python
davidhalter__jedi
jedi/plugins/django.py
{ "start": 9972, "end": 10289 }
class ____(BaseTreeParamName): def __init__(self, field_name): super().__init__(field_name.parent_context, field_name.tree_name) self._field_name = field_name def get_kind(self): return Parameter.KEYWORD_ONLY def infer(self): return self._field_name.infer()
DjangoParamName
python
doocs__leetcode
solution/2500-2599/2516.Take K of Each Character From Left and Right/Solution.py
{ "start": 0, "end": 383 }
class ____: def takeCharacters(self, s: str, k: int) -> int: cnt = Counter(s) if any(cnt[c] < k for c in "abc"): return -1 mx = j = 0 for i, c in enumerate(s): cnt[c] -= 1 while cnt[c] < k: cnt[s[j]] += 1 j += 1 ...
Solution
python
gevent__gevent
benchmarks/bench_spawn.py
{ "start": 611, "end": 5929 }
class ____(object): def __init__(self, spawn_duration, sleep_duration=-1, join_duration=-1): self.spawn_duration = spawn_duration self.sleep_duration = sleep_duration self.join_duration = join_duration def _test(spawn, sleep, options): ...
Times
python
numpy__numpy
tools/c_coverage/c_coverage_report.py
{ "start": 599, "end": 1393 }
class ____(HtmlFormatter): """Custom HTML formatter to insert extra information with the lines.""" def __init__(self, lines, **kwargs): HtmlFormatter.__init__(self, **kwargs) self.lines = lines def wrap(self, source, outfile): for i, (c, t) in enumerate(HtmlFormatter.wrap(self, sour...
FunctionHtmlFormatter
python
spack__spack
lib/spack/spack/test/config.py
{ "start": 11188, "end": 64372 }
class ____: def __init__(self, path): self.path = path def test_substitute_config_variables(mock_low_high_config, monkeypatch): prefix = spack.paths.prefix.lstrip("/") assert cross_plat_join( os.sep + os.path.join("foo", "bar", "baz"), prefix ) == spack_path.canonicalize_path("/foo/bar...
MockEnv
python
TheAlgorithms__Python
data_structures/queues/linked_queue.py
{ "start": 148, "end": 334 }
class ____: def __init__(self, data: Any) -> None: self.data: Any = data self.next: Node | None = None def __str__(self) -> str: return f"{self.data}"
Node
python
PrefectHQ__prefect
src/integrations/prefect-ray/prefect_ray/task_runners.py
{ "start": 2449, "end": 4323 }
class ____(PrefectWrappedFuture[R, "ray.ObjectRef"]): def wait(self, timeout: float | None = None) -> None: try: result = ray.get(self.wrapped_future, timeout=timeout) except ray.exceptions.GetTimeoutError: return except Exception as exc: result = run_coro...
PrefectRayFuture
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/overload.py
{ "start": 352, "end": 667 }
class ____: """docstring""" @overload def sum(self, x: int, y: int = 0) -> int: ... @overload def sum(self, x: float, y: float = 0.0) -> float: ... @overload def sum(self, x: str, y: str = ...) -> str: ... def sum(self, x, y=None): """docstring""" return x + y
Math
python
mlflow__mlflow
mlflow/genai/git_versioning/__init__.py
{ "start": 400, "end": 5360 }
class ____: def __init__(self, remote_name: str = "origin") -> None: try: self.info = GitInfo.from_env(remote_name=remote_name) except GitOperationError as e: _logger.warning( f"Encountered an error while retrieving git information: {e}. " f"Gi...
GitContext
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/autoVariance5.py
{ "start": 522, "end": 611 }
class ____(Generic[T]): @deco def select_all(self, *args: object) -> list[Any]: ...
A
python
mlflow__mlflow
tests/projects/test_projects.py
{ "start": 16325, "end": 19290 }
class ____: def __init__(self, prefix): self.prefix = prefix def __eq__(self, other): return isinstance(other, str) and other.startswith(self.prefix) def test_parse_kubernetes_config_without_context(mock_kubernetes_job_template): with mock.patch("mlflow.projects._logger.debug") as mock_de...
StartsWithMatcher
python
ray-project__ray
rllib/examples/_old_api_stack/models/parametric_actions_model.py
{ "start": 532, "end": 2516 }
class ____(DistributionalQTFModel): """Parametric action model that handles the dot product and masking. This assumes the outputs are logits for a single Categorical action dist. Getting this to work with a more complex output (e.g., if the action space is a tuple of several distributions) is also poss...
ParametricActionsModel
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 8958, "end": 9593 }
class ____: param_names = ["shapes", "how", "axis", "ignore_index"] params = [ get_benchmark_shapes("TimeConcat"), ["inner", "outer"], [0, 1], [True, False], ] def setup(self, shapes, how, axis, ignore_index): self.df1 = generate_dataframe("int", *shapes[0], RAND...
TimeConcat
python
dagster-io__dagster
python_modules/dagster/dagster_tests/core_tests/test_user_code_boundary.py
{ "start": 23, "end": 1451 }
class ____(Exception): def __init__(self): super().__init__("The user has errored") def test_user_error_boundary_op_compute(): @dg.op def throws_user_error(_): raise UserError() @dg.job def job_def(): throws_user_error() result = job_def.execute_in_process(raise_on_er...
UserError
python
tensorflow__tensorflow
tensorflow/python/ops/tensor_array_ops.py
{ "start": 15973, "end": 25904 }
class ____: """Graph-mode implementation of TensorArray backed by TensorLists. The backing tensor of this TensorArray is a TensorList variant tensor which is stored in the `flow`. The `handle` is always none here. The reason we use the `flow` field and not the `handle` field is to ensure backwards compatibilit...
_GraphTensorArrayV2
python
pypa__hatch
src/hatch/python/resolve.py
{ "start": 1153, "end": 2960 }
class ____(ABC): def __init__(self, name: str, source: str) -> None: self.__name = name self.__source = source @property def name(self) -> str: return self.__name @cached_property def source(self) -> str: return self.__source if (custom_source := get_custom_source(s...
Distribution
python
numpy__numpy
tools/swig/test/testSuperTensor.py
{ "start": 13622, "end": 13937 }
class ____(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" #self.result = int(self.result) ######################################################################
uintTestCase
python
cython__cython
tests/run/ext_auto_richcmp.py
{ "start": 2636, "end": 4301 }
class ____(ClassEqNe): """ >>> a = ClassEqNeGe(1) >>> b = ClassEqNeGe(2) >>> c = ClassEqNeGe(1) >>> a == a True >>> a != a False >>> a >= a True >>> a <= a True >>> a == b False >>> a != b True >>> a >= b False >>> b <= a False >>> a ...
ClassEqNeGe
python
huggingface__transformers
src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py
{ "start": 13300, "end": 14049 }
class ____(nn.Module): def __init__( self, in_channels=1, out_channels=384, kernel_size=1, padding=0, dropout_rate=0.0, ): super().__init__() self.conv = nn.Conv1d( in_channels=in_channels, out_channels=out_channels, ...
FastSpeech2ConformerVarianceEmbedding
python
django__django
tests/test_utils/test_testcase.py
{ "start": 3327, "end": 5796 }
class ____(TestCase): # setUpTestData re-assignment are also wrapped in TestData. jim_douglas = None @classmethod def setUpTestData(cls): cls.jim_douglas = Person.objects.create(name="Jim Douglas") cls.car = Car.objects.create(name="1963 Volkswagen Beetle") cls.herbie = cls.jim_...
TestDataTests
python
virgili0__Virgilio
Tools/regex-bin/regexPrinter.py
{ "start": 3161, "end": 4450 }
class ____(TreeNode): def __init__(self, token, value): TreeNode.__init__(self, token, value, None) def get_printer(self, values): if self.token == Token.QUESTION: temp = [""] + [v for v in values] ss = sorted(temp) elif self.token in (Token.TIMES, Token.PLUS): ...
QuantifierNode
python
walkccc__LeetCode
solutions/2608. Shortest Cycle in a Graph/2608.py
{ "start": 0, "end": 806 }
class ____: def findShortestCycle(self, n: int, edges: list[list[int]]) -> int: INF = 1001 ans = INF graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) def bfs(i: int) -> int: """Returns the length of the minimum cycle by starting BFS from n...
Solution
python
openai__openai-python
src/openai/types/conversations/conversation.py
{ "start": 189, "end": 886 }
class ____(BaseModel): id: str """The unique ID of the conversation.""" created_at: int """ The time at which the conversation was created, measured in seconds since the Unix epoch. """ metadata: object """Set of 16 key-value pairs that can be attached to an object. This can b...
Conversation