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
patrick-kidger__equinox
equinox/internal/_omega.py
{ "start": 5273, "end": 7126 }
class ____ωUpdateRef: def __init__(self, value, item, is_leaf): self.value = value self.item = item self.is_leaf = is_leaf def _set_binary_at(base, name: str, op: Callable[[Any, Any, Any], Any]) -> None: def fn(self, other): if isinstance(other, ω): if jtu.tree_stru...
_
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2.py
{ "start": 127179, "end": 132993 }
class ____( CategoricalColumn, fc_old._CategoricalColumn, # pylint: disable=protected-access collections.namedtuple( 'VocabularyFileCategoricalColumn', ('key', 'vocabulary_file', 'vocabulary_size', 'num_oov_buckets', 'dtype', 'default_value', 'file_format'))): """See `categorical...
VocabularyFileCategoricalColumn
python
viewflow__viewflow
viewflow/workflow/flow/mixins.py
{ "start": 183, "end": 1428 }
class ____(metaclass=ViewsetMeta): """Task detail view.""" index_view_class: Optional[Type[View]] = None @viewprop def index_view(self): """View for a task detail.""" if self.index_view_class: return self.index_view_class.as_view() @property def index_path(self): ...
NodeDetailMixin
python
pypa__pip
src/pip/_vendor/urllib3/exceptions.py
{ "start": 1071, "end": 1305 }
class ____(HTTPError): """Raised when the connection to a proxy fails.""" def __init__(self, message, error, *args): super(ProxyError, self).__init__(message, error, *args) self.original_error = error
ProxyError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 6441, "end": 6533 }
class ____: pass def method1(): return 1 def method2(): return 22 # end # E302
Test
python
facebookresearch__faiss
benchs/bench_fw/benchmark_io.py
{ "start": 1396, "end": 9229 }
class ____: path: str # local path def __init__(self, path: str): self.path = path self.cached_ds: Dict[Any, Any] = {} def clone(self): return BenchmarkIO(path=self.path) def get_local_filepath(self, filename): if len(filename) > 184: fn, ext = os.path.spl...
BenchmarkIO
python
python__mypy
mypy/nodes.py
{ "start": 46975, "end": 50992 }
class ____(Statement): """Class definition""" __slots__ = ( "name", "_fullname", "defs", "type_args", "type_vars", "base_type_exprs", "removed_base_type_exprs", "info", "metaclass", "decorators", "keywords", "analyz...
ClassDef
python
allegroai__clearml
clearml/backend_api/services/v2_13/workers.py
{ "start": 402, "end": 2166 }
class ____(NonStrictDataModel): """ :param name: Name of the metrics category. :type name: str :param metric_keys: The names of the metrics in the category. :type metric_keys: Sequence[str] """ _schema = { "properties": { "metric_keys": { "description": "...
MetricsCategory
python
sympy__sympy
sympy/combinatorics/free_groups.py
{ "start": 3282, "end": 9552 }
class ____(DefaultPrinting): """ Free group with finite or infinite number of generators. Its input API is that of a str, Symbol/Expr or a sequence of one of these types (which may be empty) See Also ======== sympy.polys.rings.PolyRing References ========== .. [1] https://www...
FreeGroup
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py
{ "start": 2131, "end": 2172 }
class ____: foo: int = 1 @attr.frozen
C
python
imageio__imageio
imageio/plugins/_freeimage.py
{ "start": 23817, "end": 31325 }
class ____(object): def __init__(self, fi, filename, ftype, flags): self._fi = fi self._filename = filename self._ftype = ftype self._flags = flags self._bitmap = None self._close_funcs = [] def __del__(self): self.close() def close(self): if...
FIBaseBitmap
python
kamyu104__LeetCode-Solutions
Python/count-square-sum-triples.py
{ "start": 31, "end": 398 }
class ____(object): def countTriples(self, n): """ :type n: int :rtype: int """ lookup = set() for i in xrange(1, n+1): lookup.add(i**2) result = 0 for i in xrange(1, n+1): for j in xrange(1, n+1): result += int(...
Solution
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-neptune/llama_index/vector_stores/neptune/base.py
{ "start": 495, "end": 1074 }
class ____(Exception): """Exception for the Neptune queries.""" def __init__(self, exception: Union[str, Dict]): if isinstance(exception, dict): self.message = exception["message"] if "message" in exception else "unknown" self.details = exception["details"] if "details" in excep...
NeptuneVectorQueryException
python
numpy__numpy
tools/swig/test/testVector.py
{ "start": 13291, "end": 13556 }
class ____(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ######################################################################
floatTestCase
python
django-haystack__django-haystack
test_haystack/mocks.py
{ "start": 807, "end": 1175 }
class ____(SearchResult): def __init__(self, app_label, model_name, pk, score, **kwargs): super().__init__(app_label, model_name, pk, score, **kwargs) self._model = apps.get_model("core", model_name) MOCK_SEARCH_RESULTS = [ MockSearchResult("core", "MockModel", i, 1 - (i / 100.0)) for i in ran...
MockSearchResult
python
joke2k__faker
faker/providers/automotive/en_PH/__init__.py
{ "start": 108, "end": 2499 }
class ____(AutomotiveProvider): """Implement automotive provider for ``en_PH`` locale. Vehicle registration in the Philippines has many controversies and is full of quirks. On top of that, some terms are highly subject to interpretation or to varying definitions when applied colloquially, e.g. "motor" ...
Provider
python
pallets__werkzeug
examples/cupoftee/network.py
{ "start": 3595, "end": 3795 }
class ____: def __init__(self, server, name, score): self.server = server self.name = name self.score = score self.size = round(100 + log(max(score, 1)) * 25, 2)
Player
python
pytorch__pytorch
test/quantization/core/test_quantized_module.py
{ "start": 59023, "end": 79703 }
class ____(QuantizationTestCase): def _test_qconv_impl(self, q_mod, dq_mod, dim, dtype, bias): in_channels = 3 out_channels = 10 kernel_size = 2 stride = 1 padding = 0 dilation = 1 groups = 1 padding_mode = 'zeros' if qengine_is_qnnpack(): ...
TestDynamicQuantizedModule
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_cloud_batch.py
{ "start": 13066, "end": 13939 }
class ____: @pytest.mark.asyncio @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_batch.BatchServiceAsyncClient") async def test_get_job(self,...
TestCloudBatchAsyncHook
python
aio-libs__aiohttp
aiohttp/pytest_plugin.py
{ "start": 621, "end": 1156 }
class ____(Protocol): # TODO(PY311): Use Unpack to specify ClientSession kwargs. @overload async def __call__( self, __param: Application, *, server_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> TestClient[Request, Application]: ... @overload a...
AiohttpClient
python
doocs__leetcode
solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.py
{ "start": 0, "end": 259 }
class ____: def findMinArrowShots(self, points: List[List[int]]) -> int: ans, last = 0, -inf for a, b in sorted(points, key=lambda x: x[1]): if a > last: ans += 1 last = b return ans
Solution
python
pypa__warehouse
warehouse/search/tasks.py
{ "start": 2740, "end": 9434 }
class ____(Lock): def __init__(self, redis_client, timeout=None, blocking_timeout=None): super().__init__( redis_client, name="search-index", timeout=timeout, blocking_timeout=blocking_timeout, ) @tasks.task(bind=True, ignore_result=True, acks_late=T...
SearchLock
python
MongoEngine__mongoengine
mongoengine/base/datastructures.py
{ "start": 6569, "end": 12347 }
class ____(BaseList): @classmethod def __match_all(cls, embedded_doc, kwargs): """Return True if a given embedded doc matches all the filter kwargs. If it doesn't return False. """ for key, expected_value in kwargs.items(): doc_val = getattr(embedded_doc, key) ...
EmbeddedDocumentList
python
tensorflow__tensorflow
tensorflow/python/eager/forwardprop_test.py
{ "start": 38816, "end": 40863 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters([(math_ops.sin, (2, 3), 5), (math_ops.sin, (2, 3, 4), 10)]) def testJVPBatchCorrectness(self, f, primal_shape, batch_size): primals = [random_ops.random_uniform(primal_shape)] tangent_batch = [random_o...
BatchTests
python
pydantic__pydantic
pydantic-core/tests/serializers/test_string.py
{ "start": 6534, "end": 6578 }
class ____(str, BasicClass): pass
StrMixin
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 186915, "end": 186998 }
class ____(_Int4RangeTests, _RangeTypeCompilation): pass
Int4RangeCompilationTest
python
scipy__scipy
scipy/linalg/tests/test_decomp.py
{ "start": 112075, "end": 117147 }
class ____: def test_null_space(self): rng = np.random.RandomState(1) dtypes = [np.float32, np.float64, np.complex64, np.complex128] sizes = [1, 2, 3, 10, 100] for dt, n in itertools.product(dtypes, sizes): X = np.ones((2, n), dtype=dt) eps = np.finfo(dt).e...
TestNullSpace
python
getsentry__sentry
src/sentry/integrations/jira_server/actions/form.py
{ "start": 348, "end": 949 }
class ____(IntegrationNotifyServiceForm): provider = IntegrationProviderSlug.JIRA_SERVER.value def clean(self) -> dict[str, Any] | None: cleaned_data = super().clean() or {} integration_id = cleaned_data.get("integration") integration = integration_service.get_integration( ...
JiraServerNotifyServiceForm
python
Pylons__pyramid
src/pyramid/config/assets.py
{ "start": 7039, "end": 7267 }
class ____: def __init__(self, path, source): self.path = path self.source = source def __call__(self, resource_name): if resource_name == self.path: return self.source, ''
FileOverride
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/components.py
{ "start": 17057, "end": 18948 }
class ____(PageIncrement): """ Page increment strategy with subpages for the `items` stream. From the `items` documentation https://developer.monday.com/api-reference/docs/items: Please note that you cannot return more than 100 items per query when using items at the root. To adjust your qu...
ItemPaginationStrategy
python
openai__openai-python
src/openai/types/responses/response_function_tool_call_item.py
{ "start": 199, "end": 340 }
class ____(ResponseFunctionToolCall): id: str # type: ignore """The unique ID of the function tool call."""
ResponseFunctionToolCallItem
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 925882, "end": 926600 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveEnterpriseMember""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "user", "viewer") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the ...
RemoveEnterpriseMemberPayload
python
numba__numba
numba/cuda/tests/cudapy/test_vectorize_decor.py
{ "start": 549, "end": 1548 }
class ____(CUDATestCase): def test_broadcast(self): a = np.random.randn(100, 3, 1) b = a.transpose(2, 1, 0) def fn(a, b): return a - b @vectorize(['float64(float64,float64)'], target='cuda') def fngpu(a, b): return a - b expect = fn(a, b) ...
TestGPUVectorizeBroadcast
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 38444, "end": 39551 }
class ____( _CompositeTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("x", Integer, def...
MutableCompositeColumnDefaultTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/tasks.py
{ "start": 44418, "end": 48065 }
class ____(GoogleCloudBaseOperator): """ Forces to run a task in Cloud Tasks. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudTasksTaskRunOperator` :param location: The location name in which the task was created. :...
CloudTasksTaskRunOperator
python
coleifer__peewee
tests/test_utils.py
{ "start": 201, "end": 292 }
class ____(TestModel): key = CharField() class Meta: order_by = ('key',)
Data
python
rushter__MLAlgorithms
mla/gaussian_mixture.py
{ "start": 194, "end": 6850 }
class ____(BaseEstimator): """Gaussian Mixture Model: clusters with Gaussian prior. Finds clusters by repeatedly performing Expectation–Maximization (EM) algorithm on the dataset. GMM assumes the datasets is distributed in multivariate Gaussian, and tries to find the underlying structure of the Gaussia...
GaussianMixture
python
walkccc__LeetCode
solutions/3111. Minimum Rectangles to Cover Points/3111.py
{ "start": 0, "end": 260 }
class ____: def minRectanglesToCoverPoints(self, points: list[list[int]], w: int) -> int: ans = 0 prevX = -w - 1 xs = sorted([x for x, _ in points]) for x in xs: if x > prevX + w: ans += 1 prevX = x return ans
Solution
python
dask__distributed
distributed/deploy/ssh.py
{ "start": 5779, "end": 15241 }
class ____(Process): """A Remote Dask Scheduler controlled by SSH Parameters ---------- address: str The hostname where we should run this worker connect_options: dict kwargs to be passed to asyncssh connections remote_python: str Path to Python on remote node to run thi...
Scheduler
python
joblib__joblib
joblib/externals/loky/process_executor.py
{ "start": 40312, "end": 40479 }
class ____(RuntimeError): """ Raised when a ProcessPoolExecutor is shutdown while a future was in the running or pending state. """
ShutdownExecutorError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 133169, "end": 133823 }
class ____(sgqlc.types.Input): """Autogenerated input type of AddProjectV2ItemById""" __schema__ = github_schema __field_names__ = ("project_id", "content_id", "client_mutation_id") project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId") """The ID of the Project to add th...
AddProjectV2ItemByIdInput
python
walkccc__LeetCode
solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py
{ "start": 0, "end": 730 }
class ____: def countSubMultisets(self, nums: list[int], l: int, r: int) -> int: MOD = 1_000_000_007 # dp[i] := the number of submultisets of `nums` with sum i dp = [1] + [0] * r count = collections.Counter(nums) zeros = count.pop(0, 0) for num, freq in count.items(): # stride[i] := dp[...
Solution
python
PyCQA__pylint
tests/functional/u/unpacking/unpacking_non_sequence.py
{ "start": 2558, "end": 2717 }
class ____: 'base class with `test` method implementation' @staticmethod def test(data): 'default implementation' return data
TestBase
python
wandb__wandb
wandb/vendor/pygments/lexers/dsls.py
{ "start": 26223, "end": 29213 }
class ____(RegexLexer): """ Lexer for `Flatline <https://github.com/bigmlcom/flatline>`_ expressions. .. versionadded:: 2.2 """ name = 'Flatline' aliases = ['flatline'] filenames = [] mimetypes = ['text/x-flatline'] special_forms = ('let',) builtins = ( "!=", "*", "+",...
FlatlineLexer
python
etianen__django-reversion
tests/test_app/models.py
{ "start": 2141, "end": 2326 }
class ____(models.Model): revision = models.ForeignKey( Revision, on_delete=models.CASCADE, ) name = models.CharField( max_length=191, )
TestMeta
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 9608, "end": 14292 }
class ____(Exception): def __init__(self, bool, msg): self.bool = bool super().__init__(msg) def raise_func(): raise ValueError(expected_err) def custom_raise_func(): raise CustomException(True, "foo") @torch.jit.script def raise_func_script(expected_err: str) -> torch.Tensor: rais...
CustomException
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_cond_format23.py
{ "start": 345, "end": 7880 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional formatting.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle...
TestAssembleWorksheet
python
walkccc__LeetCode
solutions/3433. Count Mentions Per User/3433.py
{ "start": 202, "end": 1592 }
class ____: def countMentions( self, numberOfUsers: int, events: list[list[str]] ) -> list[int]: ans = [0] * numberOfUsers online = [True] * numberOfUsers offlineQueue = [] # min-heap to track users that are offline allMentionsCount = 0 events.sort(key=lambda x: (int(x[1]), -...
Solution
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 4214, "end": 4580 }
class ____: @pytest.mark.parametrize( 'stub, expected', [ (AttributeStub(name='foo', typ=int), ' foo: int'), (AttributeStub(name='foo', typ=make_forward_ref('Foo')), ' foo: \'Foo\''), ], ) def test_simple_attribute(self, stub, expected): assert s...
TestAttributeStub
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/ingress.py
{ "start": 564, "end": 782 }
class ____(BaseModel): host: str path: str pathType: IngressPathType tls: IngressTLSConfiguration precedingPaths: list[IngressPath] succeedingPaths: list[IngressPath]
WebserverIngressConfiguration
python
pallets__werkzeug
tests/test_formparser.py
{ "start": 8358, "end": 16845 }
class ____: def test_basic(self): resources = join(dirname(__file__), "multipart") client = Client(form_data_consumer) repository = [ ( "firefox3-2png1txt", "---------------------------186454651713519341951581030105", [ ...
TestMultiPart
python
dagster-io__dagster
python_modules/libraries/dagster-snowflake/dagster_snowflake/snowflake_io_manager.py
{ "start": 5264, "end": 13917 }
class ____(ConfigurableIOManagerFactory): """Base class for an IO manager definition that reads inputs from and writes outputs to Snowflake. Examples: .. code-block:: python from dagster_snowflake import SnowflakeIOManager from dagster_snowflake_pandas import SnowflakePandasTyp...
SnowflakeIOManager
python
pytorch__pytorch
test/functorch/test_aotdispatch.py
{ "start": 322590, "end": 323958 }
class ____(AOTTestCase): @modules(module_db, allowed_dtypes=(torch.float,)) @decorateForModules(unittest.expectedFailure, aot_autograd_module_failures) def test_aot_autograd_module_exhaustive(self, device, dtype, training, module_info): _test_aot_autograd_module_helper(self, device, dtype, training,...
TestEagerFusionModuleInfo
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 8347, "end": 22437 }
class ____: @mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset")) @mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook")) def test_execute(self, mock_hook, mock_dataset): mock_hook.return_value.create_custom_container_training_job.return_value = ( None, "training_id...
TestVertexAICreateCustomContainerTrainingJobOperator
python
hyperopt__hyperopt
hyperopt/tests/unit/test_pyll_utils.py
{ "start": 3945, "end": 4559 }
class ____(unittest.TestCase): def test_hp_uniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.uniform, "stub", 10, 10) def test_hp_quniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.quniform, "stub", 10, 10, 1) def test_hp_logunifo...
TestDistributionsWithRangeValidateBoundries
python
pytorch__pytorch
test/export/test_sparse.py
{ "start": 1136, "end": 1211 }
class ____(torch.nn.Module): def forward(self, x): return x
IdNet
python
pytorch__pytorch
torch/_inductor/utils.py
{ "start": 114455, "end": 116657 }
class ____(MutableMapping[KeyType, ValType]): """ A dictionary-like object that allows for scoped updates. It maintains an original dictionary and a set of new items that can override the original items within the scope. The original dictionary is unmodified. """ def __init__(self, origina...
ScopedDict
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 16312, "end": 19572 }
class ____: def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b / a))...
TestComplexDivision
python
mwaskom__seaborn
tests/_marks/test_base.py
{ "start": 224, "end": 4973 }
class ____: def mark(self, **features): @dataclass class MockMark(Mark): linewidth: float = Mappable(rc="lines.linewidth") pointsize: float = Mappable(4) color: str = Mappable("C0") fillcolor: str = Mappable(depend="color") alpha: float =...
TestMappable
python
django__django
tests/generic_relations/tests.py
{ "start": 37754, "end": 38126 }
class ____(SimpleTestCase): def test_none_allowed(self): # AllowsNullGFK doesn't require a content_type, so None argument should # also be allowed. AllowsNullGFK(content_object=None) # TaggedItem requires a content_type but initializing with None should # be allowed. ...
TestInitWithNoneArgument
python
pytest-dev__pytest
testing/test_subtests.py
{ "start": 26826, "end": 31689 }
class ____: """Check --pdb support for subtests fixture and TestCase.subTest.""" class _FakePdb: """Fake debugger class implementation that tracks which methods were called on it.""" quitting: bool = False calls: list[str] = [] def __init__(self, *_: object, **__: object) -> N...
TestDebugging
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchClass3.py
{ "start": 592, "end": 630 }
class ____: title: str @final
AFinal
python
pytorch__pytorch
torch/_dynamo/types.py
{ "start": 3950, "end": 4034 }
class ____(Protocol): def __call__(self, record: Any) -> None: ...
ProfilerEndHook
python
getsentry__sentry
tests/sentry/models/test_projectcodeowners.py
{ "start": 223, "end": 3148 }
class ____(TestCase): def tearDown(self) -> None: cache.delete(ProjectCodeOwners.get_cache_key(self.project.id)) super().tearDown() def setUp(self) -> None: self.login_as(user=self.user) self.team = self.create_team( organization=self.organization, slug="tiger-team...
ProjectCodeOwnersTestCase
python
pyparsing__pyparsing
examples/tiny/tiny_engine.py
{ "start": 1923, "end": 15187 }
class ____: """Runtime engine to execute TINY AST nodes. Responsibilities: - Manage I/O buffers (text-based input and output) - Maintain a simple variable environment (name -> value, with optional type) - Maintain a stack of frames (local variables) to scope variables defined in functions - Pro...
TinyEngine
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/call17.py
{ "start": 420, "end": 772 }
class ____(Generic[E_co]): def or_else(self, op: Callable[[E_co], Result[T_co, F]]) -> Result[T_co, F]: ... Result = Ok[T_co] | Err[E_co] def inner(func: Callable[[E_co], Err[F]], r: Result[T_co, E_co]) -> Result[T_co, F]: match r: case Ok(): return r.or_else(func) case Err(): ...
Err
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-azure-translate/llama_index/tools/azure_translate/base.py
{ "start": 194, "end": 1194 }
class ____(BaseToolSpec): """Azure Translate tool spec.""" spec_functions = ["translate"] def __init__(self, api_key: str, region: str) -> None: """Initialize with parameters.""" self.headers = { "Ocp-Apim-Subscription-Key": api_key, "Ocp-Apim-Subscription-Region": ...
AzureTranslateToolSpec
python
joke2k__faker
faker/providers/internet/bn_BD/__init__.py
{ "start": 46, "end": 500 }
class ____(InternetProvider): """ Implement internet provider for ``bn_BD`` locale. """ free_email_domains = ( "gmail.com", "yahoo.com", "hotmail.com", "mail.ru", "yandex.ru", "rambler.ru", ) tlds = ( "com", "com", "com", ...
Provider
python
huggingface__transformers
src/transformers/models/florence2/modeling_florence2.py
{ "start": 3026, "end": 4157 }
class ____(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, config: Florence2Config): super().__init__() num_pos = config.vision_config.max_position_embeddings embedding_dim = config.vision_config.embed_dim[-1] s...
Florence2VisionLearnedAbsolutePositionEmbedding2D
python
networkx__networkx
networkx/lazy_imports.py
{ "start": 2281, "end": 5764 }
class ____(types.ModuleType): def __init__(self, frame_data, *args, **kwargs): self.__frame_data = frame_data super().__init__(*args, **kwargs) def __getattr__(self, x): if x in ("__class__", "__file__", "__frame_data"): super().__getattr__(x) else: fd = ...
DelayedImportErrorModule
python
ray-project__ray
python/ray/data/tests/test_predicate_pushdown.py
{ "start": 28891, "end": 31214 }
class ____: """Tests for PUSH_INTO_BRANCHES behavior operators. Operator: Union Predicates are duplicated and pushed into each branch. """ def test_simple_union_with_filter(self, ray_start_regular_shared): """Filter after union should push into both branches.""" ds1 = ray.data.rang...
TestPushIntoBranchesBehavior
python
milvus-io__pymilvus
tests/test_connections.py
{ "start": 294, "end": 7595 }
class ____: """ Connect to a connected alias will: - ignore and return if no configs are given - raise ConnectionConfigException if inconsistent configs are given Connect to an existing and not connected alias will: - connect with the existing alias config if no configs are ...
TestConnect
python
bokeh__bokeh
src/bokeh/models/renderers/renderer.py
{ "start": 2376, "end": 3889 }
class ____(StyledElement): """An abstract base class for renderer types. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) level = Enum(RenderLevel, help=""" Specifies the level in which to paint...
Renderer
python
lazyprogrammer__machine_learning_examples
supervised_class2/bagging_regression.py
{ "start": 1018, "end": 1927 }
class ____: def __init__(self, B): self.B = B def fit(self, X, Y): N = len(X) self.models = [] for b in range(self.B): idx = np.random.choice(N, size=N, replace=True) Xb = X[idx] Yb = Y[idx] model = DecisionTreeRegressor() model.fit(Xb, Yb) self.models.append(mo...
BaggedTreeRegressor
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source.py
{ "start": 1408, "end": 1529 }
class ____(BaseModel): item: Dict[str, object] sample: Optional[Dict[str, object]] = None
SourceFileContentContent
python
getsentry__sentry
src/sentry/rules/conditions/reappeared_event.py
{ "start": 395, "end": 1532 }
class ____(EventCondition): id = "sentry.rules.conditions.reappeared_event.ReappearedEventCondition" label = "The issue changes state from archived to escalating" def passes(self, event: GroupEvent, state: EventState) -> bool: return state.has_escalated def get_activity( self, start: d...
ReappearedEventCondition
python
huggingface__transformers
src/transformers/models/decision_transformer/modeling_decision_transformer.py
{ "start": 3394, "end": 12458 }
class ____(nn.Module): def __init__(self, config, is_cross_attention=False, layer_idx=None): super().__init__() self.config = config max_positions = config.max_position_embeddings self.register_buffer( "bias", torch.tril(torch.ones((max_positions, max_position...
DecisionTransformerGPT2Attention
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 10575, "end": 13008 }
class ____(FileSystemEventHandler): """ Matches given patterns with file paths associated with occurring events. """ def __init__(self, patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False): super(PatternMatchingEventHandler, self).__init__() ...
PatternMatchingEventHandler
python
kamyu104__LeetCode-Solutions
Python/contains-duplicate.py
{ "start": 29, "end": 189 }
class ____(object): # @param {integer[]} nums # @return {boolean} def containsDuplicate(self, nums): return len(nums) > len(set(nums))
Solution
python
huggingface__transformers
tests/models/fsmt/test_modeling_fsmt.py
{ "start": 20786, "end": 23700 }
class ____(unittest.TestCase): padding_idx = 1 tolerance = 1e-4 def test_basic(self): input_ids = torch.tensor([[4, 10]], dtype=torch.long, device=torch_device) emb1 = SinusoidalPositionalEmbedding(num_positions=6, embedding_dim=6, padding_idx=self.padding_idx).to( torch_device ...
TestSinusoidalPositionalEmbeddings
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/models/border.py
{ "start": 33, "end": 539 }
class ____(IntFlag): EMPTY = 0 TOP = auto() BOTTOM = auto() LEFT = auto() RIGHT = auto() @property def corner(self) -> bool: return self in ( self.TOP | self.LEFT, self.TOP | self.RIGHT, self.BOTTOM | self.LEFT, self.BOTTOM | self.RIGH...
Border
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 312894, "end": 314039 }
class ____(StatNode): child_attrs = [] is_terminator = True def analyse_expressions(self, env): return self nogil_check = Node.gil_error gil_message = "Raising exception" def generate_execution_code(self, code): code.mark_pos(self.pos) vars = code.funcstate.exc_vars ...
ReraiseStatNode
python
ray-project__ray
python/ray/air/config.py
{ "start": 14472, "end": 21131 }
class ____: """Configurable parameters for defining the checkpointing strategy. Default behavior is to persist all checkpoints to disk. If ``num_to_keep`` is set, the default retention policy is to keep the checkpoints with maximum timestamp, i.e. the most recent checkpoints. Args: num_to_...
CheckpointConfig
python
tornadoweb__tornado
tornado/test/ioloop_test.py
{ "start": 807, "end": 16180 }
class ____(AsyncTestCase): def test_add_callback_return_sequence(self): # A callback returning {} or [] shouldn't spin the CPU, see Issue #1803. self.calls = 0 loop = self.io_loop test = self old_add_callback = loop.add_callback def add_callback(self, callback, *arg...
TestIOLoop
python
langchain-ai__langchain
libs/core/langchain_core/example_selectors/base.py
{ "start": 178, "end": 1716 }
class ____(ABC): """Interface for selecting examples to include in prompts.""" @abstractmethod def add_example(self, example: dict[str, str]) -> Any: """Add new example to store. Args: example: A dictionary with keys as input variables and values as their values...
BaseExampleSelector
python
spulec__freezegun
tests/test_warnings.py
{ "start": 139, "end": 2895 }
class ____: """ A module that triggers warnings on attribute access. This does not happen with regular modules, there has to be a bit of lazy module magic going on in order for this to happen. Examples of modules that uses this pattern in real projects can be found at: py.code - the compiler ...
ModuleWithWarning
python
lxml__lxml
src/lxml/html/diff.py
{ "start": 21747, "end": 32304 }
class ____(token): """ Represents the href in an anchor tag. Unlike other words, we only show the href when it changes. """ hide_when_equal = True def html(self): return ' Link: %s' % self def tokenize(html, include_hrefs=True): """ Parse the given HTML and returns token objects (...
href_token
python
pytorch__pytorch
test/distributed/test_c10d_gloo.py
{ "start": 7542, "end": 7759 }
class ____(test_c10d_common.AbstractTimeoutTest, TestCase): @requires_gloo() @retry_on_connect_failures def test_default_store_timeout_gloo(self): self._test_default_store_timeout("gloo")
TimeoutTest
python
walkccc__LeetCode
solutions/2976. Minimum Cost to Convert String I/2976.py
{ "start": 0, "end": 891 }
class ____: def minimumCost( self, source: str, target: str, original: list[str], changed: list[str], cost: list[int], ) -> int: ans = 0 # dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) dist = [[math.inf] * 26 for _ in range(26)] for a, b, c ...
Solution
python
huggingface__transformers
tests/models/esm/test_modeling_esmfold.py
{ "start": 1151, "end": 6105 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=False, use_input_mask=True, use_token_type_ids=False, use_labels=False, vocab_size=19, hidden_size=32, num_hidden_layers=2, num_attention_h...
EsmFoldModelTester
python
keras-team__keras
guides/functional_api.py
{ "start": 22211, "end": 25135 }
class ____(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) self.dense_1 = layers.Dense(64, activation='relu') self.dense_2 = layers.Dense(10) def call(self, inputs): x = self.dense_1(inputs) return self.dense_2(x) # Instantiate the model. mlp = MLP() # Necessary to crea...
MLP
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 91961, "end": 92474 }
class ____: def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1 + 1e-6)) def test_special(self): with np.errstate(invalid="ignore", divide="ignore"): assert_equal(ncu.log1p(np.nan), np.nan) assert...
TestLog1p
python
davidhalter__jedi
test/completion/lambdas.py
{ "start": 1408, "end": 1835 }
class ____(object): def __init__(self, pred=lambda a, b: a): self.a = 1 #? int() self.a #? float() pred(1.0, 2) # ----------------- # test_nocond in grammar (happens in list comprehensions with `if`) # ----------------- # Doesn't need to do anything yet. It should just not r...
Test
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/ExampleApp.py
{ "start": 1172, "end": 1635 }
class ____: Red = "#B71C1C" Pink = "#FCE4EC" Purple = "#4A148C" DeepPurple = "#311B92" Indigo = "#1A237E" Blue = "#0D47A1" LightBlue = "#01579B" Cyan = "#006064" Teal = "#004D40" Green = "#1B5E20" LightGreen = "#33691E" Lime = "#827717" Yellow = "#F57F17" Amber =...
LightThemeColors
python
huggingface__transformers
src/transformers/models/phi/modular_phi.py
{ "start": 8182, "end": 12411 }
class ____(LlamaModel): def __init__(self, config: PhiConfig): super().__init__(config) self.layers = nn.ModuleList( [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.embed_dropout = nn.Dropout(config.embd_pdrop) self.fin...
PhiModel
python
gevent__gevent
src/gevent/hub.py
{ "start": 34270, "end": 34590 }
class ____(object): __slots__ = ['callback', 'obj'] def __init__(self, callback, obj): self.callback = callback self.obj = obj def __call__(self, *args): callback = self.callback obj = self.obj self.callback = None self.obj = None callback(obj)
linkproxy
python
ansible__ansible
lib/ansible/plugins/lookup/nested.py
{ "start": 1458, "end": 1995 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): my_list = terms[:] my_list.reverse() if len(my_list) == 0: raise AnsibleError("with_nested requires at least one element in the nested list") result = my_list.pop() while len(my_list) > 0: ...
LookupModule
python
doocs__leetcode
solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.py
{ "start": 0, "end": 671 }
class ____: def reconstructMatrix( self, upper: int, lower: int, colsum: List[int] ) -> List[List[int]]: n = len(colsum) ans = [[0] * n for _ in range(2)] for j, v in enumerate(colsum): if v == 2: ans[0][j] = ans[1][j] = 1 upper, lower ...
Solution
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 162, "end": 247 }
class ____(): def __test(self): # [unused-private-member] pass
AnotherClass
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_vector/generate/async_.py
{ "start": 318, "end": 473 }
class ____( Generic[Properties, References], _NearVectorGenerateExecutor[ConnectionAsync, Properties, References], ): pass
_NearVectorGenerateAsync