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
kamyu104__LeetCode-Solutions
Python/maximize-score-after-pair-deletions.py
{ "start": 38, "end": 283 }
class ____(object): def maxScore(self, nums): """ :type nums: List[int] :rtype: int """ return sum(nums)-min(nums) if len(nums)%2 else sum(nums)-min(nums[i]+nums[i+1] for i in xrange(len(nums)-1))
Solution
python
huggingface__transformers
src/transformers/models/parakeet/configuration_parakeet.py
{ "start": 6987, "end": 10429 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ParakeetForCTC`]. It is used to instantiate a Parakeet CTC model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be...
ParakeetCTCConfig
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 47063, "end": 53129 }
class ____: all_transitions = set(product(ALL_ORCHESTRATION_STATES, CANONICAL_STATES)) terminal_transitions = set(product(TERMINAL_STATES, ALL_ORCHESTRATION_STATES)) # Cast to sorted lists for deterministic ordering. # Sort as strings to handle `None`. active_transitions = list( sorted(all_...
TestTransitionsFromTerminalStatesRule
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 3413, "end": 7038 }
class ____(TorchDistributionWrapper): """MultiCategorical distribution for MultiDiscrete action spaces.""" @override(TorchDistributionWrapper) def __init__( self, inputs: List[TensorType], model: TorchModelV2, input_lens: Union[List[int], np.ndarray, Tuple[int, ...]], ...
TorchMultiCategorical
python
django__django
tests/model_fields/test_uuid.py
{ "start": 3246, "end": 7966 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.objs = [ NullableUUIDModel.objects.create( field=uuid.UUID("25d405be-4895-4d50-9b2e-d6695359ce47"), ), NullableUUIDModel.objects.create(field="550e8400e29b41d4a716446655440000"), ...
TestQuerying
python
astropy__astropy
astropy/coordinates/tests/test_shape_manipulation.py
{ "start": 552, "end": 2657 }
class ____: @classmethod def setup_class(cls): # For these tests, we set up frames and coordinates using copy=False, # so we can check that broadcasting is handled correctly. lon = Longitude(np.arange(0, 24, 4), u.hourangle) lat = Latitude(np.arange(-90, 91, 30), u.deg) #...
ShapeSetup
python
django__django
tests/template_tests/test_nodelist.py
{ "start": 918, "end": 1353 }
class ____(SimpleTestCase): def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ ("Hello, world!", "<TextNode: 'Hello, world!'>"), ("One\ntwo.", "<TextNode: 'One\\ntwo.'>"), ]: template = engine.from_string(temptext) text...
TextNodeTest
python
keon__algorithms
tests/test_maths.py
{ "start": 788, "end": 1390 }
class ____(unittest.TestCase): """ Test for the file power.py Arguments: unittest {[type]} -- [description] """ def test_power(self): self.assertEqual(8, power(2, 3)) self.assertEqual(1, power(5, 0)) self.assertEqual(0, power(10, 3, 5)) self.assertEqual(2803...
TestPower
python
run-llama__llama_index
llama-index-core/llama_index/core/postprocessor/sbert_rerank.py
{ "start": 420, "end": 3577 }
class ____(BaseNodePostprocessor): model: str = Field(description="Sentence transformer model name.") top_n: int = Field(description="Number of nodes to return sorted by score.") device: str = Field( default="cpu", description="Device to use for sentence transformer.", ) keep_retriev...
SentenceTransformerRerank
python
langchain-ai__langchain
libs/core/langchain_core/prompts/chat.py
{ "start": 22479, "end": 22702 }
class ____(_StringImageMessagePromptTemplate): """System message prompt template. This is a message that is not sent to the user. """ _msg_class: type[BaseMessage] = SystemMessage
SystemMessagePromptTemplate
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 31884, "end": 32133 }
class ____(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=100) # Three different styles of serializer. # All should allow ordering by username, but not by password.
SensitiveOrderingFilterModel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 1795, "end": 1851 }
class ____(ParentClosed4): b: list[str]
ChildClosed4_7
python
scipy__scipy
scipy/optimize/_optimize.py
{ "start": 107719, "end": 140160 }
class ____(RuntimeError): pass def _recover_from_bracket_error(solver, fun, bracket, args, **options): # `bracket` was originally written without checking whether the resulting # bracket is valid. `brent` and `golden` built on top of it without # checking the returned bracket for validity, and their o...
BracketError
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/struct_store/sql_query.py
{ "start": 20899, "end": 23030 }
class ____(BaseSQLTableQueryEngine): """ PGvector SQL query engine. A modified version of the normal text-to-SQL query engine because we can infer embedding vectors in the sql query. NOTE: this is a beta feature NOTE: Any Text-to-SQL application should be aware that executing arbitrary SQ...
PGVectorSQLQueryEngine
python
Textualize__textual
src/textual/widgets/_text_area.py
{ "start": 3247, "end": 100199 }
class ____(ScrollView): DEFAULT_CSS = """\ TextArea { width: 1fr; height: 1fr; border: tall $border-blurred; padding: 0 1; color: $foreground; background: $surface; &.-textual-compact { border: none !important; } & .text-area--cursor { text-style: $input-cursor-te...
TextArea
python
fluentpython__example-code-2e
24-class-metaprog/timeslice.py
{ "start": 461, "end": 1803 }
class ____(): def __init__(self, arg): if isinstance(arg, slice): h = arg.start or 0 m = arg.stop or 0 s = arg.step or 0 else: h, m, s = 0, 0, arg if m in (AM, PM): self.pm = m == PM m = 0 elif s in (AM, PM): ...
T
python
kamyu104__LeetCode-Solutions
Python/toeplitz-matrix.py
{ "start": 33, "end": 345 }
class ____(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ return all(i == 0 or j == 0 or matrix[i-1][j-1] == val for i, row in enumerate(matrix) for j, val in enumerate(row))
Solution
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 194834, "end": 197929 }
class ____(test_util.TensorFlowTestCase): def _convert(self, original, original_dtype, output_dtype, expected): x_np = np.array(original, dtype=original_dtype.as_numpy_dtype()) y_np = np.array(expected, dtype=output_dtype.as_numpy_dtype()) with self.cached_session(): image = constant_op.constant(x...
ConvertImageTest
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_poly_loading.py
{ "start": 6371, "end": 8495 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsExecutionResults ): @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) adata = Column(String(50)) ...
ChunkingTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1598908, "end": 1599126 }
class ____(sgqlc.types.Union): """The results of a search.""" __schema__ = github_schema __types__ = (App, Discussion, Issue, MarketplaceListing, Organization, PullRequest, Repository, User)
SearchResultItem
python
keras-team__keras
keras/src/ops/image_test.py
{ "start": 8937, "end": 34107 }
class ____(testing.TestCase): def setUp(self): # Defaults to channels_last self.data_format = backend.image_data_format() backend.set_image_data_format("channels_last") return super().setUp() def tearDown(self): backend.set_image_data_format(self.data_format) ret...
ImageOpsStaticShapeTest
python
jamielennox__requests-mock
tests/test_custom_matchers.py
{ "start": 606, "end": 863 }
class ____(object): def __init___(self): self.called = False def __call__(self, request): self.called = True return None def match_all(request): return requests_mock.create_response(request, content=b'data')
FailMatcher
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/alloy_db.py
{ "start": 37777, "end": 43421 }
class ____(AlloyDBWriteBaseOperator): """ Create a User in an Alloy DB cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:AlloyDBCreateUserOperator` :param user_id: Required. ID of the user to create. :param user_c...
AlloyDBCreateUserOperator
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_run_launcher.py
{ "start": 1194, "end": 4075 }
class ____(BaseTestSuite): def test_run_launcher(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "no_config_job") result = execute_dagster_graphql( context=graphql_context, query=LAUNCH_PIPELINE_EXECUTION_MUTATION, v...
TestBasicLaunch
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/app_testing/tutorial001_py310/main.py
{ "start": 443, "end": 2604 }
class ____(SQLModel): name: str | None = None secret_name: str | None = None age: int | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def crea...
HeroUpdate
python
ApeWorX__ape
src/ape_test/_watch.py
{ "start": 1218, "end": 2729 }
class ____(events.FileSystemEventHandler): EVENTS_WATCHED = ( events.EVENT_TYPE_CREATED, events.EVENT_TYPE_DELETED, events.EVENT_TYPE_MODIFIED, events.EVENT_TYPE_MOVED, ) def dispatch(self, event: events.FileSystemEvent) -> None: if event.event_type in self.EVENTS_WA...
EventHandler
python
pyca__cryptography
src/cryptography/x509/ocsp.py
{ "start": 662, "end": 1172 }
class ____(utils.Enum): SUCCESSFUL = 0 MALFORMED_REQUEST = 1 INTERNAL_ERROR = 2 TRY_LATER = 3 SIG_REQUIRED = 5 UNAUTHORIZED = 6 _ALLOWED_HASHES = ( hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512, ) def _verify_algorithm(algorithm: hashes.HashAlgor...
OCSPResponseStatus
python
spack__spack
lib/spack/spack/util/prefix.py
{ "start": 244, "end": 2238 }
class ____(str): """This class represents an installation prefix, but provides useful attributes for referring to directories inside the prefix. Attributes of this object are created on the fly when you request them, so any of the following are valid: >>> prefix = Prefix("/usr") >>> prefix.bin...
Prefix
python
scipy__scipy
scipy/interpolate/tests/test_fitpack2.py
{ "start": 39395, "end": 50425 }
class ____: def test_defaults(self): x = array([1,2,3,4,5]) y = array([1,2,3,4,5]) z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]]) lut = RectBivariateSpline(x,y,z) assert_array_almost_equal(lut(x,y),z) def test_evaluate(self): x = array([...
TestRectBivariateSpline
python
getsentry__sentry
src/sentry/search/events/builder/discover.py
{ "start": 18678, "end": 20832 }
class ____(DiscoverQueryBuilder): base_function_acl = ["array_join", "histogram", "spans_histogram"] def __init__( self, num_buckets: int, histogram_column: str, histogram_rows: int | None, histogram_params: HistogramParams, key_column: str | None, field_...
HistogramQueryBuilder
python
pallets__quart
examples/api/src/api/__init__.py
{ "start": 555, "end": 791 }
class ____(TodoIn): id: int @app.post("/todos/") @validate_request(TodoIn) @validate_response(Todo) async def create_todo(data: Todo) -> Todo: return Todo(id=1, task=data.task, due=data.due) def run() -> None: app.run()
Todo
python
mlflow__mlflow
mlflow/models/resources.py
{ "start": 6262, "end": 6936 }
class ____(DatabricksResource): """ Define a Databricks Genie Space to serve a model. Args: genie_space_id (str): The genie space id on_behalf_of_user (Optional[bool]): If True, the resource is accessed with with the permission of the invoker of the model in the serving endpoint. If...
DatabricksGenieSpace
python
django__django
django/core/serializers/xml_serializer.py
{ "start": 18171, "end": 18620 }
class ____(DefusedXmlException): """Resolving an external reference is forbidden.""" def __init__(self, context, base, sysid, pubid): super().__init__() self.context = context self.base = base self.sysid = sysid self.pubid = pubid def __str__(self): tpl = "E...
ExternalReferenceForbidden
python
wandb__wandb
wandb/sdk/artifacts/storage_handlers/http_handler.py
{ "start": 2232, "end": 4624 }
class ____(StorageHandler): _scheme: str _cache: ArtifactFileCache _session: requests.Session def __init__(self, session: requests.Session, scheme: str = "http") -> None: self._scheme = scheme self._cache = get_artifact_file_cache() self._session = session def can_handle(se...
HTTPHandler
python
django__django
tests/distinct_on_fields/models.py
{ "start": 1014, "end": 1221 }
class ____(models.Model): staff = models.ForeignKey(Staff, models.CASCADE) tag = models.ForeignKey(Tag, models.CASCADE) def __str__(self): return "%s -> %s" % (self.tag, self.staff)
StaffTag
python
apache__airflow
providers/microsoft/mssql/src/airflow/providers/microsoft/mssql/hooks/mssql.py
{ "start": 1265, "end": 5447 }
class ____(DbApiHook): """ Interact with Microsoft SQL Server. :param args: passed to DBApiHook :param sqlalchemy_scheme: Scheme sqlalchemy connection. Default is ``mssql+pymssql`` Only used for ``get_sqlalchemy_engine`` and ``get_sqlalchemy_connection`` methods. :param kwargs: passed to DbA...
MsSqlHook
python
PrefectHQ__prefect
src/integrations/prefect-dask/prefect_dask/task_runners.py
{ "start": 3532, "end": 17501 }
class ____(TaskRunner): """ A parallel task_runner that submits tasks to the `dask.distributed` scheduler. By default a temporary `distributed.LocalCluster` is created (and subsequently torn down) within the `start()` contextmanager. To use a different cluster class (e.g. [`dask_kubernetes.KubeC...
DaskTaskRunner
python
kamyu104__LeetCode-Solutions
Python/happy-number.py
{ "start": 70, "end": 443 }
class ____(object): # @param {integer} n # @return {boolean} def isHappy(self, n): lookup = {} while n != 1 and n not in lookup: lookup[n] = True n = self.nextNumber(n) return n == 1 def nextNumber(self, n): new = 0 for char in str(n): ...
Solution
python
ethereum__web3.py
web3/types.py
{ "start": 13885, "end": 14043 }
class ____(TypedDict): blockStateCalls: Sequence[BlockStateCallV1] validation: NotRequired[bool] traceTransfers: NotRequired[bool]
SimulateV1Payload
python
dask__distributed
distributed/comm/ucx.py
{ "start": 899, "end": 1633 }
class ____(BaseListener): prefix = UCXConnector.prefix comm_class = UCXConnector.comm_class encrypted = UCXConnector.encrypted def __init__( self, address: str, comm_handler: Callable[[UCX], Awaitable[None]] | None = None, deserialize: bool = False, allow_offload...
UCXListener
python
apache__airflow
providers/vertica/tests/unit/vertica/hooks/test_vertica.py
{ "start": 4779, "end": 7527 }
class ____: def setup_method(self): self.cur = mock.MagicMock(rowcount=0) self.cur.nextset.side_effect = [None] self.conn = mock.MagicMock() self.conn.cursor.return_value = self.cur conn = self.conn class UnitTestVerticaHook(VerticaHook): conn_name_attr =...
TestVerticaHook
python
sqlalchemy__sqlalchemy
examples/inheritance/joined.py
{ "start": 1399, "end": 1894 }
class ____(Person): __tablename__ = "engineer" id: Mapped[intpk] = mapped_column(ForeignKey("person.id")) status: Mapped[str50] engineer_name: Mapped[str50] primary_language: Mapped[str50] __mapper_args__ = {"polymorphic_identity": "engineer"} def __repr__(self): return ( ...
Engineer
python
pytorch__pytorch
.github/scripts/runner_determinator.py
{ "start": 3455, "end": 3603 }
class ____(NamedTuple): """ Settings for the experiments that can be opted into. """ experiments: dict[str, Experiment] = {}
Settings
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategies.py
{ "start": 18317, "end": 19373 }
class ____(LoaderStrategy): """LoaderStratgies which deal with related objects.""" __slots__ = "mapper", "target", "uselist", "entity" def __init__(self, parent, strategy_key): super().__init__(parent, strategy_key) self.mapper = self.parent_property.mapper self.entity = self.paren...
_AbstractRelationshipLoader
python
google__pytype
pytype/rewrite/flow/frame_base_test.py
{ "start": 722, "end": 1115 }
class ____(frame_base.FrameBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.seen_opcodes = [] # pylint: disable=invalid-name def byte_FAKE_OP(self, op): self.seen_opcodes.append(('FAKE_OP', op.index)) def byte_FAKE_OP_NO_NEXT(self, op): self.seen_opcodes.appe...
TestFrame
python
getsentry__sentry
tests/sentry/incidents/test_charts.py
{ "start": 5492, "end": 10759 }
class ____(BaseMetricIssueTest): @freeze_time(frozen_time) @with_feature("organizations:incidents") def test_get_incidents_from_detector(self) -> None: self.create_detector() # dummy so detector ID != alert rule ID detector = self.create_detector(project=self.project) alert_rule = s...
FetchOpenPeriodsTest
python
getsentry__sentry
src/sentry/grouping/variants.py
{ "start": 5764, "end": 6640 }
class ____(BaseVariant): """A user-defined custom fingerprint.""" type = "custom_fingerprint" def __init__(self, fingerprint: list[str], fingerprint_info: FingerprintInfo): self.values = fingerprint self.fingerprint_info = fingerprint_info self.is_built_in = fingerprint_info.get("m...
CustomFingerprintVariant
python
facebook__pyre-check
tools/pysa_integration_tests/annotations.py
{ "start": 462, "end": 766 }
class ____: def __new__( cls, *, code: int, line: Optional[int] = None, task: Optional[str] = None, currently_found: bool = True, ) -> "ExpectIssue": return super().__new__(cls) def __call__(self, f: T) -> T: return f
ExpectIssue
python
ansible__ansible
test/integration/targets/callback-dispatch/callback_plugins/oops_always_enabled.py
{ "start": 118, "end": 656 }
class ____(CallbackBase): call_count: t.ClassVar[int] = 0 def v2_runner_on_ok(self, *args, **kwargs) -> None: print(f"hello from ALWAYS ENABLED v2_runner_on_ok {args=} {kwargs=}") CallbackModule.call_count += 1 def v2_playbook_on_stats(self, stats): print('hello from ALWAYS ENABLE...
CallbackModule
python
PyCQA__pylint
tests/functional/u/unsupported/unsupported_version_for_final.py
{ "start": 611, "end": 794 }
class ____: @myfinal # [using-final-decorator-in-unsupported-version] def my_method(self): pass @typing.final # [using-final-decorator-in-unsupported-version]
MyClass2
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_v2_func_graphs.py
{ "start": 1618, "end": 1784 }
class ____(ControlFlowFuncGraph): """FuncGraph for branches of tf.cond(). This is used to distinguish cond branches from other functions. """
CondBranchFuncGraph
python
doocs__leetcode
solution/0600-0699/0630.Course Schedule III/Solution.py
{ "start": 0, "end": 335 }
class ____: def scheduleCourse(self, courses: List[List[int]]) -> int: courses.sort(key=lambda x: x[1]) pq = [] s = 0 for duration, last in courses: heappush(pq, -duration) s += duration while s > last: s += heappop(pq) retu...
Solution
python
huggingface__transformers
src/transformers/models/ovis2/modeling_ovis2.py
{ "start": 27849, "end": 33673 }
class ____(Ovis2PreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = {} _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} def __init__(self, config: Ovis2Config): super().__init__(config) self.model = Ovis2Model(config) self.lm_head =...
Ovis2ForConditionalGeneration
python
kamyu104__LeetCode-Solutions
Python/apply-discount-every-n-orders.py
{ "start": 131, "end": 899 }
class ____(object): def __init__(self, n, discount, products, prices): """ :type n: int :type discount: int :type products: List[int] :type prices: List[int] """ self.__n = n self.__discount = discount self.__curr = 0 self.__lookup = {...
Cashier
python
walkccc__LeetCode
solutions/398. Random Pick Index/398.py
{ "start": 0, "end": 298 }
class ____: def __init__(self, nums: list[int]): self.nums = nums def pick(self, target: int) -> int: ans = -1 rng = 0 for i, num in enumerate(self.nums): if num == target: rng += 1 if random.randint(0, rng - 1) == 0: ans = i return ans
Solution
python
kamyu104__LeetCode-Solutions
Python/design-a-number-container-system.py
{ "start": 140, "end": 939 }
class ____(object): def __init__(self): self.__idx_to_num = {} self.__num_to_idxs = collections.defaultdict(SortedList) def change(self, index, number): """ :type index: int :type number: int :rtype: None """ if index in self.__idx_to_num: ...
NumberContainers
python
ray-project__ray
python/ray/train/tests/lightning_test_utils.py
{ "start": 3015, "end": 3677 }
class ____(pl.LightningDataModule): def __init__(self, batch_size: int = 8, dataset_size: int = 256) -> None: super().__init__() self.batch_size = batch_size self.train_data = torch.randn(dataset_size, 32) self.val_data = torch.randn(dataset_size, 32) self.test_data = torch.r...
DummyDataModule
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 733789, "end": 734454 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("created_at", "key", "read_only", "title", "verified") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) key = sgqlc...
DeployKey
python
mlflow__mlflow
dev/build.py
{ "start": 162, "end": 3094 }
class ____: # name of the package on PyPI. pypi_name: str # type of the package, one of "dev", "skinny", "tracing", "release" type: str # path to the package relative to the root of the repository build_path: str DEV = Package("mlflow", "dev", ".") RELEASE = Package("mlflow", "release", ".") S...
Package
python
allegroai__clearml
clearml/backend_interface/base.py
{ "start": 615, "end": 6315 }
class ____(SessionInterface): """Base class for a backend manager class""" _default_session = None _num_retry_warning_display = 1 _offline_mode = ENV_OFFLINE_MODE.get() _JSON_EXCEPTION = ( (jsonschema.ValidationError, requests.exceptions.InvalidJSONError) if hasattr(requests.excepti...
InterfaceBase
python
walkccc__LeetCode
solutions/1568. Minimum Number of Days to Disconnect Island/1568.py
{ "start": 0, "end": 1132 }
class ____: def minDays(self, grid: list[list[int]]) -> int: DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) def dfs(grid: list[list[int]], i: int, j: int, seen: set[tuple[int, int]]): seen.add((i, j)) for dx, dy in DIRS: x = i + dx y = j + dy ...
Solution
python
simplejson__simplejson
simplejson/tests/test_for_json.py
{ "start": 293, "end": 372 }
class ____(dict): def for_json(self): return {'alpha': 1}
DictForJson
python
kamyu104__LeetCode-Solutions
Python/subtree-removal-game-with-fibonacci-tree.py
{ "start": 1072, "end": 1465 }
class ____(object): def findGameWinner(self, n): """ :type n: int :rtype: bool """ grundy = [0, 1] # 0-indexed for i in xrange(2, n): grundy[i%2] = (grundy[(i-1)%2]+1)^(grundy[(i-2)%2]+1) # colon principle, replace the branches by a non-branching stalk ...
Solution2
python
celery__celery
celery/exceptions.py
{ "start": 7529, "end": 7633 }
class ____(TaskError): """The task has invalid data or ain't properly constructed."""
InvalidTaskError
python
Netflix__metaflow
metaflow/_vendor/packaging/_parser.py
{ "start": 1148, "end": 9399 }
class ____(NamedTuple): name: str url: str extras: List[str] specifier: str marker: Optional[MarkerList] # -------------------------------------------------------------------------------------- # Recursive descent parser for dependency specifier # --------------------------------------------------...
ParsedRequirement
python
imageio__imageio
tests/test_core.py
{ "start": 849, "end": 939 }
class ____: def __init__(self, request): """Can read anything"""
EpicDummyPlugin
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 52431, "end": 58562 }
class ____(LukePreTrainedModel): def __init__(self, config): super().__init__(config) self.luke = LukeModel(config) self.num_labels = config.num_labels self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) ...
LukeForEntityClassification
python
joke2k__faker
faker/providers/job/vi_VN/__init__.py
{ "start": 41, "end": 1950 }
class ____(JobProvider): """Translated from Super class""" jobs = ( # Information technology field "Lập trình viên", "Kỹ sư phần mềm", "Kiến trúc sư phần mềm", "Nhà phân tích dữ liệu", "Chuyên viên bảo mật", "Tester", "DevOps Engineer", "P...
Provider
python
run-llama__llama_index
llama-index-core/llama_index/core/agent/react/types.py
{ "start": 867, "end": 1254 }
class ____(BaseReasoningStep): """Observation reasoning step.""" observation: str return_direct: bool = False def get_content(self) -> str: """Get content.""" return f"Observation: {self.observation}" @property def is_done(self) -> bool: """Is the reasoning step the la...
ObservationReasoningStep
python
psf__black
src/black/mode.py
{ "start": 673, "end": 6727 }
class ____(Enum): F_STRINGS = 2 NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 # The following two feature-flags are mutually exclusive, and exactly one should be # set for every version of python. ASYNC_IDENTIFIERS = 6 ASYNC_KEYWORDS = 7 ASSIGNMENT_EXPR...
Feature
python
langchain-ai__langchain
libs/partners/prompty/langchain_prompty/core.py
{ "start": 247, "end": 346 }
class ____(BaseModel, Generic[T]): """Simple model for a single item.""" item: T
SimpleModel
python
django__django
tests/admin_inlines/models.py
{ "start": 521, "end": 887 }
class ____(models.Model): name = models.CharField(max_length=50) teacher = models.ForeignKey(Teacher, models.CASCADE) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() parent = GenericForeignKey() def __str__(self): return "I am %s,...
Child
python
huggingface__transformers
src/transformers/models/apertus/modular_apertus.py
{ "start": 13245, "end": 13288 }
class ____(LlamaModel): pass
ApertusModel
python
joke2k__faker
faker/providers/internet/el_GR/__init__.py
{ "start": 108, "end": 2284 }
class ____(InternetProvider): free_email_domains = ( "hol.gr", "gmail.com", "hotmail.gr", "yahoo.gr", "googlemail.gr", "otenet.gr", "forthnet.gr", ) tlds = ("com", "com", "com", "net", "org", "gr", "gr", "gr") @slugify_domain def user_name(sel...
Provider
python
mahmoud__glom
glom/matching.py
{ "start": 28455, "end": 35174 }
class ____: """Check objects are used to make assertions about the target data, and either pass through the data or raise exceptions if there is a problem. If any check condition fails, a :class:`~glom.CheckError` is raised. Args: spec: a sub-spec to extract the data to which other asserti...
Check
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 674929, "end": 675671 }
class ____(sgqlc.types.relay.Connection): """The connection type for IssueComment.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("IssueCommentEdge"), graphql_name="edges") """A list of edges.""" node...
IssueCommentConnection
python
plotly__plotly.py
plotly/graph_objs/isosurface/caps/_y.py
{ "start": 233, "end": 4043 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "isosurface.caps" _path_str = "isosurface.caps.y" _valid_props = {"fill", "show"} @property def fill(self): """ Sets the fill ratio of the `caps`. The default fill value of the `caps` is 1 meaning that they are entirely...
Y
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 255563, "end": 257097 }
class ____(unittest.TestCase): def testSendAndRecvFds(self): def close_pipes(pipes): for fd1, fd2 in pipes: os.close(fd1) os.close(fd2) def close_fds(fds): for fd in fds: os.close(fd) # send 10 file descriptors ...
SendRecvFdsTests
python
pandas-dev__pandas
asv_bench/benchmarks/boolean.py
{ "start": 42, "end": 739 }
class ____: def setup(self): N = 10_000 left, right, lmask, rmask = np.random.randint(0, 2, size=(4, N)).astype("bool") self.left = pd.arrays.BooleanArray(left, lmask) self.right = pd.arrays.BooleanArray(right, rmask) def time_or_scalar(self): self.left | True se...
TimeLogicalOps
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock-iii.py
{ "start": 1144, "end": 2193 }
class ____(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): min_price, max_profit_from_left, max_profits_from_left = \ float("inf"), 0, [] for price in prices: min_price = min(min_price, price) max_profit_from_l...
Solution3
python
getsentry__sentry
tests/sentry/users/api/bases/test_user.py
{ "start": 544, "end": 3767 }
class ____(DRFPermissionTestCase): user_permission = UserPermission() def setUp(self) -> None: super().setUp() self.normal_user = self.create_user() def test_allows_none_user_as_anonymous(self) -> None: assert self.user_permission.has_object_permission(self.make_request(), APIView(...
UserPermissionTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 60069, "end": 60369 }
class ____(AliasedReturnsRows): element: FromClause @util.ro_non_memoized_property def description(self) -> str: name = self.name if isinstance(name, _anonymous_label): return f"Anonymous alias of {self.element.description}" return name
FromClauseAlias
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/exc.py
{ "start": 4209, "end": 5520 }
class ____(sa_exc.InvalidRequestError): """A refresh operation failed to retrieve the database row corresponding to an object's known primary key identity. A refresh operation proceeds when an expired attribute is accessed on an object, or when :meth:`_query.Query.get` is used to retrieve an object...
ObjectDeletedError
python
pallets__werkzeug
src/werkzeug/local.py
{ "start": 11366, "end": 12345 }
class ____(_ProxyLookup): """Look up an augmented assignment method on a proxied object. The method is wrapped to return the proxy instead of the object. """ __slots__ = () def __init__( self, f: t.Callable[..., t.Any] | None = None, fallback: t.Callable[[LocalProxy[t.Any]]...
_ProxyIOp
python
django__django
django/contrib/contenttypes/fields.py
{ "start": 11806, "end": 12342 }
class ____(ForeignObjectRel): """ Used by GenericRelation to store information about the relation. """ def __init__( self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, ): super().__init__( field, ...
GenericRel
python
numba__numba
numba/core/types/misc.py
{ "start": 10263, "end": 11977 }
class ____(Callable, Opaque): """ The type of the jitted class (not instance). When the type of a class is called, its constructor is invoked. """ mutable = True name_prefix = "jitclass" instance_type_class = ClassInstanceType def __init__(self, class_def, ctor_template_cls, struct, ji...
ClassType
python
django__django
tests/db_functions/tests.py
{ "start": 251, "end": 303 }
class ____(Upper): bilateral = True
UpperBilateral
python
huggingface__transformers
tests/models/whisper/test_modeling_whisper.py
{ "start": 6279, "end": 13653 }
class ____: def __init__( self, parent, batch_size=3, # need batch_size != num_hidden_layers seq_length=60, is_training=True, use_labels=False, vocab_size=200, hidden_size=16, num_hidden_layers=2, num_attention_heads=4, input_c...
WhisperModelTester
python
pytest-dev__pytest-asyncio
docs/how-to-guides/multiple_loops_example.py
{ "start": 184, "end": 638 }
class ____(DefaultEventLoopPolicy): pass @pytest.fixture( scope="session", params=( CustomEventLoopPolicy(), CustomEventLoopPolicy(), ), ) def event_loop_policy(request): return request.param @pytest.mark.asyncio @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def...
CustomEventLoopPolicy
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_materialization_health.py
{ "start": 14678, "end": 14835 }
class ____: num_missing_partitions: int total_num_partitions: int @whitelist_for_serdes @record.record
AssetHealthMaterializationHealthyPartitionedMeta
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 1506, "end": 27311 }
class ____: def test_ctor(self, xp): # knots should be an ordered 1-D array of finite real numbers assert_raises((TypeError, ValueError), BSpline, **dict(t=[1, 1.j], c=[1.], k=0)) with np.errstate(invalid='ignore'): assert_raises(ValueError, BSpline, **dict(t=[1,...
TestBSpline
python
python-poetry__poetry
src/poetry/console/commands/show.py
{ "start": 1249, "end": 23754 }
class ____(GroupCommand, EnvCommand): name = "show" description = "Shows information about packages." arguments: ClassVar[list[Argument]] = [ argument("package", "The package to inspect", optional=True) ] options: ClassVar[list[Option]] = [ *GroupCommand._group_dependency_options(),...
ShowCommand
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/execution_result.py
{ "start": 882, "end": 9874 }
class ____(ABC): @property @abstractmethod def job_def(self) -> JobDefinition: ... @property @abstractmethod def dagster_run(self) -> DagsterRun: ... @property @abstractmethod def all_events(self) -> Sequence[DagsterEvent]: ... @property @abstractmethod def run_id(self...
ExecutionResult
python
astral-sh__uv
scripts/scenarios/generate.py
{ "start": 1926, "end": 11494 }
class ____(StrEnum): install = auto() compile = auto() lock = auto() def template_file(self) -> Path: return TEMPLATES / f"{self.name}.mustache" def test_file(self) -> Path: match self.value: case TemplateKind.install: return TESTS / "pip_install_scenari...
TemplateKind
python
tensorflow__tensorflow
tensorflow/cc/saved_model/testdata/generate_saved_models.py
{ "start": 2338, "end": 2479 }
class ____(module.Module): def __init__(self): super(CyclicModule, self).__init__() self.child = ReferencesParent(self)
CyclicModule
python
protocolbuffers__protobuf
python/google/protobuf/internal/testing_refleaks.py
{ "start": 681, "end": 1186 }
class ____(unittest.TestResult): """A TestResult which forwards events to a parent object, except for Skips.""" def __init__(self, parent_result): unittest.TestResult.__init__(self) self.parent_result = parent_result def addError(self, test, error): self.parent_result.addError(test, error) def ad...
LocalTestResult
python
tensorflow__tensorflow
tensorflow/python/tools/saved_model_cli_test.py
{ "start": 2147, "end": 47212 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): super(SavedModelCLITestCase, self).setUp() if platform.system() == 'Windows': self.skipTest('Skipping failing tests on Windows.') def _save_dummy_model(self, get_ops_mock): class DummyModel(autotrackable.AutoTrackable): ""...
SavedModelCLITestCase
python
astropy__astropy
astropy/modeling/tests/test_parameters.py
{ "start": 4561, "end": 4680 }
class ____(Model): m1a = Parameter(default=1.0) m1b = Parameter(default=5.0) def evaluate(): pass
M1
python
modin-project__modin
modin/config/envvars.py
{ "start": 28646, "end": 28881 }
class ____(EnvironmentVariable, type=ExactStr): """Allows to select a library that we will use for testing performance.""" varname = "MODIN_ASV_USE_IMPL" choices = ("modin", "pandas") default = "modin"
AsvImplementation
python
ansible__ansible
test/integration/targets/templating/filter_plugins/broken_filter.py
{ "start": 37, "end": 134 }
class ____: @property def accept_args_markers(self): raise Exception('boom')
Broken