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
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/random_translation.py
{ "start": 599, "end": 14932 }
class ____(BaseImagePreprocessingLayer): """A preprocessing layer which randomly translates images during training. This layer will apply random translations to each image during training, filling empty space according to `fill_mode`. Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255...
RandomTranslation
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/event_logs.py
{ "start": 1620, "end": 1773 }
class ____(BaseModel): """Event Log Collection Response.""" event_logs: Iterable[EventLogResponse] total_entries: int
EventLogCollectionResponse
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 119096, "end": 119520 }
class ____(nn.Module): def __init__(self, config: OneFormerConfig): super().__init__() self.task_mlp = OneFormerMLPPredictionHead( config.task_seq_len, config.hidden_dim, config.hidden_dim, 2, ) def forward(self, inputs: Tensor) -> Tensor:...
OneFormerTaskModel
python
apache__airflow
airflow-core/src/airflow/api_fastapi/auth/managers/models/base_user.py
{ "start": 856, "end": 1014 }
class ____: """User model interface.""" @abstractmethod def get_id(self) -> str: ... @abstractmethod def get_name(self) -> str: ...
BaseUser
python
great-expectations__great_expectations
tests/data_context/test_data_context_variables.py
{ "start": 2421, "end": 19327 }
class ____(_ConfigurationProvider): def __init__(self, config_values=None) -> None: self._config_values = config_values or {} super().__init__() def get_values(self): return self._config_values @pytest.fixture def ephemeral_data_context_variables( data_context_config: DataContextC...
StubConfigurationProvider
python
facebook__pyre-check
tools/incremental_test/batch.py
{ "start": 2745, "end": 3145 }
class ____(FinishedRunnerResult): def get_status(self) -> str: return "pass" def to_json(self, dont_show_discrepancy: bool) -> Dict[str, Any]: # Don't bother include the input specification in the result if the test passes. return { "status": self.get_status(), "...
PassedRunnerResult
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 17337, "end": 17859 }
class ____(PointEvent): ''' Announce a mouse movement event over a Bokeh plot. Attributes: sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coordi...
MouseMove
python
lepture__authlib
authlib/oauth2/rfc7523/validator.py
{ "start": 633, "end": 1668 }
class ____(BearerTokenValidator): TOKEN_TYPE = "bearer" token_cls = JWTBearerToken def __init__(self, public_key, issuer=None, realm=None, **extra_attributes): super().__init__(realm, **extra_attributes) self.public_key = public_key claims_options = { "exp": {"essential"...
JWTBearerTokenValidator
python
numba__numba
numba/testing/main.py
{ "start": 27289, "end": 31545 }
class ____(runner.TextTestRunner): """ A test runner which delegates the actual running to a pool of child processes. """ resultclass = ParallelTestResult timeout = _TIMEOUT def __init__(self, runner_cls, nprocs, useslice, **kwargs): runner.TextTestRunner.__init__(self, **kwargs) ...
ParallelTestRunner
python
tensorflow__tensorflow
third_party/xla/xla/python_api/xla_shape_test.py
{ "start": 998, "end": 4443 }
class ____(absltest.TestCase): def assertShape(self, shape, expected_dimensions, expected_element_type): self.assertEqual(shape.element_type(), expected_element_type) self.assertEqual(shape.dimensions(), expected_dimensions) def assertLayout(self, layout, expected_minor_to_major): self.assertEqual(lay...
CreateShapeFromNumpyTest
python
spyder-ide__spyder
spyder/api/widgets/menus.py
{ "start": 980, "end": 1162 }
class ____: Context = 'context_menu' Options = 'options_menu' # ---- Style # -----------------------------------------------------------------------------
PluginMainWidgetMenus
python
viewflow__viewflow
tests/json/test_json__basics.py
{ "start": 3028, "end": 3131 }
class ____(forms.ModelForm): class Meta: model = Person exclude = ["data"]
PersonForm
python
spyder-ide__spyder
spyder/plugins/preferences/widgets/configdialog.py
{ "start": 681, "end": 4517 }
class ____(SidebarDialog): """Preferences dialog.""" # Signals check_settings = Signal() sig_size_changed = Signal(QSize) sig_reset_preferences_requested = Signal() # Constants TITLE = _("Preferences") MIN_WIDTH = 940 if MAC else (875 if WIN else 920) MIN_HEIGHT = 700 if MAC else (...
ConfigDialog
python
getlogbook__logbook
src/logbook/queues.py
{ "start": 20897, "end": 22431 }
class ____(WrapperHandler): """This handled uses a single background thread to dispatch log records to a specific other handler using an internal queue. The idea is that if you are using a handler that requires some time to hand off the log records (such as the mail handler) and would block your reques...
ThreadedWrapperHandler
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
{ "start": 31737, "end": 39286 }
class ____(SearchStrategy[Ex]): """Implements a union of strategies. Given a number of strategies this generates values which could have come from any of them. The conditional distribution draws uniformly at random from some non-empty subset of these strategies and then draws from the conditional d...
OneOfStrategy
python
walkccc__LeetCode
solutions/1995. Count Special Quadruplets/1995.py
{ "start": 0, "end": 296 }
class ____: def countQuadruplets(self, nums: list[int]) -> int: n = len(nums) return sum(nums[a] + nums[b] + nums[c] == nums[d] for a in range(n) for b in range(a + 1, n) for c in range(b + 1, n) for d in range(c + 1, n))
Solution
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0103_add_unique_constraint.py
{ "start": 230, "end": 3473 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
django-debug-toolbar__django-debug-toolbar
tests/panels/test_async_panel_compatibility.py
{ "start": 247, "end": 298 }
class ____(Panel): is_async = False
MockSyncPanel
python
numpy__numpy
numpy/typing/tests/data/pass/ufunc_config.py
{ "start": 245, "end": 318 }
class ____: def write(self, a: str) -> None: return None
Write1
python
huggingface__transformers
src/transformers/models/edgetam/modular_edgetam.py
{ "start": 6285, "end": 6357 }
class ____(Sam2TwoWayAttentionBlock): pass
EdgeTamTwoWayAttentionBlock
python
crytic__slither
slither/core/declarations/solidity_variables.py
{ "start": 5923, "end": 7232 }
class ____(SourceMapping): # Non standard handling of type(address). This function returns an undefined object # The type is dynamic # https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#type-information # As a result, we set return_type during the Ir conversion def __init__(s...
SolidityFunction
python
getsentry__sentry
src/sentry/integrations/base.py
{ "start": 5683, "end": 5799 }
class ____(TypedDict): type: str external_id: str data: dict[str, str] scopes: list[str]
_UserIdentity
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_skew_to_be_between.py
{ "start": 1009, "end": 5372 }
class ____(ColumnAggregateMetricProvider): """MetricProvider Class for Aggregate Mean MetricProvider""" metric_name = "column.custom.skew" value_keys = ("abs",) @column_aggregate_value(engine=PandasExecutionEngine) def _pandas(cls, column, abs=False, **kwargs): if abs: return n...
ColumnSkew
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 78450, "end": 80520 }
class ____(SageMakerBaseOperator): """ Creates a SageMaker experiment, to be then associated to jobs etc. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:SageMakerCreateExperimentOperator` :param name: name of the experiment...
SageMakerCreateExperimentOperator
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 41708, "end": 42064 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("pt_PT") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in PtPtProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in PtPt...
TestPtPt
python
PyCQA__isort
scripts/mkstdlibs.py
{ "start": 564, "end": 1606 }
class ____: srcdir = "" config = FakeConfig() for version_module in VERSIONS: version_match = re.match( r"^stdlibs\.py(?P<major>\d)(?P<minor>\d+)$", version_module.__name__, ) version_info = (version_match.groupdict()["major"], version_match.groupdict()["minor"]) # Any modules...
FakeApp
python
pydantic__pydantic
pydantic/v1/types.py
{ "start": 32326, "end": 34622 }
class ____(int): @classmethod def __get_validators__(cls) -> 'CallableGenerator': yield cls.validate @classmethod def validate(cls, v: StrIntFloat) -> 'ByteSize': try: return cls(int(v)) except ValueError: pass str_match = byte_string_re.match(st...
ByteSize
python
PyCQA__pylint
pylint/config/callback_actions.py
{ "start": 1572, "end": 2591 }
class ____(_CallbackAction): """Action that has access to the Run object.""" def __init__( self, option_strings: Sequence[str], dest: str, nargs: None = None, const: None = None, default: None = None, type: None = None, choices: None = None, ...
_AccessRunObjectAction
python
euske__pdfminer
pdfminer/ccitt.py
{ "start": 367, "end": 1271 }
class ____: def __init__(self): self._pos = 0 return @classmethod def add(klass, root, v, bits): p = root b = None for i in range(len(bits)): if 0 < i: if p[b] is None: p[b] = [None, None] p = p[b] ...
BitParser
python
kamyu104__LeetCode-Solutions
Python/basic-calculator-ii.py
{ "start": 47, "end": 1373 }
class ____(object): def calculate(self, s): """ :type s: str :rtype: int """ def compute(operands, operators): right, left = operands.pop(), operands.pop() operands.append(ops[operators.pop()](left, right)) ops = {'+':operator.add, '-':operato...
Solution
python
matplotlib__matplotlib
lib/matplotlib/rcsetup.py
{ "start": 29200, "end": 52944 }
class ____(list): """A marker class indicating that a list-of-str is case-insensitive.""" def _convert_validator_spec(key, conv): if isinstance(conv, list): ignorecase = isinstance(conv, _ignorecase) return ValidateInStrings(key, conv, ignorecase=ignorecase) else: return conv # M...
_ignorecase
python
crytic__slither
slither/core/declarations/solidity_import_placeholder.py
{ "start": 366, "end": 1522 }
class ____(Variable): """ Placeholder for import on top level objects See the example at https://blog.soliditylang.org/2020/09/02/solidity-0.7.1-release-announcement/ In the long term we should remove this and better integrate import aliases """ def __init__(self, import_directive: Import) -> N...
SolidityImportPlaceHolder
python
django__django
tests/multiple_database/tests.py
{ "start": 79782, "end": 80167 }
class ____(TestCase): databases = {"default", "other"} def test_pickling(self): for db in self.databases: Book.objects.using(db).create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) qs = Book.objects.all() self.assertEqu...
PickleQuerySetTestCase
python
django__django
tests/admin_views/models.py
{ "start": 7885, "end": 7989 }
class ____(Account): """A service-specific account of type Bar.""" servicename = "bar"
BarAccount
python
anthropics__anthropic-sdk-python
tests/test_legacy_response.py
{ "start": 1930, "end": 3595 }
class ____(BaseModel): foo: str bar: int def test_response_parse_custom_model(client: Anthropic) -> None: response = LegacyAPIResponse( raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), client=client, stream=False, stream_cls=None, cast_to=st...
CustomModel
python
ethereum__web3.py
web3/providers/persistent/subscription_container.py
{ "start": 137, "end": 1697 }
class ____: def __init__(self) -> None: self.subscriptions: list[EthSubscription[Any]] = [] self.subscriptions_by_id: dict[HexStr, EthSubscription[Any]] = {} self.subscriptions_by_label: dict[str, EthSubscription[Any]] = {} def __len__(self) -> int: return len(self.subscriptions...
SubscriptionContainer
python
django__django
tests/delete_regress/models.py
{ "start": 2746, "end": 2805 }
class ____(Image): class Meta: proxy = True
Photo
python
django__django
django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py
{ "start": 86, "end": 802 }
class ____(migrations.Migration): dependencies = [ ("auth", "0006_require_contenttypes_0002"), ] operations = [ migrations.AlterField( model_name="user", name="username", field=models.CharField( error_messages={"unique": "A user with that ...
Migration
python
pytorch__pytorch
test/functorch/test_control_flow.py
{ "start": 140401, "end": 155937 }
class ____(TestCase): def setUp(self): torch._dynamo.reset() super().setUp() def _check_autograd(self, result, result_exp, autograd_param): grad_param = [p for p in autograd_param if p.requires_grad] result_flatten, _ = pytree.tree_flatten(result) result_exp_flatten, _ ...
AssociativeScanTests
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py
{ "start": 6893, "end": 13005 }
class ____(quantize_model_test_base.QuantizedModelTest): """Test cases regarding the use of QuantizationOptions proto. Run all tests cases in both the graph mode (default in TF1) and the eager mode (default in TF2) to ensure support for when TF2 is disabled. """ class SimpleModel(module.Module): def __...
QuantizationOptionsTest
python
google__pytype
pytype/abstract/abstract_utils.py
{ "start": 2669, "end": 2815 }
class ____: def __init__(self, container): self.container = container DUMMY_CONTAINER: DummyContainer = DummyContainer(None)
DummyContainer
python
realpython__materials
bulk-file-rename-tool-python/source_code_final/rprename/rename.py
{ "start": 182, "end": 941 }
class ____(QObject): # Define custom signals progressed = pyqtSignal(int) renamedFile = pyqtSignal(Path) finished = pyqtSignal() def __init__(self, files, prefix): super().__init__() self._files = files self._prefix = prefix def renameFiles(self): for fileNumber...
Renamer
python
bokeh__bokeh
src/bokeh/plotting/contour.py
{ "start": 2378, "end": 2562 }
class ____: ''' Coordinates for all contour lines over a whole sequence of contour levels. ''' xs: list[np.ndarray] ys: list[np.ndarray] @dataclass(frozen=True)
LineCoords
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/hitl.py
{ "start": 3022, "end": 3146 }
class ____(BaseHITLDetail): """Schema for Human-in-the-loop detail.""" task_instance: TaskInstanceResponse
HITLDetail
python
pytest-dev__pytest
testing/acceptance_test.py
{ "start": 534, "end": 19961 }
class ____: def test_config_error(self, pytester: Pytester) -> None: pytester.copy_example("conftest_usageerror/conftest.py") result = pytester.runpytest(pytester.path) assert result.ret == ExitCode.USAGE_ERROR result.stderr.fnmatch_lines(["*ERROR: hello"]) result.stdout.fnma...
TestGeneralUsage
python
airbytehq__airbyte
airbyte-integrations/connectors/source-sftp-bulk/source_sftp_bulk/client.py
{ "start": 516, "end": 2838 }
class ____: _connection: paramiko.SFTPClient = None def __init__( self, host: str, username: str, password: str = None, private_key: Optional[str] = None, port: Optional[int] = None, timeout: Optional[int] = REQUEST_TIMEOUT, ): self.host = hos...
SFTPClient
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_insights/src/connectors_insights/result_backends.py
{ "start": 1402, "end": 2499 }
class ____(ResultBackend): def __init__(self, local_directory: Path): super().__init__() if not local_directory.exists(): local_directory.mkdir(parents=True) self.local_directory = local_directory def _write(self, connector: Connector, file_to_persist: FileToPersist) -> Non...
LocalDir
python
getsentry__sentry
fixtures/integrations/jira/mock.py
{ "start": 160, "end": 2876 }
class ____(StubJiraApiClient, MockService): def get_projects_list(self, cached: bool = True): """ List all projects in the Jira data format. :return: list of project objects """ return [ { "self": f"http://www.example.com/jira/rest/api/2/project/{...
MockJira
python
networkx__networkx
networkx/generators/tests/test_lattice.py
{ "start": 5950, "end": 7950 }
class ____: "Tests for :func:`networkx.generators.lattice.triangular_lattice_graph`" def test_lattice_points(self): """Tests that the graph is really a triangular lattice.""" for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]: G = nx.triangular_lattice_graph(m, n) ...
TestTriangularLatticeGraph
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams2.py
{ "start": 205, "end": 295 }
class ____[T, S]: ... # This should generate an error if <3.12 def func1[T, S](): ...
ClassA
python
scipy__scipy
scipy/optimize/_hessian_update_strategy.py
{ "start": 3815, "end": 10735 }
class ____(HessianUpdateStrategy): """Hessian update strategy with full dimensional internal representation. """ _syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update _syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update # Symmetric matrix-vector product _symv = get_b...
FullHessianUpdateStrategy
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 84978, "end": 85632 }
class ____(dict, NonStrictDataModel): """ Task section params """ _schema = { "additionalProperties": True, "description": "Task section params", "type": "object", } def __init__(self, *args, **kwargs): self.assert_isinstance(args, "section_params", dict, is_ar...
SectionParams
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/sensors/test_wasb.py
{ "start": 3163, "end": 7991 }
class ____: def get_dag_run(self, dag_id: str = "test_dag_id", run_id: str = "test_dag_id") -> DagRun: if hasattr(DagRun, "execution_date"): # for 2.x dag_run = DagRun( # type: ignore[call-arg] dag_id=dag_id, run_type="manual", execution_date=tim...
TestWasbBlobAsyncSensor
python
kamyu104__LeetCode-Solutions
Python/bold-words-in-string.py
{ "start": 154, "end": 1272 }
class ____(object): def boldWords(self, words, S): """ :type words: List[str] :type S: str :rtype: str """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() for i, word in enumerate(words): functools.reduce(dict.__getitem__, wor...
Solution
python
tensorflow__tensorflow
tensorflow/python/module/module_test.py
{ "start": 12704, "end": 13042 }
class ____(module.Module): def __init__(self, depth, trainable=True): super().__init__(name="badger") with self.name_scope: self.child = None if depth > 1: self.child = RecursiveModule(depth - 1, trainable=trainable) self.w = variables.Variable(1.0, trainable=trainable, name="mushro...
RecursiveModule
python
walkccc__LeetCode
solutions/3040. Maximum Number of Operations With the Same Score II/3040.py
{ "start": 0, "end": 915 }
class ____: def maxOperations(self, nums: list[int]) -> int: @functools.lru_cache(None) def dp(i: int, j: int, score: int) -> int: """ Returns the maximum number of operations that can be performed for nums[i..j], s.t. all operations have the same `score`. """ if i >= j: ...
Solution
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py
{ "start": 23860, "end": 24522 }
class ____: @pytest.fixture(autouse=True) def setup(self) -> None: clear_db_assets() clear_db_runs() clear_db_dags() clear_db_dag_bundles() def teardown_method(self) -> None: clear_db_assets() clear_db_runs() clear_db_dags() clear_db_dag_bundl...
TestAssetAliases
python
kamyu104__LeetCode-Solutions
Python/graph-valid-tree.py
{ "start": 947, "end": 1848 }
class ____(object): # @param {integer} n # @param {integer[][]} edges # @return {boolean} def validTree(self, n, edges): # A structure to track each node's [visited_from, neighbors] visited_from = [-1] * n neighbors = collections.defaultdict(list) for u, v in edges: ...
Solution2
python
dagster-io__dagster
scripts/gen_airbyte_classes.py
{ "start": 3928, "end": 4435 }
class ____(SchemaType): def __init__(self, inner: SchemaType): self.inner = inner def __str__(self): return f"List[{self.inner}]" def annotation( self, scope: Optional[str] = None, quote: bool = False, hide_default: bool = False ): return f"List[{self.inner.annotation(s...
ListType
python
doocs__leetcode
lcof/面试题55 - II. 平衡二叉树/Solution.py
{ "start": 164, "end": 502 }
class ____: def isBalanced(self, root: TreeNode) -> bool: def dfs(root): if root is None: return 0 l, r = dfs(root.left), dfs(root.right) if l == -1 or r == -1 or abs(l - r) > 1: return -1 return 1 + max(l, r) return df...
Solution
python
getsentry__sentry
src/sentry/monitors/serializers.py
{ "start": 5295, "end": 5660 }
class ____(MonitorSerializerResponseOptional): id: str name: str slug: str status: str isMuted: bool isUpserting: bool config: MonitorConfigSerializerResponse dateCreated: datetime project: ProjectSerializerResponse environments: MonitorEnvironmentSerializerResponse owner: Ac...
MonitorSerializerResponse
python
getsentry__sentry
src/sentry/analytics/events/comment_webhooks.py
{ "start": 365, "end": 458 }
class ____(CommentEvent): pass @analytics.eventclass("comment.deleted")
CommentUpdatedEvent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_errorbars02.py
{ "start": 315, "end": 1798 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_errorbars02.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with error bars.""" workbook = Wor...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/types.py
{ "start": 1018, "end": 1822 }
class ____: @classmethod def enums(cls): attrs = [] for attr in cls.__dict__.values(): if isinstance(attr, EnumMeta): attrs.append(attr) return attrs @classmethod def contains(cls, value) -> bool: for enum in cls.enums(): with supp...
CliEventTags
python
huggingface__transformers
src/transformers/models/flaubert/modeling_flaubert.py
{ "start": 18543, "end": 24476 }
class ____(nn.Module): r""" A SQuAD head inspired by XLNet. Args: config ([`FlaubertConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use. """ def __init__(self, config: FlaubertConfig): ...
FlaubertSQuADHead
python
huggingface__transformers
src/transformers/models/dinov2/modeling_dinov2.py
{ "start": 11352, "end": 12399 }
class ____(nn.Module): def __init__(self, config) -> None: super().__init__() self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size)) def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: return hidden_state * self.lambda1 # Copied from transform...
Dinov2LayerScale
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/keyline.py
{ "start": 168, "end": 980 }
class ____(App): CSS = """ Vertical { keyline: thin red; } Horizontal { keyline: heavy green; } Grid { keyline: double magenta; } Box { width: 1fr; height: 1fr; } Horizontal > Box, Vertical > Box { margin: 1; } Grid ...
KeylineApp
python
numpy__numpy
benchmarks/benchmarks/bench_io.py
{ "start": 123, "end": 996 }
class ____(Benchmark): params = ["int8", "int16", "float32", "float64", "complex64", "complex128"] param_names = ['type'] def setup(self, typename): dtype = np.dtype(typename) self.d = np.arange((50 * 500), dtype=dtype).reshape((500, 50)) self.e = np.arange((50 * 500),...
Copy
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py
{ "start": 1452, "end": 1580 }
class ____: a: str = 0 b = field() c: int = foo() d = list() @attr.s(auto_attribs=False) # auto_attribs = False
C
python
python-pillow__Pillow
src/PIL/_util.py
{ "start": 282, "end": 684 }
class ____: def __init__(self, ex: BaseException): self.ex = ex def __getattr__(self, elt: str) -> NoReturn: raise self.ex @staticmethod def new(ex: BaseException) -> Any: """ Creates an object that raises the wrapped exception ``ex`` when used, and casts it to ...
DeferredError
python
huggingface__transformers
src/transformers/generation/continuous_batching/cache_manager.py
{ "start": 9954, "end": 11812 }
class ____(ABC): """Abstract base class for cache managers. Cache managers keep track of per-request cache allocations, determine when a new physical block needs to be allocated and compute physical indices for reading or writing to the cache.""" _index: int block_table: dict[str, list[int]] # request...
CacheAllocator
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 7123, "end": 7889 }
class ____(Option, metaclass=OptionType): """``gens`` option to polynomial manipulation functions. """ option = 'gens' requires: list[str] = [] excludes: list[str] = [] @classmethod def default(cls): return () @classmethod def preprocess(cls, gens): if isinstance(gens...
Gens
python
ray-project__ray
rllib/env/wrappers/unity3d_env.py
{ "start": 453, "end": 12475 }
class ____(MultiAgentEnv): # Default base port when connecting directly to the Editor _BASE_PORT_EDITOR = 5004 # Default base port when connecting to a compiled environment _BASE_PORT_ENVIRONMENT = 5005 # The worker_id for each environment instance _WORKER_ID = 0 def __init__( self,...
Unity3DEnv
python
huggingface__transformers
src/transformers/models/mamba/modeling_mamba.py
{ "start": 33281, "end": 40027 }
class ____(MambaPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "backbone.embeddings.weight"} def __init__(self, config): super().__init__(config) self.backbone = MambaModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) ...
MambaForCausalLM
python
doocs__leetcode
solution/3100-3199/3142.Check if Grid Satisfies Conditions/Solution.py
{ "start": 0, "end": 394 }
class ____: def satisfiesConditions(self, grid: List[List[int]]) -> bool: m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, x in enumerate(row): if i + 1 < m and x != grid[i + 1][j]: return False if j + 1 < n and x ==...
Solution
python
google__jax
tests/distributed_test.py
{ "start": 913, "end": 2381 }
class ____(jtu.JaxTestCase): # TODO(phawkins): Enable after https://github.com/jax-ml/jax/issues/11222 # is fixed. @unittest.SkipTest def testInitializeAndShutdown(self): if not jtu.test_device_matches(["gpu"]): self.skipTest("Test only works with GPUs.") # Tests the public APIs. Since they use gl...
DistributedTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_ops_test.py
{ "start": 3834, "end": 56510 }
class ____(test.TestCase, parameterized.TestCase): @classmethod def setUpClass(cls): # pylint: disable=g-missing-super-call cls._gpu_available = test_util.is_gpu_available() # TODO(ebrevdo): This will work once we find a way to get rendezvous # working for CSRSparseMatrix and can remove the HostMemory ...
CSRSparseMatrixOpsTest
python
pytorch__pytorch
torch/_inductor/codegen/memory_planning.py
{ "start": 1398, "end": 2736 }
class ____: """ A collection of LiveRange regions, allowing for non-contiguous live regions. Invariant: LiveRanges.ranges is in sorted order and non-overlapping """ def __init__(self, ranges: Iterable[LiveRange]): ranges = [*sorted(ranges, key=lambda x: x.begin)] self.ranges = ...
LiveRanges
python
pypa__pipenv
pipenv/vendor/importlib_metadata/_itertools.py
{ "start": 2147, "end": 5351 }
class ____: """Wrap *iterable* and return an object that buckets the iterable into child iterables based on a *key* function. >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character >>> sorted(list(s)) # Get the ...
bucket
python
pypa__pipenv
pipenv/vendor/click/shell_completion.py
{ "start": 9048, "end": 10520 }
class ____(ShellComplete): """Shell completion for Bash.""" name = "bash" source_template = _SOURCE_BASH @staticmethod def _check_version() -> None: import subprocess output = subprocess.run( ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE ) ...
BashComplete
python
openai__openai-python
src/openai/types/realtime/realtime_session_create_response.py
{ "start": 10334, "end": 12589 }
class ____(BaseModel): server_label: str """A label for this MCP server, used to identify it in tool calls.""" type: Literal["mcp"] """The type of the MCP tool. Always `mcp`.""" allowed_tools: Optional[ToolMcpToolAllowedTools] = None """List of allowed tool names or a filter object.""" au...
ToolMcpTool
python
tiangolo__fastapi
docs_src/dependencies/tutorial008c_an.py
{ "start": 111, "end": 707 }
class ____(Exception): pass def get_username(): try: yield "Rick" except InternalError: print("Oops, we didn't raise again, Britney 😱") @app.get("/items/{item_id}") def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): if item_id == "portal-gun": raise...
InternalError
python
django__django
django/db/models/expressions.py
{ "start": 52303, "end": 54478 }
class ____(ExpressionWrapper): """The logical negation of a conditional expression.""" def __init__(self, expression): super().__init__(expression, output_field=fields.BooleanField()) def __invert__(self): return self.expression.copy() def as_sql(self, compiler, connection): t...
NegatedExpression
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/llama_index/embeddings/vertex_endpoint/utils.py
{ "start": 48, "end": 681 }
class ____(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, subclass: type) -> bool: return ( hasattr(subclass, "serialize_input") and callable(subclass.serialize_input) and hasattr(subclass, "deserialize_output") and callable(subclass.deseri...
BaseIOHandler
python
pennersr__django-allauth
allauth/socialaccount/providers/vimeo_oauth2/provider.py
{ "start": 308, "end": 786 }
class ____(OAuth2Provider): id = "vimeo_oauth2" name = "Vimeo" account_class = VimeoOAuth2Account oauth2_adapter_class = VimeoOAuth2Adapter def get_default_scope(self): return ["public", "private"] def extract_uid(self, data): return data.get("uri").split("/")[-1] def extr...
VimeoOAuth2Provider
python
pypa__pipenv
pipenv/patched/pip/_internal/operations/install/wheel.py
{ "start": 14127, "end": 14457 }
class ____: def __init__(self, file: "File") -> None: self._file = file self.src_record_path = self._file.src_record_path self.dest_path = self._file.dest_path self.changed = False def save(self) -> None: self._file.save() self.changed = fix_script(self.dest_path...
ScriptFile
python
astropy__astropy
astropy/table/tests/conftest.py
{ "start": 1138, "end": 1179 }
class ____(table.Column): pass
MyColumn
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels26.py
{ "start": 315, "end": 1561 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels26.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
django-guardian__django-guardian
guardian/testapp/tests/urls.py
{ "start": 225, "end": 536 }
class ____(PermissionRequiredMixin, View): permission_required = "testapp.change_project" urlpatterns = [ path("admin/", admin.site.urls), path("accounts/login/", LoginView.as_view(template_name="blank.html")), path("permission_required/", TestClassRedirectView.as_view()), ]
TestClassRedirectView
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/shortcuts/progress_bar/formatters.py
{ "start": 8458, "end": 9268 }
class ____(Formatter): """ Display the iterations per second. """ template = HTML( "<iterations-per-second>{iterations_per_second:.2f}</iterations-per-second>" ) def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: in...
IterationsPerSecond
python
huggingface__transformers
src/transformers/models/vaultgemma/configuration_vaultgemma.py
{ "start": 1319, "end": 10161 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`VaultGemmaModel`]. It is used to instantiate an VaultGemma model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simila...
VaultGemmaConfig
python
google__jax
docs/autodidax2_part1.py
{ "start": 2931, "end": 7205 }
class ____: def interpret_op(self, op, args): assert all(isinstance(arg, float) for arg in args) match op: case Op.add: x, y = args return x + y case Op.mul: x, y = args return x * y case _: raise ValueError(f"Unrecognized primitive op: {op}") # The c...
EvalInterpreter
python
ethereum__web3.py
web3/exceptions.py
{ "start": 7815, "end": 7972 }
class ____(PersistentConnectionError): """ Raised when a persistent connection is closed gracefully by the server. """
PersistentConnectionClosedOK
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_type_lookup_future_annotations.py
{ "start": 671, "end": 704 }
class ____(TypedDict): a: int
A
python
Textualize__rich
rich/table.py
{ "start": 6133, "end": 40025 }
class ____(JupyterMixin): """A console renderable to draw a table. Args: *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance. title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None. caption ...
Table
python
html5lib__html5lib-python
html5lib/tests/tokenizer.py
{ "start": 246, "end": 6373 }
class ____(object): def __init__(self, initialState, lastStartTag=None): self.tokenizer = HTMLTokenizer self._state = initialState self._lastStartTag = lastStartTag def parse(self, stream, encoding=None, innerHTML=False): # pylint:disable=unused-argument tokenizer = self...
TokenizerTestParser
python
numba__numba
numba/cuda/tests/cudapy/test_cuda_array_interface.py
{ "start": 449, "end": 15844 }
class ____(ContextResettingTestCase): def assertPointersEqual(self, a, b): if driver.USE_NV_BINDING: self.assertEqual(int(a.device_ctypes_pointer), int(b.device_ctypes_pointer)) def test_as_cuda_array(self): h_arr = np.arange(10) self.assertFalse...
TestCudaArrayInterface
python
huggingface__transformers
src/transformers/models/lxmert/modeling_lxmert.py
{ "start": 23334, "end": 26673 }
class ____(nn.Module): def __init__(self, config): super().__init__() # Obj-level image embedding layer self.visn_fc = LxmertVisualFeatureEncoder(config) self.config = config # Number of layers self.num_l_layers = config.l_layers self.num_x_layers = config.x...
LxmertEncoder
python
plotly__plotly.py
plotly/graph_objs/surface/contours/_x.py
{ "start": 233, "end": 9979 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "surface.contours" _path_str = "surface.contours.x" _valid_props = { "color", "end", "highlight", "highlightcolor", "highlightwidth", "project", "show", "size", "start", "u...
X
python
wandb__wandb
landfill/functional_tests/lightning_fabric/pl_base.py
{ "start": 115, "end": 387 }
class ____(Dataset): def __init__(self, size, num_samples): self.len = num_samples self.data = torch.randn(num_samples, size) def __getitem__(self, index): return self.data[index] def __len__(self): return self.len
RandomDataset