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
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 6975, "end": 7462 }
class ____(serializers.Serializer): id = serializers.SlugField() header = serializers.CharField(source="get_rendered_header") body = serializers.CharField(source="get_rendered_body") type = serializers.CharField() icon_classes = serializers.CharField(source="get_display_icon_classes") class Met...
NotificationMessageSerializer
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tfr/python/op_reg_gen.py
{ "start": 4219, "end": 5076 }
class ____(transpiler.GenericTranspiler): """Transforms Python objects into TFR MLIR source code.""" def transform_ast(self, node, ctx): gen = OpRegGenImpl(ctx) gen.visit(node) return gen.code_buffer def op_reg_gen(func): """Parse a function and emit the TFR functions.""" op_reg_code, _ = OpRegGe...
OpRegGen
python
pyodide__pyodide
src/py/_pyodide/_core_docs.py
{ "start": 23845, "end": 27484 }
class ____(JsIterable[T_co], Generic[T_co, T_contra, V_co]): """A JavaScript generator A JavaScript object is treated as a generator if its :js:data:`Symbol.toStringTag` is ``"Generator"``. Most likely this will be because it is a true :js:class:`Generator` produced by the JavaScript runtime, but i...
JsGenerator
python
scipy__scipy
scipy/spatial/tests/test_distance.py
{ "start": 57809, "end": 61090 }
class ____: def setup_method(self): # 1D arrays x = np.array([1.0, 2.0, 3.0]) y = np.array([1.0, 1.0, 5.0]) self.cases = [(x, y)] def test_minkowski(self): for x, y in self.cases: dist1 = minkowski(x, y, p=1) assert_almost_equal(dist1, 3.0) ...
TestSomeDistanceFunctions
python
PyCQA__isort
tests/unit/profiles/test_django.py
{ "start": 1682, "end": 3687 }
class ____: def __repr__(self): return '<Deferred field>' def __str__(self): return '<Deferred field>'""" ) def test_django_snippet_two(): django_isort_test( '''from django.utils.version import get_version VERSION = (3, 2, 0, 'alpha', 0) __version__ = get_version(VERSION) ...
Deferred
python
kamyu104__LeetCode-Solutions
Python/merge-similar-items.py
{ "start": 71, "end": 357 }
class ____(object): def mergeSimilarItems(self, items1, items2): """ :type items1: List[List[int]] :type items2: List[List[int]] :rtype: List[List[int]] """ return sorted((Counter(dict(items1))+Counter(dict(items2))).iteritems())
Solution
python
gevent__gevent
src/gevent/events.py
{ "start": 15170, "end": 15569 }
class ____(_PatchAllMixin, GeventWillPatchEvent): """ Implementation of `IGeventWillPatchAllEvent`. """ #: The name of the setuptools entry point that is called when this #: event is emitted. ENTRY_POINT_NAME = 'gevent.plugins.monkey.will_patch_all' def will_patch_module(self, module_name)...
GeventWillPatchAllEvent
python
networkx__networkx
networkx/utils/tests/test_mapped_queue.py
{ "start": 5344, "end": 7354 }
class ____(TestMappedQueue): def _make_mapped_queue(self, h): priority_dict = {elt: elt for elt in h} return MappedQueue(priority_dict) def test_init(self): d = {5: 0, 4: 1, "a": 2, 2: 3, 1: 4} q = MappedQueue(d) assert q.position == d def test_ties(self): d...
TestMappedDict
python
altair-viz__altair
altair/utils/_vegafusion_data.py
{ "start": 2059, "end": 9660 }
class ____(TypedDict): url: str _VegaFusionReturnType = Union[_ToVegaFusionReturnUrlDict, ToValuesReturnType] @overload def vegafusion_data_transformer( data: None = ..., max_rows: int = ... ) -> Callable[..., Any]: ... @overload def vegafusion_data_transformer( data: DataFrameLike, max_rows: int = .....
_ToVegaFusionReturnUrlDict
python
bokeh__bokeh
src/bokeh/protocol/messages/pull_doc_reply.py
{ "start": 1591, "end": 1635 }
class ____(TypedDict): doc: DocJson
PullDoc
python
ray-project__ray
release/ray_release/tests/test_test.py
{ "start": 787, "end": 17740 }
class ____(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_name(self) -> str: return self.get("name", "") def get_test_results(self, limit: int) -> List[TestResult]: return self.get("test_results", []) def is_high_impact(self) -> bool: ...
MockTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/annotation.py
{ "start": 6911, "end": 18370 }
class ____(SupportsAnnotations): """clones a SupportsAnnotations and applies an 'annotations' dictionary. Unlike regular clones, this clone also mimics __hash__() and __eq__() of the original element so that it takes its place in hashed collections. A reference to the original element is maintaine...
Annotated
python
getsentry__sentry
src/sentry/overwatch_webhooks/overwatch_consent/impl.py
{ "start": 563, "end": 1930 }
class ____(OverwatchConsentService): def get_organization_consent_status( self, *, organization_ids: list[int], region_name: str ) -> dict[int, RpcOrganizationConsentStatus]: """ Get consent status for multiple organizations in a region. Consent is determined by the combination ...
DatabaseBackedOverwatchConsentService
python
tornadoweb__tornado
tornado/httpserver.py
{ "start": 1510, "end": 10551 }
class ____(TCPServer, Configurable, httputil.HTTPServerConnectionDelegate): r"""A non-blocking, single-threaded HTTP server. A server is defined by a subclass of `.HTTPServerConnectionDelegate`, or, for backwards compatibility, a callback that takes an `.HTTPServerRequest` as an argument. The delegate ...
HTTPServer
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 39558, "end": 47570 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): pca_ = helper_functions.get_value("PCA") if pca_ is None: return np.NaN components = pca_.components_ pca_.components_ = components[:1] transformed = pca_.transform(X) pca_.components_...
PCASkewnessFirstPC
python
mlflow__mlflow
mlflow/genai/evaluation/context.py
{ "start": 1418, "end": 4020 }
class ____(Context): """ Context for eval execution. NOTE: This class is not covered by unit tests and is meant to be tested through smoke tests that run this code on an actual Databricks cluster. """ def __init__(self): self._run_id = None self._context_tags = context_registry...
RealContext
python
dagster-io__dagster
python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py
{ "start": 43293, "end": 44687 }
class ____(ColumnConstraint): """A column constraint that ensures all values in a pandas column are greater than the provided lower bound [inclusive]. Args: min_value (Union[int, float, datetime.datetime]): The lower bound. ignore_missing_vals (bool): If true, this constraint will enforce t...
MinValueColumnConstraint
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 90572, "end": 91019 }
class ____(object): ''' This only exists to be able to attach a .close method to iterators that do not support attribute assignment (most of itertools). ''' def __init__(self, iterator, close=None): self.iterator = iterator self.close_callbacks = makelist(close) def __iter__(self):...
_closeiter
python
pypa__pip
src/pip/_vendor/rich/pretty.py
{ "start": 8147, "end": 14333 }
class ____(JupyterMixin): """A rich renderable that pretty prints an object. Args: _object (Any): An object to pretty print. highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None. indent_size (int, optional): Number...
Pretty
python
RaRe-Technologies__gensim
gensim/test/test_aggregation.py
{ "start": 372, "end": 797 }
class ____(unittest.TestCase): def setUp(self): self.confirmed_measures = [1.1, 2.2, 3.3, 4.4] def test_arithmetic_mean(self): """Test arithmetic_mean()""" obtained = aggregation.arithmetic_mean(self.confirmed_measures) expected = 2.75 self.assertEqual(obtained, expected...
TestAggregation
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/base_streams.py
{ "start": 20685, "end": 21108 }
class ____(IncrementalShopifySubstream): slice_key = "id" data_field = "metafields" parent_stream_class: Union[ShopifyStream, IncrementalShopifyStream] = None def path(self, stream_slice: Optional[Mapping[str, Any]] = None, **kwargs) -> str: object_id = stream_slice[self.slice_key] ret...
MetafieldShopifySubstream
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/plugin/pytestplugin.py
{ "start": 5907, "end": 21646 }
class ____: def pytest_configure_node(self, node): from sqlalchemy.testing import provision from sqlalchemy.testing import asyncio # the master for each node fills workerinput dictionary # which pytest-xdist will transfer to the subprocess plugin_base.memoize_important_foll...
XDistHooks
python
urllib3__urllib3
src/urllib3/util/ssl_match_hostname.py
{ "start": 479, "end": 5845 }
class ____(ValueError): pass def _dnsname_match( dn: typing.Any, hostname: str, max_wildcards: int = 1 ) -> typing.Match[str] | None | bool: """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False ...
CertificateError
python
tensorflow__tensorflow
tensorflow/python/keras/layers/core.py
{ "start": 55730, "end": 56442 }
class ____(dispatch.GlobalOpDispatcher): """A global dispatcher that allows building a functional model with TF Ops.""" def handle(self, op, args, kwargs): """Handle the specified operation with the specified arguments.""" if any( isinstance(x, keras_tensor.KerasTensor) for x in nest.flatte...
KerasOpDispatcher
python
PrefectHQ__prefect
src/integrations/prefect-databricks/tests/test_rest.py
{ "start": 1381, "end": 1464 }
class ____(BaseModel): some_float: float some_bool: bool
TestAnotherBaseModel
python
huggingface__transformers
src/transformers/models/squeezebert/modeling_squeezebert.py
{ "start": 4987, "end": 5371 }
class ____(nn.Module): """ ConvActivation: Conv, Activation """ def __init__(self, cin, cout, groups, act): super().__init__() self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout, kernel_size=1, groups=groups) self.act = ACT2FN[act] def forward(self, x): outp...
ConvActivation
python
dagster-io__dagster
python_modules/dagster/dagster/_core/system_config/objects.py
{ "start": 1605, "end": 2328 }
class ____(NamedTuple): """Outputs are configured as a dict if any of the outputs have an output manager with an output_config_schema, and a list otherwise. """ config: Optional[Union[dict, list]] @property def output_names(self) -> AbstractSet[str]: if isinstance(self.config, list): ...
OutputsConfig
python
getsentry__sentry
tests/sentry/models/test_organization.py
{ "start": 7042, "end": 19747 }
class ____(TestCase, HybridCloudTestMixin): def setUp(self) -> None: self.owner = self.create_user("foo@example.com") with assume_test_silo_mode(SiloMode.CONTROL): TotpInterface().enroll(self.owner) self.org = self.create_organization(owner=self.owner) self.request = self...
Require2fa
python
readthedocs__readthedocs.org
readthedocs/organizations/tests/test_forms.py
{ "start": 1126, "end": 5550 }
class ____(OrganizationTestCase): def test_add_team_member_by_name(self): url = reverse( "organization_team_member_add", args=[self.organization.slug, self.team.slug], ) resp = self.client.post(url, data={"username_or_email": self.user.username}) self.assertEq...
OrganizationTeamMemberFormTests
python
joke2k__faker
faker/providers/date_time/en_PH/__init__.py
{ "start": 46, "end": 144 }
class ____(DateTimeProvider): """No difference from default DateTimeProvider""" pass
Provider
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1146664, "end": 1147107 }
class ____(ScaleInvalidDataShowAsstrokeWidth): """ ScaleInvalidDataShowAsValuestrokeWidth schema wrapper. Parameters ---------- value : float The stroke width, in pixels. """ _schema = {"$ref": '#/definitions/ScaleInvalidDataShowAsValue<"strokeWidth">'} def __init__(self, valu...
ScaleInvalidDataShowAsValuestrokeWidth
python
getsentry__sentry
src/sentry/web/frontend/react_page.py
{ "start": 9015, "end": 9235 }
class ____(GenericReactPageView): auth_required = False def handle_auth_required(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: raise Exception("This should not be called")
AuthV2ReactPageView
python
neetcode-gh__leetcode
python/0088-merge-sorted-array.py
{ "start": 0, "end": 455 }
class ____: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ while m > 0 and n > 0: if nums1[m-1] >= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 ...
Solution
python
huggingface__transformers
src/transformers/models/phimoe/modular_phimoe.py
{ "start": 12689, "end": 12955 }
class ____(MixtralPreTrainedModel): _can_record_outputs = { "router_logits": OutputRecorder(PhimoeTopKRouter, layer_name="mlp.router", index=0), "hidden_states": PhimoeDecoderLayer, "attentions": PhimoeAttention, }
PhimoePreTrainedModel
python
mkdocs__mkdocs
mkdocs/structure/nav.py
{ "start": 532, "end": 1401 }
class ____: def __init__(self, items: list, pages: list[Page]) -> None: self.items = items # Nested List with full navigation of Sections, Pages, and Links. self.pages = pages # Flat List of subset of Pages in nav, in order. self.homepage = None for page in pages: if p...
Navigation
python
huggingface__transformers
tests/models/swinv2/test_modeling_swinv2.py
{ "start": 17364, "end": 20373 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256") if is_vision_available() else None ) @slow def test_inference_image_classificati...
Swinv2ModelIntegrationTest
python
django__django
django/contrib/gis/geos/prototypes/io.py
{ "start": 2274, "end": 3059 }
class ____(GEOSFuncFactory): # Although the function definitions take `const unsigned char *` # as their parameter, we use c_char_p here so the function may # take Python strings directly as parameters. Inside Python there # is not a difference between signed and unsigned characters, so # it is not ...
WKBReadFunc
python
getsentry__sentry
src/sentry/workflow_engine/models/detector.py
{ "start": 1785, "end": 8398 }
class ____(DefaultFieldsModel, OwnerModel, JSONConfigBase): __relocation_scope__ = RelocationScope.Organization objects: ClassVar[DetectorManager] = DetectorManager() objects_for_deletion: ClassVar[BaseManager] = BaseManager() project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE) ...
Detector
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 26227, "end": 26360 }
class ____(Exception): """Indicates that an error occurred during the execution of an external process."""
DagsterPipesExecutionError
python
numba__numba
numba/core/typing/npydecl.py
{ "start": 807, "end": 7336 }
class ____(AbstractTemplate): @classmethod def _handle_inputs(cls, ufunc, args, kws): """ Process argument types to a given *ufunc*. Returns a (base types, explicit outputs, ndims, layout) tuple where: - `base types` is a tuple of scalar types for each input - `explicit o...
Numpy_rules_ufunc
python
tensorflow__tensorflow
tensorflow/python/ops/variable_scope.py
{ "start": 2037, "end": 6470 }
class ____: """Holds partition info used by initializer functions.""" __slots__ = ["_full_shape", "_var_offset"] def __init__(self, full_shape, var_offset): """Constructor. Args: full_shape: Tuple or list of `int` indicating the full combined shape of the partitioned variables. var_...
_PartitionInfo
python
pytorch__pytorch
torch/_dynamo/variables/ctx_manager.py
{ "start": 9836, "end": 11197 }
class ____(ContextWrappingVariable): """represents torch._functorch.pyfunction.temporarily_pop_interpreter_stack()""" @staticmethod def create( tx: "InstructionTranslator", target_values: Any, **kwargs: Any ) -> "TemporarilyPopInterpreterStackCtxManagerVariable": return TemporarilyPopIn...
TemporarilyPopInterpreterStackCtxManagerVariable
python
pyinstaller__pyinstaller
tests/unit/test_modulegraph/test_imports.py
{ "start": 2400, "end": 12782 }
class ____ (unittest.TestCase): if not hasattr(unittest.TestCase, 'assertIsInstance'): def assertIsInstance(self, value, types): if not isinstance(value, types): self.fail("%r is not an instance of %r"%(value, types)) def setUp(self): root = os.path.join( ...
TestModuleGraphImport
python
huggingface__transformers
tests/tokenization/test_tokenization_utils.py
{ "start": 1238, "end": 15710 }
class ____(unittest.TestCase): def check_tokenizer_from_pretrained(self, tokenizer_class): # max_model_input_sizes is a legacy attribute that may not exist on all tokenizers if not hasattr(tokenizer_class, "max_model_input_sizes"): return s3_models = list(tokenizer_class.max_mod...
TokenizerUtilsTest
python
numba__llvmlite
llvmlite/binding/module.py
{ "start": 7097, "end": 7305 }
class ____(_Iterator): kind = 'global' def _dispose(self): self._capi.LLVMPY_DisposeGlobalsIter(self) def _next(self): return ffi.lib.LLVMPY_GlobalsIterNext(self)
_GlobalsIterator
python
kamyu104__LeetCode-Solutions
Python/number-of-increasing-paths-in-a-grid.py
{ "start": 70, "end": 1467 }
class ____(object): def countPaths(self, grid): """ :type grid: List[List[int]] :rtype: int """ MOD = 10**9+7 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] in_degree = [[0]*len(grid[0]) for _ in xrange(len(grid))] q = [] for i in xrange(len(g...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol3.py
{ "start": 4671, "end": 4757 }
class ____(Protocol): @property def prop1(self) -> int: return 0
Proto15
python
mlflow__mlflow
mlflow/server/auth/config.py
{ "start": 143, "end": 1036 }
class ____(NamedTuple): default_permission: str database_uri: str admin_username: str admin_password: str authorization_function: str def _get_auth_config_path() -> str: return ( MLFLOW_AUTH_CONFIG_PATH.get() or Path(__file__).parent.joinpath("basic_auth.ini").resolve() ) def rea...
AuthConfig
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py
{ "start": 982, "end": 1349 }
class ____(BaseEvent): """Event fired when page data fetch completes successfully.""" page_id: str = Field(description="ID of the page that was fetched") document: Document = Field(description="The processed document") metadata: Dict[str, Any] = Field( default_factory=dict, description="Additio...
SNOWKBPageFetchCompletedEvent
python
pytorch__pytorch
torch/testing/_internal/distributed/multi_threaded_pg.py
{ "start": 3429, "end": 5070 }
class ____: @torch.no_grad() def work(self, data): world_size = len(data) for dest_rank in range(world_size): output_buffer, _, output_split_sizes, _ = data[dest_rank] output_indexes = self._size_cumsum( output_buffer.size(0), output_split_sizes, world_si...
AllToAllBase
python
numpy__numpy
numpy/f2py/symbolic.py
{ "start": 1294, "end": 1613 }
class ____(Enum): """ Used as Expr op attribute. """ INTEGER = 10 REAL = 12 COMPLEX = 15 STRING = 20 ARRAY = 30 SYMBOL = 40 TERNARY = 100 APPLY = 200 INDEXING = 210 CONCAT = 220 RELATIONAL = 300 TERMS = 1000 FACTORS = 2000 REF = 3000 DEREF = 3001 ...
Op
python
ray-project__ray
python/ray/llm/_internal/common/callbacks/base.py
{ "start": 398, "end": 1505 }
class ____: """ Context object passed to all callback hooks. Callbacks can read and modify fields as needed. """ worker_node_download_model: Optional["NodeModelDownloadable"] = None """Model download configuration for worker nodes. Used to specify how models should be downloaded and cached ...
CallbackCtx
python
huggingface__transformers
src/transformers/models/nystromformer/modeling_nystromformer.py
{ "start": 17406, "end": 17592 }
class ____(PreTrainedModel): config: NystromformerConfig base_model_prefix = "nystromformer" supports_gradient_checkpointing = True @auto_docstring
NystromformerPreTrainedModel
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 24270, "end": 25231 }
class ____(TestCase): def test_serializer_class_not_provided(self): class NoSerializerClass(generics.GenericAPIView): pass with pytest.raises(AssertionError) as excinfo: NoSerializerClass().get_serializer_class() assert str(excinfo.value) == ( "'NoSeria...
TestSerializer
python
PyCQA__pylint
tests/functional/e/enum_self_defined_member_6805.py
{ "start": 317, "end": 582 }
class ____(metaclass=Foo): def __new__(cls): return Parent.__new__(cls) def __getattr__(self, item): return item def magic(self): return self.dynamic NotEnumHasDynamicGetAttrMetaclass().magic()
NotEnumHasDynamicGetAttrMetaclass
python
sympy__sympy
sympy/stats/joint_rv_types.py
{ "start": 4652, "end": 8222 }
class ____(JointDistribution): _argnames = ('mu', 'sigma') is_Continuous=True @property def set(self): k = self.mu.shape[0] return S.Reals**k @staticmethod def check(mu, sigma): _value_check(mu.shape[0] == sigma.shape[0], "Size of the mean vector and covari...
MultivariateNormalDistribution
python
python__mypy
mypyc/test/test_run.py
{ "start": 16379, "end": 18037 }
class ____(TestRun): """Run the tests with strict dunder typing.""" strict_dunder_typing = True test_name_suffix = "_dunder_typing" files = ["run-dunders.test", "run-floats.test"] def fix_native_line_number(message: str, fnam: str, delta: int) -> str: """Update code locations in test case output ...
TestRunStrictDunderTyping
python
pytorch__pytorch
test/test_testing.py
{ "start": 32686, "end": 33664 }
class ____(TestCase): @deviceCountAtLeast(1) def test_mismatching_device(self, devices): for actual_device, expected_device in itertools.permutations(("cpu", *devices), 2): actual = torch.empty((), device=actual_device) expected = actual.clone().to(expected_device) fo...
TestAssertCloseMultiDevice
python
networkx__networkx
networkx/readwrite/text.py
{ "start": 221, "end": 424 }
class ____: @classmethod def as_dict(cls): return { a: getattr(cls, a) for a in dir(cls) if not a.startswith("_") and a != "as_dict" }
BaseGlyphs
python
doocs__leetcode
solution/0300-0399/0398.Random Pick Index/Solution.py
{ "start": 0, "end": 469 }
class ____: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: n = ans = 0 for i, v in enumerate(self.nums): if v == target: n += 1 x = random.randint(1, n) if x == n: ...
Solution
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 59281, "end": 59659 }
class ____(Elemwise): _parameters = ["frame", "skipna", "ddof", "numeric_only"] _defaults = {"skipna": True, "ddof": 1, "numeric_only": False} _keyword_only = ["skipna", "ddof", "numeric_only"] operation = M.var _is_length_preserving = True @functools.cached_property def _kwargs(self) -> di...
VarColumns
python
huggingface__transformers
tests/models/gpt_neox/test_modeling_gpt_neox.py
{ "start": 11245, "end": 14626 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ...
GPTNeoXModelTest
python
jina-ai__jina
jina/serve/runtimes/asyncio.py
{ "start": 1133, "end": 15380 }
class ____: """ Runtime to make sure that a server can asynchronously run inside a new asynchronous loop. It will make sure that the server is run forever while handling the TERMINATE signals to be received by the orchestrator to shutdown the server and its resources. """ def __init__( self...
AsyncNewLoopRuntime
python
huggingface__transformers
src/transformers/models/video_llama_3/configuration_video_llama_3.py
{ "start": 1256, "end": 4210 }
class ____(PreTrainedConfig): """ This is the configuration class to store the configuration of a [`VideoLlama3VisionModel`]. It is used to instantiate a VideoLLaMA3 vision encoder model according to the specified arguments, defining the model architecture. Instantiating a configuration with the default...
VideoLlama3VisionConfig
python
numba__numba
numba/core/datamodel/models.py
{ "start": 36175, "end": 37964 }
class ____(CompositeModel): def __init__(self, dmm, fe_type): super(GeneratorModel, self).__init__(dmm, fe_type) # XXX Fold this in DataPacker? self._arg_models = [self._dmm.lookup(t) for t in fe_type.arg_types if not isinstance(t, types.Omitted)] self._st...
GeneratorModel
python
networkx__networkx
networkx/algorithms/components/tests/test_weakly_connected.py
{ "start": 83, "end": 3083 }
class ____: @classmethod def setup_class(cls): cls.gc = [] G = nx.DiGraph() G.add_edges_from( [ (1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5), (5, 3), ...
TestWeaklyConnected
python
neetcode-gh__leetcode
python/0025-reverse-nodes-in-k-group.py
{ "start": 0, "end": 772 }
class ____: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: dummy = ListNode(0, head) groupPrev = dummy while True: kth = self.getKth(groupPrev, k) if not kth: break groupNext = kth.next # reverse group ...
Solution
python
tensorflow__tensorflow
tensorflow/python/tools/api/generator2/shared/exported_api.py
{ "start": 1546, "end": 3278 }
class ____(object): """ExportedApi is a collection of ExportedSymbols.""" _docs: set[ExportedDoc] _symbols: set[ExportedSymbol] def __init__( self, *, docs: Iterable[ExportedDoc] = (), symbols: Iterable[ExportedSymbol] = (), ): self._docs = set(docs) self._symbols = set(symbo...
ExportedApi
python
streamlit__streamlit
lib/streamlit/elements/widgets/color_picker.py
{ "start": 1896, "end": 10028 }
class ____: @gather_metrics("color_picker") def color_picker( self, label: str, value: str | None = None, key: Key | None = None, help: str | None = None, on_change: WidgetCallback | None = None, args: WidgetArgs | None = None, kwargs: WidgetKwargs...
ColorPickerMixin
python
pydata__xarray
xarray/coding/common.py
{ "start": 1709, "end": 5083 }
class ____(indexing.ExplicitlyIndexedNDArrayMixin): """Lazily computed array holding values of elemwise-function. Do not construct this object directly: call lazy_elemwise_func instead. Values are computed upon indexing or coercion to a NumPy array. """ def __init__(self, array, func: Callable, d...
_ElementwiseFunctionArray
python
pyparsing__pyparsing
examples/adventureEngine.py
{ "start": 6888, "end": 7605 }
class ____(Command): def __init__(self, quals): super().__init__("EXAMINE", "examining") self.subject = Item.items[quals.item] @staticmethod def help_description(): return "EXAMINE or EX or X - look closely at an object" def _do_command(self, player): msg = random.choic...
ExamineCommand
python
pypa__pipenv
pipenv/patched/pip/_vendor/rich/__main__.py
{ "start": 744, "end": 8499 }
class ____: def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: for y in range(0, 5): for x in range(options.max_width): h = x / options.max_width l = 0.1 + ((y / 5) * 0.7) r1, g1, b1 = colorsys.hls_...
ColorBox
python
pallets__jinja
src/jinja2/utils.py
{ "start": 22949, "end": 23239 }
class ____: """A joining helper for templates.""" def __init__(self, sep: str = ", ") -> None: self.sep = sep self.used = False def __call__(self) -> str: if not self.used: self.used = True return "" return self.sep
Joiner
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/components/workspace_component/component.py
{ "start": 6652, "end": 7898 }
class ____(dg.Model): by_id: Annotated[ Sequence[str], pydantic.Field(..., description="A list of connection IDs to include in the collection."), ] def resolve_connection_selector( context: dg.ResolutionContext, model ) -> Optional[Callable[[AirbyteConnection], bool]]: if isinstance(mo...
AirbyteConnectionSelectorById
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_validators.py
{ "start": 3420, "end": 3773 }
class ____(BaseDataConditionGroupValidator): conditions = serializers.ListField(required=True) def validate_conditions(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]: for condition in value: MockDataConditionValidator(data=condition).is_valid(raise_exception=True) retur...
MockConditionGroupValidator
python
google__pytype
pytype/tools/environment_test.py
{ "start": 2092, "end": 2772 }
class ____(unittest.TestCase): """Tests for {do_x}_or_die() methods. Since whether these functions complete successfully depends on one's particular environment, these tests allow either succeeding or raising SystemExit. Any other exception will cause a test failure. """ def _test(self, method, *args): ...
TestDoXOrDie
python
doocs__leetcode
solution/0200-0299/0278.First Bad Version/Solution.py
{ "start": 95, "end": 350 }
class ____: def firstBadVersion(self, n: int) -> int: l, r = 1, n while l < r: mid = (l + r) >> 1 if isBadVersion(mid): r = mid else: l = mid + 1 return l
Solution
python
celery__celery
t/unit/utils/test_time.py
{ "start": 8349, "end": 9229 }
class ____: def test_standard_tz(self): tz = tzinfo() wtz = make_aware(datetime.now(_timezone.utc), tz) assert wtz.tzinfo == tz def test_tz_when_zoneinfo(self): tz = ZoneInfo('US/Eastern') wtz = make_aware(datetime.now(_timezone.utc), tz) assert wtz.tzinfo == tz...
test_make_aware
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_dataproc.py
{ "start": 21399, "end": 25676 }
class ____: def test_submit_trigger_serialization(self, submit_trigger): """Test that the trigger serializes its configuration correctly.""" classpath, kwargs = submit_trigger.serialize() assert classpath == "airflow.providers.google.cloud.triggers.dataproc.DataprocSubmitTrigger" ass...
TestDataprocSubmitTrigger
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/gcs_upload.py
{ "start": 1226, "end": 1330 }
class ____: id: str uploaded: bool blob_id: Optional[str] @dataclass(frozen=True)
UploadedFile
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 72455, "end": 73563 }
class ____(Affine2DBase): """ A special class that does one thing, the identity transform, in a fast way. """ _mtx = np.identity(3) def frozen(self): # docstring inherited return self __str__ = _make_str_method() def get_matrix(self): # docstring inherited ...
IdentityTransform
python
getsentry__sentry
src/sentry/integrations/slack/service.py
{ "start": 4604, "end": 26257 }
class ____: """ Slack service is the main entry point for all business logic related to Slack. We will consolidate the Slack logic in here to create an easier interface to interact with, and not worry about figuring out which specific class or object you need, how to create them, in which order, and wha...
SlackService
python
coleifer__peewee
peewee.py
{ "start": 25711, "end": 26489 }
class ____(object): def __init__(self, table, database): self.table = table self.database = database def __call__(self, fn): @wraps(fn) def inner(*args, **kwargs): with _BoundTableContext(self.table, self.database): return fn(*args, **kwargs) ...
_BoundTableContext
python
tensorflow__tensorflow
tensorflow/python/training/monitored_session_test.py
{ "start": 19583, "end": 24023 }
class ____(test.TestCase): """Test distribute coordinator controls summary saving and checkpointing.""" def test_summary_hook_enabled(self): context = distribute_coordinator._WorkerContext( MockStrategy(should_save_summary=True), None, None, None) logdir = _test_dir(self.get_temp_dir(), 'test_summ...
MonitoredTrainingSessionWithDistributeCoordinatorTest
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 94426, "end": 94628 }
class ____( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): run_create_tables = None useobject = False cascade_scalar_deletes = False uselist = True
ScalarRemoveListScalarNoCascade
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 22364, "end": 25989 }
class ____(DashboardComponent): """Size of open data transfers from/to other workers per worker""" @log_errors def __init__(self, scheduler, width=600, **kwargs): self.scheduler = scheduler self.source = ColumnDataSource( { "escaped_worker": [], "...
WorkersTransferBytes
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 6642, "end": 17100 }
class ____(nn.Module): def __init__( self, config: Pop2PianoConfig, has_relative_attention_bias=False, layer_idx: Optional[int] = None, ): super().__init__() self.is_decoder = config.is_decoder self.has_relative_attention_bias = has_relative_attention_bias...
Pop2PianoAttention
python
pytest-dev__pytest
testing/test_mark.py
{ "start": 14690, "end": 24020 }
class ____: def test_merging_markers_deep(self, pytester: Pytester) -> None: # issue 199 - propagate markers into nested classes p = pytester.makepyfile( """ import pytest class TestA(object): pytestmark = pytest.mark.a def test_b(s...
TestFunctional
python
catalyst-team__catalyst
catalyst/callbacks/optuna.py
{ "start": 303, "end": 3003 }
class ____(Callback): """Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric score over the dataset)...
OptunaPruningCallback
python
apache__airflow
helm-tests/tests/helm_tests/other/test_resource_quota.py
{ "start": 900, "end": 1763 }
class ____: """Tests resource quota.""" def test_resource_quota_template(self): docs = render_chart( values={ "quotas": { "configmaps": "10", "persistentvolumeclaims": "4", "pods": "4", "replicat...
TestResourceQuota
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 16449, "end": 16730 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "UnauthorizedError" def __init__(self, message=None): super().__init__() self.message = message if message else "Authorization failed"
GrapheneUnauthorizedError
python
pytorch__pytorch
torch/_inductor/compile_fx_ext.py
{ "start": 4268, "end": 4920 }
class ____(contextlib.ExitStack): """ Helper for _LoweringSerializer.patch() """ def __init__(self, lowering: _LoweringSerializer) -> None: super().__init__() self.lowering = lowering @override def __enter__(self) -> Self: super().__enter__() from . import lowe...
_LoweringSerializerContextManager
python
django-import-export__django-import-export
tests/core/models.py
{ "start": 4350, "end": 4437 }
class ____(models.Model): f = models.FloatField(blank=True, null=True)
WithFloatField
python
dateutil__dateutil
src/dateutil/relativedelta.py
{ "start": 336, "end": 24903 }
class ____(object): """ The relativedelta type is designed to be applied to an existing datetime and can replace specific components of that datetime, or represents an interval of time. It is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <https:/...
relativedelta
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 26254, "end": 26572 }
class ____(PendingDeprecationWarning): """A similar warning as :class:`_exc.SADeprecationWarning`, this warning is not used in modern versions of SQLAlchemy. """ deprecated_since: Optional[str] = None "Indicates the version that started raising this deprecation warning"
SAPendingDeprecationWarning
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/pool/base.py
{ "start": 2770, "end": 3082 }
class ____(Enum): """Describe options for "reset on return" behaviors.""" reset_rollback = 0 reset_commit = 1 reset_none = 2 _ResetStyleArgType = Union[ ResetStyle, Literal[True, None, False, "commit", "rollback"], ] reset_rollback, reset_commit, reset_none = list(ResetStyle)
ResetStyle
python
tornadoweb__tornado
tornado/test/iostream_test.py
{ "start": 7278, "end": 27107 }
class ____(AsyncTestCase): # Tests where one stream reads and the other writes. # These should work for BaseIOStream implementations. def make_iostream_pair(self, **kwargs): raise NotImplementedError def iostream_pair(self, **kwargs): """Like make_iostream_pair, but called by ``async w...
TestReadWriteMixin
python
mlflow__mlflow
mlflow/entities/model_registry/model_version_deployment_job_run_state.py
{ "start": 143, "end": 2043 }
class ____: """Enum for model version deployment state of an :py:class:`mlflow.entities.model_registry.ModelVersion`. """ NO_VALID_DEPLOYMENT_JOB_FOUND = ProtoModelVersionDeploymentJobState.DeploymentJobRunState.Value( "NO_VALID_DEPLOYMENT_JOB_FOUND" ) RUNNING = ProtoModelVersionDeploym...
ModelVersionDeploymentJobRunState
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
{ "start": 7947, "end": 8197 }
class ____(graphene.ObjectType): assetKey = graphene.NonNull(GrapheneAssetKey) repositories = non_null_list(lambda: external.GrapheneRepository) class Meta: name = "AssetNodeDefinitionCollision"
GrapheneAssetNodeDefinitionCollision
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/conversation/base.py
{ "start": 631, "end": 5293 }
class ____(LLMChain): """Chain to have a conversation and load context from memory. This class is deprecated in favor of `RunnableWithMessageHistory`. Please refer to this tutorial for more detail: https://python.langchain.com/docs/tutorials/chatbot/ `RunnableWithMessageHistory` offers several benefit...
ConversationChain