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
gevent__gevent
src/gevent/subprocess.py
{ "start": 17854, "end": 77384 }
class ____(object): """ The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions. .. seealso:: :class:`subprocess.Popen` ...
Popen
python
FactoryBoy__factory_boy
tests/test_django.py
{ "start": 23372, "end": 29759 }
class ____(django_test.TestCase): def tearDown(self): super().tearDown() for path in os.listdir(models.WITHFILE_UPLOAD_DIR): # Remove temporary files written during tests. os.unlink(os.path.join(models.WITHFILE_UPLOAD_DIR, path)) def test_default_build(self): o ...
DjangoImageFieldTestCase
python
scikit-image__scikit-image
benchmarks/benchmark_morphology.py
{ "start": 263, "end": 1645 }
class ____: def setup(self, *args): try: # use a separate skeletonize_3d function on older scikit-image if Version(skimage.__version__) < Version('0.16.0'): self.skeletonize = morphology.skeletonize_3d else: self.skeletonize = morphology.sk...
Skeletonize3d
python
huggingface__transformers
examples/modular-transformers/modular_dummy_bert.py
{ "start": 270, "end": 1218 }
class ____(BertModel): def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None,...
DummyBertModel
python
pennersr__django-allauth
allauth/socialaccount/providers/flickr/views.py
{ "start": 227, "end": 760 }
class ____(OAuth): api_url = "https://api.flickr.com/services/rest" def get_user_info(self): default_params = {"nojsoncallback": "1", "format": "json"} p = dict({"method": "flickr.test.login"}, **default_params) u = self.query(self.api_url + "?" + urlencode(p)).json() p = dict(...
FlickrAPI
python
pytorch__pytorch
torch/_dynamo/eval_frame.py
{ "start": 23358, "end": 38377 }
class ____: def __init__( self, callback: DynamoCallback, on_enter: Callable[[], Any] = nothing, backend_ctx_ctor: Callable[ [], contextlib.AbstractContextManager[Any] ] = null_context, patch_fn: Callable[[], Any] = nothing, first_ctx: bool = False...
_TorchDynamoContext
python
django__django
tests/unmanaged_models/tests.py
{ "start": 1349, "end": 2171 }
class ____(TestCase): def test_many_to_many_between_unmanaged(self): """ The intermediary table between two unmanaged models should not be created. """ table = Unmanaged2._meta.get_field("mm").m2m_db_table() tables = connection.introspection.table_names() self...
ManyToManyUnmanagedTests
python
kamyu104__LeetCode-Solutions
Python/gray-code.py
{ "start": 481, "end": 658 }
class ____(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ return [i >> 1 ^ i for i in xrange(1 << n)]
Solution2
python
pallets__click
src/click/types.py
{ "start": 24320, "end": 28757 }
class ____(ParamType): """Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mod...
File
python
google__pytype
pytype/abstract/_instance_base.py
{ "start": 8972, "end": 11414 }
class ____(SimpleValue): """An instance of some object.""" def __init__( self, cls: "_base.BaseValue | _typing.LateAnnotation", ctx: "context.Context", container=None, ) -> None: super().__init__(cls.name, ctx) self.cls = cls self._instance_type_parameters_loaded = False s...
Instance
python
pytorch__pytorch
torch/distributions/transforms.py
{ "start": 26596, "end": 30490 }
class ____(Transform): r""" Transforms an unconstrained real vector :math:`x` with length :math:`D*(D-1)/2` into the Cholesky factor of a D-dimension correlation matrix. This Cholesky factor is a lower triangular matrix with positive diagonals and unit Euclidean norm for each row. The transform is p...
CorrCholeskyTransform
python
pypa__warehouse
tests/unit/admin/views/test_macaroons.py
{ "start": 3338, "end": 4188 }
class ____: def test_delete_succeeds_and_redirects(self, db_request, macaroon_service): user = UserFactory.create() db_request.user = user _, macaroon = macaroon_service.create_macaroon( location="test", description="test", scopes=[caveats.RequestUser(user...
TestMacaroonDelete
python
kamyu104__LeetCode-Solutions
Python/maximum-compatibility-score-sum.py
{ "start": 2187, "end": 3314 }
class ____(object): def maxCompatibilitySum(self, students, mentors): """ :type students: List[List[int]] :type mentors: List[List[int]] :rtype: int """ def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number result = 0 while n: ...
Solution2
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 40066, "end": 40178 }
class ____(TestEnPh): def setup_faker(self): self.fake = Faker("tl_PH") Faker.seed(0)
TestTlPh
python
tensorflow__tensorflow
tensorflow/python/distribute/multi_process_runner.py
{ "start": 45834, "end": 46501 }
class ____(RuntimeError): """An error indicating there is at least one subprocess with unexpected exit. When this is raised, a namedtuple object representing the multi-process run result can be retrieved by `tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError`'s `mpr_result` attr...
UnexpectedSubprocessExitError
python
PyCQA__pylint
tests/functional/b/broad_exception/broad_exception_caught.py
{ "start": 104, "end": 603 }
class ____(CustomBroadException): pass try: __revision__ += 1 except Exception: # [broad-exception-caught] print('error') try: __revision__ += 1 except BaseException: # [broad-exception-caught] print('error') try: __revision__ += 1 except ValueError: print('error') try: __revisio...
CustomNarrowException
python
python-markdown__markdown
markdown/inlinepatterns.py
{ "start": 19477, "end": 20962 }
class ____(InlineProcessor): """ Store raw inline html and return a placeholder. """ def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]: """ Store the text of `group(1)` of a pattern and return a placeholder string. """ rawhtml = self.backslash_unescape(self.unescape(m.gr...
HtmlInlineProcessor
python
doocs__leetcode
solution/0600-0699/0621.Task Scheduler/Solution.py
{ "start": 0, "end": 237 }
class ____: def leastInterval(self, tasks: List[str], n: int) -> int: cnt = Counter(tasks) x = max(cnt.values()) s = sum(v == x for v in cnt.values()) return max(len(tasks), (x - 1) * (n + 1) + s)
Solution
python
huggingface__transformers
src/transformers/utils/import_utils.py
{ "start": 79337, "end": 100397 }
class ____: def __init__(self, backend_requirement: str): self.package_name, self.version_comparison, self.version = split_package_version(backend_requirement) if self.package_name not in BACKENDS_MAPPING: raise ValueError( f"Backends should be defined in the BACKENDS_MA...
Backend
python
simplejson__simplejson
simplejson/tests/test_scanstring.py
{ "start": 132, "end": 7648 }
class ____(TestCase): # The bytes type is intentionally not used in most of these tests # under Python 3 because the decoder immediately coerces to str before # calling scanstring. In Python 2 we are testing the code paths # for both unicode and str. # # The reason this is done is because Python...
TestScanString
python
doocs__leetcode
solution/3600-3699/3653.XOR After Range Multiplication Queries I/Solution.py
{ "start": 0, "end": 280 }
class ____: def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int: mod = 10**9 + 7 for l, r, k, v in queries: for idx in range(l, r + 1, k): nums[idx] = nums[idx] * v % mod return reduce(xor, nums)
Solution
python
pyodide__pyodide
docs/sphinx_pyodide/sphinx_pyodide/lexers.py
{ "start": 259, "end": 1147 }
class ____(JavascriptLexer): tokens = { "root": [ ( r"(pyodide)(\.)(runPython|runPythonAsync)(\()", bygroups( Token.Name, Token.Operator, Token.Name, Token.Punctuation, ...
PyodideLexer
python
faif__python-patterns
patterns/structural/front_controller.py
{ "start": 1180, "end": 1617 }
class ____: """front controller""" def __init__(self) -> None: self.dispatcher = Dispatcher() def dispatch_request(self, request: Any) -> None: """ This function takes a request object and sends it to the dispatcher. """ if isinstance(request, Request): ...
RequestController
python
PrefectHQ__prefect
tests/test_flows.py
{ "start": 94808, "end": 95655 }
class ____: def test_hook_with_extra_default_arg(self): data = {} def hook(flow, flow_run, state, foo=42): data.update(name=hook.__name__, state=state, foo=foo) @flow(on_completion=[hook]) def foo_flow(): pass state = foo_flow(return_state=True) ...
TestFlowHooksWithKwargs
python
huggingface__transformers
tests/cli/test_serve.py
{ "start": 20723, "end": 26803 }
class ____(ServeCompletionsMixin, unittest.TestCase): """Tests the `generate` version of the Completions API.""" @classmethod def setUpClass(cls): """Starts a server for tests to connect to.""" cls.port = 8001 cls.server = Serve(port=cls.port, non_blocking=True) @classmethod ...
ServeCompletionsGenerateIntegrationTest
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 38755, "end": 46209 }
class ____: def test_sys_meta_path_munged(self, pytester: Pytester) -> None: pytester.makepyfile( """ def test_meta_path(): import sys; sys.meta_path = []""" ) assert pytester.runpytest().ret == 0 def test_write_pyc(self, pytester: Pytester, tmp_p...
TestAssertionRewriteHookDetails
python
numpy__numpy
numpy/ma/core.py
{ "start": 217422, "end": 223042 }
class ____(MaskedArray): """ Fake a 'void' object to use for masked array with structured dtypes. """ def __new__(self, data, mask=nomask, dtype=None, fill_value=None, hardmask=False, copy=False, subok=True): copy = None if not copy else True _data = np.array(data, copy=...
mvoid
python
PrefectHQ__prefect
tests/server/utilities/test_database.py
{ "start": 2896, "end": 6277 }
class ____: async def test_write_to_Pydantic(self, session: AsyncSession): p_model = PydanticModel(x=100) s_model = SQLPydanticModel(data=p_model) session.add(s_model) await session.flush() # clear cache session.expire_all() query = await session.scalars(sa....
TestPydantic
python
ray-project__ray
release/serve_tests/workloads/locust_utils.py
{ "start": 563, "end": 5989 }
class ____: def __init__( self, worker_type: str, host_url: str, token: str, expected_num_workers: int = None, stages: List[LocustStage] = None, wait_for_workers_timeout_s: float = None, data: Any = None, master_address: str = None, ): ...
LocustProcess
python
google__pytype
pytype/directors/directors_test.py
{ "start": 3755, "end": 10927 }
class ____(DirectorTestCase): def test_ignore_globally(self): self._create("", ["my-error"]) self._should_report(False, 42, error_name="my-error") def test_ignore_one_line(self): self._create(""" # line 2 x = 123 # type: ignore # line 4 """) self._should_report(True, 2) self._...
DirectorTest
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
{ "start": 52034, "end": 56659 }
class ____(nn.Module): def __init__(self, config: Sam3TrackerVideoPromptEncoderConfig): super().__init__() self.shared_embedding = Sam3TrackerVideoPositionalEmbedding(config) self.mask_embed = Sam3TrackerVideoMaskEmbedding(config) self.no_mask_embed = nn.Embedding(1, config.hidden_si...
Sam3TrackerVideoPromptEncoder
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 49955, "end": 53149 }
class ____(NonStrictDataModel): """ :param view: View params :type view: View :param destination: Storage id. This is where output files will be stored. :type destination: str :param model: Model id. :type model: str :param result: Task result. Values: 'success', 'failure' :type resu...
Output
python
huggingface__transformers
src/transformers/models/phi3/modeling_phi3.py
{ "start": 13548, "end": 15612 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Phi3Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx) self.mlp = Phi3MLP(config) self.input_layernorm = Phi3RM...
Phi3DecoderLayer
python
doocs__leetcode
solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/Solution.py
{ "start": 0, "end": 245 }
class ____: def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: if sx == fx and sy == fy: return t != 1 dx = abs(sx - fx) dy = abs(sy - fy) return max(dx, dy) <= t
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/ignores.py
{ "start": 383, "end": 2790 }
class ____(SanityVersionNeutral): """Sanity test for sanity test ignore entries.""" @property def can_ignore(self) -> bool: """True if the test supports ignore entries.""" return False @property def no_targets(self) -> bool: """True if the test does not use test targets. Mu...
IgnoresTest
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_trends.py
{ "start": 1930, "end": 2840 }
class ____(DiscoverQueryBuilder): def convert_aggregate_filter_to_condition( self, aggregate_filter: AggregateFilter ) -> WhereType | None: name = aggregate_filter.key.name if self.params.aliases is not None and name in self.params.aliases: return self.params.aliases[name].c...
TrendQueryBuilder
python
scrapy__scrapy
tests/spiders.py
{ "start": 4184, "end": 4495 }
class ____(SimpleSpider): name = "asyncdef_asyncio_return" async def parse(self, response): await asyncio.sleep(0.2) status = await get_from_asyncio_queue(response.status) self.logger.info(f"Got response {status}") return [{"id": 1}, {"id": 2}]
AsyncDefAsyncioReturnSpider
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/comparison2.py
{ "start": 1375, "end": 1825 }
class ____: bar: str def func3(x: DC1): # This should generate an error if reportUnnecessaryComparison is enabled. if x == 42: ... async def func4() -> bool: return True async def func5() -> None: # This should generate an error if reportUnnecessaryComparison is enabled. if func4()...
DC1
python
kamyu104__LeetCode-Solutions
Python/delete-characters-to-make-fancy-string.py
{ "start": 48, "end": 421 }
class ____(object): def makeFancyString(self, s): """ :type s: str :rtype: str """ s = list(s) cnt = j = 0 for i, c in enumerate(s): cnt = cnt+1 if i >= 1 and c == s[i-1] else 1 if cnt < 3: s[j] = c j += ...
Solution
python
django__django
tests/schema/models.py
{ "start": 694, "end": 832 }
class ____(models.Model): text_field = models.TextField(db_index=True) class Meta: apps = new_apps
AuthorTextFieldWithIndex
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_row02.py
{ "start": 315, "end": 977 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_row02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got...
TestCompareXLSXFiles
python
mlflow__mlflow
tests/models/test_utils.py
{ "start": 966, "end": 23012 }
class ____(NamedTuple): model: Any inference_data: Any @pytest.fixture(scope="module") def sklearn_knn_model(): iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. y = iris.target knn_model = knn.KNeighborsClassifier() knn_model.fit(X, y) return Mod...
ModelWithData
python
pypa__pip
src/pip/_internal/metadata/base.py
{ "start": 24813, "end": 24938 }
class ____(Protocol): location: str def as_zipfile(self) -> zipfile.ZipFile: raise NotImplementedError()
Wheel
python
getsentry__sentry
src/sentry/issues/analytics.py
{ "start": 78, "end": 182 }
class ____(analytics.Event): num_groups: int analytics.register(IssueForecastSaved)
IssueForecastSaved
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/tests/test_observer.py
{ "start": 1612, "end": 9896 }
class ____: async def test_minimal(self, mock_events_client: AsyncMock): flow_run_id = uuid.uuid4() pod_id = uuid.uuid4() await _replicate_pod_event( event={"type": "ADDED", "status": {"phase": "Running"}}, uid=str(pod_id), name="test", namesp...
TestReplicatePodEvent
python
facebookresearch__faiss
faiss/gpu/test/test_gpu_basics.py
{ "start": 7078, "end": 8149 }
class ____(unittest.TestCase): def test_gpu_ref(self): # this crashes dim = 256 training_data = np.random.randint(256, size=(10000, dim // 8)).astype('uint8') centroids = 330 def create_cpu(dim): quantizer = faiss.IndexBinaryFlat(dim) return faiss.In...
TestGpuRef
python
pytorch__pytorch
test/nn/test_parametrization.py
{ "start": 82206, "end": 83974 }
class ____(NNTestCase): @swap([True, False]) def test_weight_norm_parametrization(self, device): for dtype in [torch.float, torch.bfloat16]: input = torch.randn(3, 4, dtype=dtype, device=device) m = nn.Linear(4, 5, dtype=dtype, device=device) expected_output = m(input...
TestNNParametrizationDevice
python
cookiecutter__cookiecutter
cookiecutter/exceptions.py
{ "start": 1773, "end": 1960 }
class ____(CookiecutterException): """ Exception when version control is unavailable. Raised if the version control system (git or hg) is not installed. """
VCSNotInstalled
python
realpython__materials
django-flashcards-app/source_code_final/cards/views.py
{ "start": 590, "end": 1356 }
class ____(CardListView): template_name = "cards/box.html" form_class = CardCheckForm def get_queryset(self): return Card.objects.filter(box=self.kwargs["box_num"]) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["box_number"] = self.k...
BoxView
python
keras-team__keras
keras/src/backend/common/backend_utils_test.py
{ "start": 1606, "end": 2702 }
class ____(test_case.TestCase): def test_valid_padding_without_output_padding(self): """Test conversion with 'valid' padding and no output padding""" ( torch_padding, torch_output_padding, ) = _convert_conv_transpose_padding_args_from_keras_to_torch( kerne...
ConvertConvTransposePaddingArgsTorchTest
python
PyCQA__pylint
pylint/config/callback_actions.py
{ "start": 11411, "end": 11780 }
class ____(_XableAction): """Callback action for enabling a message.""" def __call__( self, parser: argparse.ArgumentParser, namespace: argparse.Namespace, values: str | Sequence[Any] | None, option_string: str | None = "--enable", ) -> None: self._call(self....
_EnableAction
python
simplejson__simplejson
simplejson/tests/test_namedtuple.py
{ "start": 846, "end": 997 }
class ____(object): def __init__(self, *args): self.point = Point(*args) def _asdict(self): return self.point._asdict()
DuckPoint
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 45719, "end": 46650 }
class ____(SpmConverter): def vocab(self, proto): vocab = [ ("<s>", 0.0), ("<pad>", 0.0), ("</s>", 0.0), ("<unk>", 0.0), ] vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]] vocab += [("<madeupword0>", 0.0), ("<madeupwo...
XGLMConverter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_format13.py
{ "start": 315, "end": 1021 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("format13.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_file...
TestCompareXLSXFiles
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 21614, "end": 30449 }
class ____(Request): """ Get all queues :param name: Get only queues whose name matches this pattern (python regular expression syntax) :type name: str :param id: List of Queue IDs used to filter results :type id: Sequence[str] :param tags: User-defined tags list used to filter resu...
GetAllRequest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/processors.py
{ "start": 5159, "end": 7701 }
class ____(Processor): """ Processor that highlights search matches in the document. Note that this doesn't support multiline search matches yet. The style classes 'search' and 'search.current' will be applied to the content. """ _classname = "search" _classname_current = "search.curre...
HighlightSearchProcessor
python
bokeh__bokeh
release/enums.py
{ "start": 773, "end": 874 }
class ____(Enum): PENDING = "PENDING" STARTED = "STARTED" COMPLETED = "COMPLETED"
ActionState
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 804142, "end": 804344 }
class ____(VegaLiteSchema): """OffsetDef schema wrapper.""" _schema = {"$ref": "#/definitions/OffsetDef"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
OffsetDef
python
huggingface__transformers
src/transformers/models/vits/configuration_vits.py
{ "start": 814, "end": 13892 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`VitsModel`]. It is used to instantiate a VITS model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configurati...
VitsConfig
python
anthropics__anthropic-sdk-python
tests/api_resources/beta/test_messages.py
{ "start": 19382, "end": 38804 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @pytest.mark.skip(reason="prism validates based on the non-beta endpoint") @parametrize async def test_method_create_overload_1(s...
TestAsyncMessages
python
modin-project__modin
modin/experimental/batch/pipeline.py
{ "start": 1318, "end": 3667 }
class ____(object): """ Internal representation of a single query in a pipeline. This object represents a single function to be pipelined in a batch pipeline. Parameters ---------- func : Callable The function to apply to the dataframe. is_output : bool, default: False Whet...
PandasQuery
python
encode__django-rest-framework
tests/test_routers.py
{ "start": 12115, "end": 13009 }
class ____(TestCase): """ Ensure keyword arguments passed in the `@action` decorator are properly handled. Refs #940. """ def setUp(self): class TestViewSet(viewsets.ModelViewSet): permission_classes = [] @action(methods=['post'], detail=True, permission_classes=[p...
TestActionKeywordArgs
python
kamyu104__LeetCode-Solutions
Python/find-the-number-of-copy-arrays.py
{ "start": 38, "end": 548 }
class ____(object): def countArrays(self, original, bounds): """ :type original: List[int] :type bounds: List[List[int]] :rtype: int """ left, right = bounds[0] result = right-left+1 for i in xrange(1, len(original)): diff = original[i]-ori...
Solution
python
huggingface__transformers
src/transformers/models/informer/modeling_informer.py
{ "start": 27811, "end": 28468 }
class ____(GradientCheckpointingLayer): def __init__(self, c_in): super().__init__() self.downConv = nn.Conv1d( in_channels=c_in, out_channels=c_in, kernel_size=3, padding=1, padding_mode="circular", ) self.norm = nn.BatchNo...
InformerConvLayer
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_base_monitor_environment_details.py
{ "start": 4811, "end": 6200 }
class ____(MonitorTestCase): __test__ = False def setUp(self) -> None: self.login_as(user=self.user) super().setUp() def test_simple(self) -> None: monitor = self._create_monitor(status=MonitorStatus.ACTIVE) monitor_environment = self._create_monitor_environment(monitor) ...
BaseDeleteMonitorTest
python
zarr-developers__zarr-python
src/zarr/codecs/sharding.py
{ "start": 1721, "end": 2024 }
class ____(Enum): """ Enum for index location used by the sharding codec. """ start = "start" end = "end" def parse_index_location(data: object) -> ShardingCodecIndexLocation: return parse_enum(data, ShardingCodecIndexLocation) @dataclass(frozen=True)
ShardingCodecIndexLocation
python
huggingface__transformers
examples/pytorch/question-answering/trainer_seq2seq_qa.py
{ "start": 1018, "end": 6616 }
class ____(Seq2SeqTrainer): def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs): super().__init__(*args, **kwargs) self.eval_examples = eval_examples self.post_process_function = post_process_function # def evaluate(self, eval_dataset=None, eval_examples=...
QuestionAnsweringSeq2SeqTrainer
python
jina-ai__jina
tests/integration/docarray_v2/csp/SampleRerankerExecutor/executor.py
{ "start": 547, "end": 1446 }
class ____(Executor): @requests(on="/rerank") def foo(self, docs: DocList[RerankerInput], **kwargs) -> DocList[RankedOutput]: ret = [] for doc in docs: ret.append( RankedOutput( results=[ RankedObjectOutput( ...
SampleRerankerExecutor
python
optuna__optuna
optuna/samplers/_brute_force.py
{ "start": 786, "end": 4063 }
class ____: # This is a class to represent the tree of search space. # A tree node has three states: # 1. Unexpanded. This is represented by children=None. # 2. Leaf. This is represented by children={} and param_name=None. # 3. Normal node. It has a param_name and non-empty children. param_nam...
_TreeNode
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/idna/codec.py
{ "start": 186, "end": 769 }
class ____(codecs.Codec): def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]: if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return b"", 0 return encode(data), len(data) def decode(...
Codec
python
PyCQA__pylint
tests/functional/a/access/access_to_protected_members.py
{ "start": 1138, "end": 1501 }
class ____: """Test for GitHub issue 1031""" _attr = 1 def correct_access(self): """Demonstrates correct access""" return type(self)._attr def incorrect_access(self): """Demonstrates incorrect access""" if self._attr == 1: return type(INST)._protected # [pr...
Issue1031
python
pydantic__pydantic
pydantic/v1/mypy.py
{ "start": 30208, "end": 31515 }
class ____: def __init__( self, name: str, is_required: bool, alias: Optional[str], has_dynamic_alias: bool, line: int, column: int ): self.name = name self.is_required = is_required self.alias = alias self.has_dynamic_alias = has_dynamic_alias self.line = line ...
PydanticModelField
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 10838, "end": 11590 }
class ____(InstallationError): """Built metadata contains inconsistent information. This is raised when the metadata contains values (e.g. name and version) that do not match the information previously obtained from sdist filename, user-supplied ``#egg=`` value, or an install requirement name. """ ...
MetadataInconsistent
python
huggingface__transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
{ "start": 31106, "end": 35721 }
class ____(MegatronBertPreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight", "cls.predictions.decoder.bias": "cls.predictions.bias", } def __init__(self, config, add_binary_head=True): r""" add_binary_head (`bool...
MegatronBertForPreTraining
python
TheAlgorithms__Python
digital_image_processing/resize/resize.py
{ "start": 122, "end": 2220 }
class ____: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height shoul...
NearestNeighbour
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_in_set_spark_optimized.py
{ "start": 2343, "end": 8415 }
class ____(ColumnAggregateExpectation): """Expect each column value to be in a given set; optimized using **join** for spark backends. Args: column (str): \ The column name. value_set (set-like): \ A set of objects used for comparison. Keyword Args: mostly (...
ExpectColumnValuesToBeInSetSparkOptimized
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py
{ "start": 1027, "end": 1102 }
class ____: def __index__(self): raise NotImplementedError
Index5
python
doocs__leetcode
solution/2000-2099/2085.Count Common Words With One Occurrence/Solution.py
{ "start": 0, "end": 218 }
class ____: def countWords(self, words1: List[str], words2: List[str]) -> int: cnt1 = Counter(words1) cnt2 = Counter(words2) return sum(v == 1 and cnt2[w] == 1 for w, v in cnt1.items())
Solution
python
getsentry__sentry
tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py
{ "start": 29370, "end": 63640 }
class ____(AlertRuleDetailsBase): method = "put" def test_simple(self) -> None: self.create_member( user=self.user, organization=self.organization, role="owner", teams=[self.team] ) self.login_as(self.user) alert_rule = self.alert_rule # We need the IDs to f...
AlertRuleDetailsPutEndpointTest
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 18183, "end": 24118 }
class ____(VariableTracker): # The ExceptionVariable corresponds to the BaseException class in Python def __init__( self, exc_type, args, init_kwargs=None, source=None, mutation_type=None ) -> None: super().__init__(source=source, mutation_type=mutation_type) self.exc_type = exc_type...
ExceptionVariable
python
kubernetes-client__python
kubernetes/e2e_test/test_client.py
{ "start": 1603, "end": 23885 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.config = base.get_e2e_configuration() def test_pod_apis(self): client = api_client.ApiClient(configuration=self.config) api = core_v1_api.CoreV1Api(client) name = 'busybox-test-' + short_uuid() po...
TestClient
python
huggingface__transformers
src/transformers/models/mlcd/modeling_mlcd.py
{ "start": 2293, "end": 4096 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, dim: int, theta: float = 10000.0) -> None: super().__init__() inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) self.register_buffer("inv_freq", inv_freq, p...
MLCDRotaryEmbedding
python
PrefectHQ__prefect
src/prefect/server/schemas/core.py
{ "start": 30719, "end": 31674 }
class ____(ORMBaseModel): """An ORM representation of a block document reference.""" parent_block_document_id: UUID = Field( default=..., description="ID of block document the reference is nested within" ) parent_block_document: Optional[BlockDocument] = Field( default=None, description...
BlockDocumentReference
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 135222, "end": 137439 }
class ____(TestCase): @parametrize( "dtype", [ np.uint8, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, ], ) def test_basic(self, dtype): a = np.array([...
TestLexsort
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 12438, "end": 13706 }
class ____(TestBaseAsyncSpiderMiddleware): """process_start tests for simple start""" ITEM_TYPE = (Request, dict) MW_SIMPLE = ProcessStartSimpleMiddleware async def _get_processed_start( self, *mw_classes: type[Any] ) -> AsyncIterator[Any] | None: class TestSpider(Spider): ...
TestProcessStartSimple
python
pytorch__pytorch
test/test_autograd.py
{ "start": 534303, "end": 551182 }
class ____(TestCase): @unittest.skipIf(not TEST_CUDA, "requires CUDA") def test_flops_and_mem(self): # From https://github.com/pytorch/pytorch/pull/126320 def get_act_mem(f): out = f() out.backward() # Why do one forward and backward? start_mem = t...
TestSelectiveActivationCheckpoint
python
numba__numba
numba/tests/test_jitmethod.py
{ "start": 109, "end": 1284 }
class ____(unittest.TestCase): def test_bound_jit_method_with_loop_lift(self): class Something(object): def __init__(self, x0): self.x0 = x0 @jit(forceobj=True) def method(self, x): a = np.empty(shape=5, dtype=np.float32) x...
TestJITMethod
python
coleifer__peewee
peewee.py
{ "start": 160237, "end": 160302 }
class ____(IntegerField): field_type = 'BIGINT'
BigIntegerField
python
doocs__leetcode
solution/0000-0099/0080.Remove Duplicates from Sorted Array II/Solution.py
{ "start": 0, "end": 219 }
class ____: def removeDuplicates(self, nums: List[int]) -> int: k = 0 for x in nums: if k < 2 or x != nums[k - 2]: nums[k] = x k += 1 return k
Solution
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/__init__.py
{ "start": 5345, "end": 5551 }
class ____: def __init__(self, *args, **kwargs): output = kwargs.get("output", ["" for _ in range(10)]) self.readline = MagicMock(side_effect=[line.encode() for line in output])
MockStdOut
python
huggingface__transformers
src/transformers/models/cpmant/modeling_cpmant.py
{ "start": 6687, "end": 8995 }
class ____(nn.Module): def __init__(self, config: CpmAntConfig, layer_idx=None): super().__init__() self.layernorm_before_attention = CpmAntLayerNorm(config) self.self_attention = CpmAntAttention(config, layer_idx=layer_idx) if config.dropout_p: self.dropout = torch.nn.Dr...
CpmAntSelfAttentionBlock
python
kamyu104__LeetCode-Solutions
Python/recover-a-tree-from-preorder-traversal.py
{ "start": 218, "end": 1041 }
class ____(object): def recoverFromPreorder(self, S): """ :type S: str :rtype: TreeNode """ i = 0 stack = [] while i < len(S): level = 0 while i < len(S) and S[i] == '-': level += 1 i += 1 whi...
Solution
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 4486, "end": 5296 }
class ____(Operation): def call(self, x): return backend.numpy.absolute(x) def compute_output_spec(self, x): sparse = getattr(x, "sparse", False) return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse) @keras_export(["keras.ops.absolute", "keras.ops.numpy.absolute"]) def absolute(x)...
Absolute
python
huggingface__transformers
tests/models/qwen2_vl/test_video_processing_qwen2_vl.py
{ "start": 4551, "end": 17573 }
class ____(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = Qwen2VLVideoProcessor if is_torchvision_available() else None def setUp(self): super().setUp() self.video_processor_tester = Qwen2VLVideoProcessingTester(self) @property def video_processor_dict(self...
Qwen2VLVideoProcessingTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/gcs_to_gcs.py
{ "start": 1277, "end": 26015 }
class ____(BaseOperator): """ Copies objects from a bucket to another, with renaming if requested. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GCSToGCSOperator` :param source_bucket: The source Google Cloud Storage bucke...
GCSToGCSOperator
python
pytorch__pytorch
torch/optim/lr_scheduler.py
{ "start": 60434, "end": 68933 }
class ____(LRScheduler): """Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This scheduler reads a metrics quantity and if no improvement is seen for a 'patience' number of epochs, the learni...
ReduceLROnPlateau
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/nodes.py
{ "start": 144, "end": 2249 }
class ____: __slots__ = 'tag', 'value', 'start_mark', 'end_mark', 'comment', 'anchor' def __init__(self, tag, value, start_mark, end_mark, comment=None, anchor=None): # type: (Any, Any, Any, Any, Any, Any) -> None self.tag = tag self.value = value self.start_mark = start_mark ...
Node
python
PyCQA__pylint
tests/functional/p/postponed/postponed_evaluation_activated_with_alias.py
{ "start": 187, "end": 342 }
class ____: @classmethod def from_string(cls, source) -> MyClass: ... def validate_b(self, obj: OtherClass) -> bool: ...
MyClass
python
ApeWorX__ape
src/ape/utils/rpc.py
{ "start": 2033, "end": 5248 }
class ____(CaseInsensitiveDict): """ A dict-like data-structure for HTTP-headers. It is case-insensitive and appends user-agent strings rather than overrides. """ def __setitem__(self, key, value): if key.lower() != "user-agent" or not self.__contains__("user-agent"): return...
RPCHeaders
python
celery__celery
celery/backends/redis.py
{ "start": 25579, "end": 28560 }
class ____(RedisBackend): """Redis sentinel task result store.""" # URL looks like `sentinel://0.0.0.0:26347/3;sentinel://0.0.0.0:26348/3` _SERVER_URI_SEPARATOR = ";" sentinel = getattr(redis, "sentinel", None) connection_class_ssl = SentinelManagedSSLConnection if sentinel else None def __in...
SentinelBackend