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
dagster-io__dagster
python_modules/dagster/dagster/_module_alias_map.py
{ "start": 2821, "end": 3349 }
class ____(Loader): def __init__(self, alias: str, base_spec: ModuleSpec): self.alias = alias self.base_spec = base_spec def exec_module(self, _module: ModuleType) -> None: # pyright: ignore[reportIncompatibleMethodOverride] base_module = importlib.import_module(self.base_spec.name) ...
AliasedModuleLoader
python
PrefectHQ__prefect
tests/client/test_prefect_client.py
{ "start": 72543, "end": 78763 }
class ____: async def test_read_work_pools(self, prefect_client): # default pool shows up when running the test class or individuals, but not when running # test as a module pools = await prefect_client.read_work_pools() existing_name = set([p.name for p in pools]) existing_i...
TestWorkPools
python
huggingface__transformers
src/transformers/models/cwm/modeling_cwm.py
{ "start": 19056, "end": 22130 }
class ____(CwmPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = CwmModel(...
CwmForCausalLM
python
PrefectHQ__prefect
src/integrations/prefect-databricks/tests/test_rest.py
{ "start": 1464, "end": 2688 }
class ____(BaseModel): model_config = ConfigDict(extra="allow", frozen=True) some_string: str some_int: int another_base_model: TestAnotherBaseModel other_base_models: List[TestAnotherBaseModel] def test_serialize_model(): expected = { "base_model": { "some_string": "abc",...
TestBaseModel
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instance.py
{ "start": 2362, "end": 3428 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.String) daemonStatus = graphene.Field( graphene.NonNull(GrapheneDaemonStatus), daemon_type=graphene.Argument(graphene.String), ) allDaemonStatuses = non_null_list(GrapheneDaemonStatus) class Meta: name = "Daemon...
GrapheneDaemonHealth
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/named_tuples.py
{ "start": 1776, "end": 1975 }
class ____(NamedTuple): benign: int bad: str def issue_with_named_tuple_with_tainted_attribute(): NamedTupleWithTaintedAttribute(bad=_test_source(), benign=1)
NamedTupleWithTaintedAttribute
python
hyperopt__hyperopt
hyperopt/rdists.py
{ "start": 3781, "end": 5538 }
class ____(quniform_gen): """Stats for Y = q * round(e^X / q) where X ~ U(low, high).""" # -- not inheriting from scipy.stats.rv_discrete # because I don't understand the design of those rv classes def __init__(self, low, high, q): low, high = list(map(float, (low, high))) elow = np...
qloguniform_gen
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 1551, "end": 3183 }
class ____(TestCase): def test_copies(self): A = np.array([[1, 2], [3, 4]]) Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) assert_equal(np.resize(A, (2, 4)), Ar1) Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(np.resize(A, (4, 2)), Ar2) Ar3 = np.array([...
TestResize
python
kamyu104__LeetCode-Solutions
Python/root-equals-sum-of-children.py
{ "start": 166, "end": 361 }
class ____(object): def checkTree(self, root): """ :type root: Optional[TreeNode] :rtype: bool """ return root.val == root.left.val+root.right.val
Solution
python
pypa__pip
src/pip/_vendor/rich/progress.py
{ "start": 5904, "end": 8721 }
class ____(RawIOBase, BinaryIO): """A reader that tracks progress while it's being read from.""" def __init__( self, handle: BinaryIO, progress: "Progress", task: TaskID, close_handle: bool = True, ) -> None: self.handle = handle self.progress = progr...
_Reader
python
mlflow__mlflow
mlflow/store/artifact/hdfs_artifact_repo.py
{ "start": 498, "end": 7986 }
class ____(ArtifactRepository): """ Stores artifacts on HDFS. This repository is used with URIs of the form ``hdfs:/<path>``. The repository can only be used together with the RestStore. """ def __init__( self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | Non...
HdfsArtifactRepository
python
getsentry__sentry
src/sentry/snuba/metrics/query.py
{ "start": 4072, "end": 4276 }
class ____: """ Modelled after snuba_sdk.conditions.Condition """ lhs: MetricField op: Op rhs: int | float | str Groupable = Union[str, Literal["project_id"]]
MetricConditionField
python
python__mypy
mypy/test/testsemanal.py
{ "start": 4716, "end": 6187 }
class ____(DataSuite): required_out_section = True files = ["semanal-typeinfo.test"] def run_case(self, testcase: DataDrivenTestCase) -> None: """Perform a test case.""" try: # Build test case input. src = "\n".join(testcase.input) result = build.build( ...
SemAnalTypeInfoSuite
python
pytorch__pytorch
torch/_export/db/examples/constrain_as_size_example.py
{ "start": 42, "end": 515 }
class ____(torch.nn.Module): """ If the value is not known at tracing time, you can provide hint so that we can trace further. Please look at torch._check APIs. """ def forward(self, x): a = x.item() torch._check(a >= 0) torch._check(a <= 5) return torch.zeros((a, 5)...
ConstrainAsSizeExample
python
joke2k__faker
faker/providers/person/pt_PT/__init__.py
{ "start": 44, "end": 6739 }
class ____(PersonProvider): formats_male = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", ...
Provider
python
mlflow__mlflow
mlflow/anthropic/autolog.py
{ "start": 2099, "end": 5101 }
class ____: """Context manager for handling MLflow spans in both sync and async contexts.""" def __init__(self, original, instance, args, kwargs): self.original = original self.instance = instance self.inputs = construct_full_inputs(original, instance, *args, **kwargs) # These ...
TracingSession
python
protocolbuffers__protobuf
python/google/protobuf/internal/duration_test.py
{ "start": 588, "end": 4008 }
class ____(unittest.TestCase): def test_duration_integer_conversion(self): self.assertEqual(1, duration.to_nanoseconds(duration.from_nanoseconds(1))) self.assertEqual(-1, duration.to_seconds(duration.from_seconds(-1))) self.assertEqual( 123, duration.to_milliseconds(duration.from_milliseconds(123...
DurationTest
python
zarr-developers__zarr-python
src/zarr/core/metadata/v3.py
{ "start": 4833, "end": 5950 }
class ____(TypedDict): """ This class models allowed extra fields in array metadata. They are ignored by Zarr Python. """ must_understand: Literal[False] def check_allowed_extra_field(data: object) -> TypeGuard[AllowedExtraField]: """ Check if the extra field is allowed according to the Z...
AllowedExtraField
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/reflection.py
{ "start": 1317, "end": 24609 }
class ____: """Parses the results of a SHOW CREATE TABLE statement.""" def __init__( self, dialect: MySQLDialect, preparer: MySQLIdentifierPreparer ): self.dialect = dialect self.preparer = preparer self._prep_regexes() def parse( self, show_create: str, charset...
MySQLTableDefinitionParser
python
Textualize__textual
src/textual/scrollbar.py
{ "start": 1203, "end": 1740 }
class ____(ScrollMessage, verbose=True): """Message sent when click and dragging handle.""" __slots__ = ["x", "y", "animate"] def __init__( self, x: float | None = None, y: float | None = None, animate: bool = True, ) -> None: self.x = x self.y = y ...
ScrollTo
python
pdm-project__pdm
src/pdm/models/working_set.py
{ "start": 2165, "end": 3367 }
class ____(Mapping[str, im.Distribution]): """A dictionary of currently installed distributions""" def __init__(self, paths: list[str] | None = None, shared_paths: list[str] | None = None) -> None: if paths is None: paths = sys.path if shared_paths is None: shared_paths ...
WorkingSet
python
pytoolz__cytoolz
cytoolz/tests/test_dicttoolz.py
{ "start": 8054, "end": 9047 }
class ____(TestDict): """Test CustomMapping as input and factory Class attributes: D: callable that inputs a dict and creates or returns a MutableMapping kw: kwargs dict to specify "factory" keyword (if applicable) """ D = CustomMapping kw = {'factory': lambda: CustomMapping()} de...
TestCustomMapping
python
Textualize__textual
tests/snapshot_tests/language_snippets.py
{ "start": 971, "end": 1143 }
class ____: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclasses must implement this method.")
Animal
python
pandas-dev__pandas
asv_bench/benchmarks/indexing.py
{ "start": 10655, "end": 11050 }
class ____: def setup(self): dti = date_range("2016-01-01", periods=10000, tz="US/Pacific") dti2 = dti.tz_convert("UTC") self.dti = dti self.dti2 = dti2 def time_get_indexer_mismatched_tz(self): # reached via e.g. # ser = Series(range(len(dti)), index=dti) ...
DatetimeIndexIndexing
python
readthedocs__readthedocs.org
readthedocs/integrations/models.py
{ "start": 7262, "end": 9677 }
class ____(models.QuerySet): """ Return a subclass of Integration, based on the integration type. .. note:: This doesn't affect queries currently, only fetching of an object """ def _get_subclass(self, integration_type): # Build a mapping of integration_type -> class dynamically ...
IntegrationQuerySet
python
python-openxml__python-docx
tests/opc/test_package.py
{ "start": 10615, "end": 17017 }
class ____: def it_can_unmarshal_from_a_pkg_reader( self, pkg_reader_, pkg_, part_factory_, _unmarshal_parts_, _unmarshal_relationships_, parts_dict_, ): _unmarshal_parts_.return_value = parts_dict_ Unmarshaller.unmarshal(pkg_reader_, pkg_,...
DescribeUnmarshaller
python
pypa__pipenv
pipenv/patched/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 9287, "end": 11523 }
class ____(_InstallRequirementBackedCandidate): is_editable = False def __init__( self, link: Link, template: InstallRequirement, factory: "Factory", name: Optional[NormalizedName] = None, version: Optional[Version] = None, ) -> None: source_link = li...
LinkCandidate
python
walkccc__LeetCode
solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py
{ "start": 0, "end": 850 }
class ____: # Same as 3029. Minimum Time to Revert Word to Initial State I def minimumTimeToInitialState(self, word: str, k: int) -> int: n = len(word) maxOps = (n - 1) // k + 1 z = self._zFunction(word) for ans in range(1, maxOps): if z[ans * k] >= n - ans * k: return ans return...
Solution
python
pandas-dev__pandas
pandas/tests/indexes/period/test_indexing.py
{ "start": 24667, "end": 25751 }
class ____: @pytest.mark.parametrize("freq", ["h", "D"]) def test_get_value_datetime_hourly(self, freq): # get_loc and get_value should treat datetime objects symmetrically # TODO: this test used to test get_value, which is removed in 2.0. # should this test be moved somewhere, or is wh...
TestGetValue
python
sqlalchemy__sqlalchemy
examples/dogpile_caching/model.py
{ "start": 1464, "end": 2132 }
class ____(Base): __tablename__ = "address" id = Column(Integer, primary_key=True) person_id = Column(Integer, ForeignKey("person.id"), nullable=False) street = Column(String(200), nullable=False) postal_code_id = Column(Integer, ForeignKey("postal_code.id")) postal_code = relationship(PostalCo...
Address
python
langchain-ai__langchain
libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py
{ "start": 697, "end": 12413 }
class ____(BaseChatModel): """Fake model for testing middleware.""" def _generate( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> ChatResult: """Top Level call""" ...
FakeToolCallingModel
python
python-openxml__python-docx
tests/test_table.py
{ "start": 11361, "end": 18978 }
class ____: """Unit-test suite for `docx.table._Cell` objects.""" @pytest.mark.parametrize( ("tc_cxml", "expected_value"), [ ("w:tc", 1), ("w:tc/w:tcPr", 1), ("w:tc/w:tcPr/w:gridSpan{w:val=1}", 1), ("w:tc/w:tcPr/w:gridSpan{w:val=4}", 4), ]...
Describe_Cell
python
aio-libs__aiohttp
tests/test_web_exceptions.py
{ "start": 8877, "end": 10398 }
class ____: async def test_ctor(self) -> None: resp = web.HTTPMethodNotAllowed( "GET", ["POST", "PUT"], headers={"X-Custom": "value"}, reason="Unsupported", text="text", content_type="custom", ) assert resp.method == "GE...
TestHTTPMethodNotAllowed
python
ray-project__ray
python/ray/serve/_private/utils.py
{ "start": 2093, "end": 2130 }
class ____(Enum): VALUE = 1
DEFAULT
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 1187, "end": 1258 }
class ____(SimpleModel): point = models.PointField(null=True)
Point2D
python
doocs__leetcode
solution/rating.py
{ "start": 90, "end": 6618 }
class ____: def __init__(self, region='CN', retry=3): self.retry = retry self.region = region if region == 'CN': self.url = 'https://leetcode.cn/graphql' self.page_query = Template( "{\n localRankingV2(page:$page) {\nmyRank {\nattendedContestCount\n" ...
Ranking
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_state.py
{ "start": 13251, "end": 13743 }
class ____: """Fakes the DeploymentReplica class.""" def __init__(self, version: DeploymentVersion): self._version = version @property def version(self): return self._version def update_state(self, state): pass def replica(version: Optional[DeploymentVersion] = None) -> ...
FakeDeploymentReplica
python
python-markdown__markdown
tests/test_syntax/inline/test_code.py
{ "start": 781, "end": 2324 }
class ____(TestCase): def test_code_comments(self): self.assertMarkdownRenders( self.dedent( """ Some code `<!--` that is not HTML `-->` in a paragraph. Some code `<!--` that is not HTML `-->` in a paragraph. ...
TestCode
python
facebook__pyre-check
client/commands/tests/pyre_server_options_test.py
{ "start": 454, "end": 940 }
class ____(frontend_configuration.OpenSource): def __init__(self) -> None: self.configuration = configuration_module.Configuration( global_root=Path("test"), targets=[], relative_local_root="local", ) def get_server_start_command( self, download_if_ne...
FakeFrontendConfiguration
python
django__django
tests/queries/models.py
{ "start": 18418, "end": 18586 }
class ____(models.Model): json_field = models.JSONField(blank=True, null=True) class Meta: required_db_features = {"supports_json_field"}
JSONFieldNullable
python
cherrypy__cherrypy
cherrypy/tutorial/tut05_derived_objects.py
{ "start": 1867, "end": 2605 }
class ____(Page): """Another page app.""" title = 'Another Page' @cherrypy.expose def index(self): """Produce HTTP response body of another page app index URI.""" return ( self.header() + """ <p> And this is the amazing second page! ...
AnotherPage
python
ray-project__ray
python/ray/serve/tests/test_telemetry_1.py
{ "start": 3150, "end": 6176 }
class ____: pass stub_app = Stub.bind() @pytest.mark.skipif(sys.platform == "win32", reason="File path incorrect on Windows.") def test_rest_api(manage_ray_with_telemetry, tmp_dir): """ Check that telemetry works with REST API. """ storage = manage_ray_with_telemetry # Check that REST API ...
Stub
python
kamyu104__LeetCode-Solutions
Python/increasing-triplet-subsequence.py
{ "start": 45, "end": 532 }
class ____(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ min_num, a, b = float("inf"), float("inf"), float("inf") for c in nums: if min_num >= c: min_num = c elif b >= c: ...
Solution
python
neetcode-gh__leetcode
python/0090-subsets-ii.py
{ "start": 0, "end": 614 }
class ____: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() def backtrack(i, subset): if i == len(nums): res.append(subset[::]) return # All subsets that include nums[i] subset.append(num...
Solution
python
tensorflow__tensorflow
tensorflow/tools/docs/generate2_test.py
{ "start": 1948, "end": 3204 }
class ____(googletest.TestCase): @mock.patch.object(generate2, 'tf', fake_tf) def test_end_to_end(self): generate2.MIN_NUM_FILES_EXPECTED = 1 output_dir = pathlib.Path(googletest.GetTempDir())/'output' if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir) genera...
Generate2Test
python
PrefectHQ__prefect
tests/server/orchestration/api/test_block_types.py
{ "start": 17794, "end": 20633 }
class ____: async def test_install_system_block_types(self, client): response = await client.post("/block_types/filter") block_types = parse_obj_as(List[BlockType], response.json()) assert len(block_types) == 0 r = await client.post("/block_types/install_system_block_types") ...
TestSystemBlockTypes
python
huggingface__transformers
src/transformers/models/depth_anything/modeling_depth_anything.py
{ "start": 4936, "end": 6318 }
class ____(nn.Module): """Feature fusion layer, merges feature maps from different stages. Args: config (`[DepthAnythingConfig]`): Model configuration class defining the model architecture. """ def __init__(self, config): super().__init__() self.projection = nn.Con...
DepthAnythingFeatureFusionLayer
python
pytorch__pytorch
torch/_dynamo/guards.py
{ "start": 36049, "end": 36114 }
class ____: code_list: list[str] guard: Guard
GuardCodeList
python
kamyu104__LeetCode-Solutions
Python/guess-the-word.py
{ "start": 67, "end": 708 }
class ____(object): def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] :type master: Master :rtype: None """ possible = range(len(wordlist)) n = 0 while n < 6: count = [collections.Counter(w[i] for w in wordlist) for ...
Solution
python
getsentry__sentry
src/sentry/search/events/types.py
{ "start": 2544, "end": 2752 }
class ____(TypedDict): data: SnubaData meta: EventsMeta SAMPLING_MODES = Literal[ "BEST_EFFORT", "PREFLIGHT", "NORMAL", "HIGHEST_ACCURACY", "HIGHEST_ACCURACY_FLEX_TIME" ] @dataclass
EventsResponse
python
django__django
tests/admin_views/admin.py
{ "start": 24125, "end": 24290 }
class ____(admin.ModelAdmin): list_display = ["id", "name"] list_display_links = ["id"] list_editable = ["name"] list_per_page = 2
UnorderedObjectAdmin
python
PrefectHQ__prefect
src/prefect/blocks/abstract.py
{ "start": 4917, "end": 6085 }
class ____(Block, ABC, Generic[T]): """ Block that represents an entity in an external service that can trigger a long running execution. """ @property def logger(self) -> LoggerOrAdapter: """ Returns a logger based on whether the JobBlock is called from within a flow or...
JobBlock
python
pyca__cryptography
src/cryptography/hazmat/primitives/ciphers/algorithms.py
{ "start": 2697, "end": 3229 }
class ____(CipherAlgorithm): name = "ChaCha20" key_sizes = frozenset([256]) def __init__(self, key: utils.Buffer, nonce: utils.Buffer): self.key = _verify_key_size(self, key) utils._check_byteslike("nonce", nonce) if len(nonce) != 16: raise ValueError("nonce must be 128...
ChaCha20
python
doocs__leetcode
solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution3.py
{ "start": 0, "end": 274 }
class ____: def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: ans = [] x = y = 0 for a, b in zip(A, B): x |= 1 << a y |= 1 << b ans.append((x & y).bit_count()) return ans
Solution
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
{ "start": 737, "end": 807 }
class ____(Test2_C1): def foo(self, attribute): ...
Test2_C2
python
fluentpython__example-code
21-class-metaprog/evaltime.py
{ "start": 75, "end": 402 }
class ____(): print('<[2]> ClassOne body') def __init__(self): print('<[3]> ClassOne.__init__') def __del__(self): print('<[4]> ClassOne.__del__') def method_x(self): print('<[5]> ClassOne.method_x') class ClassTwo(object): print('<[6]> ClassTwo body') @deco_alp...
ClassOne
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 10928, "end": 11289 }
class ____(BiffRecord): """ This record is part of the worksheet/workbook protection. It specifies whether a worksheet or a workbook is protected against modification. Protection is not active, if this record is omitted. """ _REC_ID = 0x0012 def __init__(self, protect): self._r...
ProtectRecord
python
google__jax
jax/_src/core.py
{ "start": 17159, "end": 18308 }
class ____: __slots__ = ["count", "aval", "initial_qdd", "final_qdd"] count: int aval: AbstractValue # these are only useful for jaxpr binders but rather than create a separate # type for those, breaking existing interpreters, we add fields here. initial_qdd : QuasiDynamicData | None final_qdd : QuasiDyn...
Var
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 43080, "end": 43750 }
class ____(PipesContextLoader): """Context loader that reads context from a JSON file on GCS. Args: client (google.cloud.storage.Client): A google.cloud.storage.Client object. """ def __init__(self, client: "GCSClient"): self._client = client @contextmanager def load_context(s...
PipesGCSContextLoader
python
ansible__ansible
test/integration/targets/ansible-test-container/runme.py
{ "start": 25757, "end": 26318 }
class ____(ApplicationError): """An error from executing a subprocess.""" def __init__(self, result: SubprocessResult) -> None: self.result = result message = f'Command `{shlex.join(result.command)}` exited with status: {result.status}' stdout = (result.stdout or '').strip() s...
SubprocessError
python
patrick-kidger__equinox
equinox/_module/_module.py
{ "start": 3743, "end": 4598 }
class ____(eqx.Module): vmap_linear: Callable def __init__(self, ...): self.vmap_linear = eqx.filter_vmap(eqx.nn.Linear(...)) def __call__(self, ...): ... = self.vmap_linear(...) ``` """ def _warn_jax_transformed_function(cls: "_ModuleMeta", x: object) -> None: # not `isinstance`, ju...
MyModule
python
pytorch__pytorch
tools/code_coverage/package/tool/parser/coverage_record.py
{ "start": 73, "end": 409 }
class ____(NamedTuple): filepath: str covered_lines: list[int] uncovered_lines: list[int] | None = None def to_dict(self) -> dict[str, Any]: return { "filepath": self.filepath, "covered_lines": self.covered_lines, "uncovered_lines": self.uncovered_lines, ...
CoverageRecord
python
scrapy__scrapy
tests/test_addons.py
{ "start": 1541, "end": 7307 }
class ____: def test_load_settings(self): settings_dict = { "ADDONS": {"tests.test_addons.SimpleAddon": 0}, } crawler = get_crawler(settings_dict=settings_dict) manager = crawler.addons assert isinstance(manager.addons[0], SimpleAddon) def test_notconfigured(...
TestAddonManager
python
python__mypy
mypy/nodes.py
{ "start": 52487, "end": 52873 }
class ____(Statement): """An expression as a statement, such as print(s).""" __slots__ = ("expr",) __match_args__ = ("expr",) expr: Expression def __init__(self, expr: Expression) -> None: super().__init__() self.expr = expr def accept(self, visitor: StatementVisitor[T]) -> ...
ExpressionStmt
python
walkccc__LeetCode
solutions/2585. Number of Ways to Earn Points/2585-2.py
{ "start": 0, "end": 456 }
class ____: def waysToReachTarget(self, target: int, types: list[list[int]]) -> int: MOD = 1_000_000_007 # dp[j] := the number of ways to earn j points with the types so far dp = [1] + [0] * target for count, mark in types: for j in range(target, -1, -1): for solved in range(1, count + ...
Solution
python
GoogleCloudPlatform__python-docs-samples
firestore/cloud-client/snippets.py
{ "start": 3066, "end": 32749 }
class ____: def __init__(self, name, state, country, capital=False, population=0, regions=[]): self.name = name self.state = state self.country = country self.capital = capital self.population = population self.regions = regions @staticmethod def from_dict(so...
City
python
run-llama__llama_index
llama-index-integrations/postprocessor/llama-index-postprocessor-contextual-rerank/tests/test_contextual_rerank.py
{ "start": 292, "end": 2344 }
class ____(TestCase): def test_contextual_rerank(self): nodes = [ NodeWithScore(node=TextNode(text="the capital of france is paris")), NodeWithScore( node=TextNode(text="the capital of the United States is Washington DC") ), ] exp_rerank_r...
TestContextualRerank
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 18132, "end": 18441 }
class ____(CellEditor): ''' Select cell editor. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) options = List(String, help=""" The list of options to select from. """)
SelectEditor
python
huggingface__transformers
src/transformers/models/glm4/modular_glm4.py
{ "start": 3464, "end": 3510 }
class ____(GlmAttention): pass
Glm4Attention
python
numba__numba
numba/core/caching.py
{ "start": 16087, "end": 16968 }
class ____(CacheImpl): """ Implements the logic to cache CodeLibrary objects. """ _filename_prefix = None # must be overridden def reduce(self, codelib): """ Returns a serialized CodeLibrary """ return codelib.serialize_using_object_code() def rebuild(self, ta...
CodeLibraryCacheImpl
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/models.py
{ "start": 31, "end": 357 }
class ____(models.Model): server_url = models.CharField(max_length=255) handle = models.CharField(max_length=255) secret = models.TextField() issued = models.IntegerField() lifetime = models.IntegerField() assoc_type = models.TextField() def __str__(self): return self.server_url
OpenIDStore
python
huggingface__transformers
tests/models/efficientnet/test_modeling_efficientnet.py
{ "start": 8429, "end": 9417 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return AutoImageProcessor.from_pretrained("google/efficientnet-b7") if is_vision_available() else None @slow def test_inference_image_classification_head(self): model = EfficientNetForImageClassification....
EfficientNetModelIntegrationTest
python
ApeWorX__ape
src/ape/pytest/fixtures.py
{ "start": 18926, "end": 22934 }
class ____(ManagerAccessMixin): supported: bool = True snapshots: SnapshotRegistry = SnapshotRegistry() def __init__( self, config_wrapper: "ConfigWrapper", receipt_capture: "ReceiptCapture", chain_snapshots: Optional[dict] = None, ): self.config_wrapper = config...
IsolationManager
python
getsentry__sentry
tests/acceptance/test_trace_view_from_explore.py
{ "start": 481, "end": 3665 }
class ____(AcceptanceTestCase, TraceTestCase, SnubaTestCase): viewname = "sentry-api-0-organization-events" FEATURES = [ "organizations:visibility-explore-view", "organizations:performance-view", "organizations:trace-spans-format", ] def setUp(self) -> None: super().setU...
TraceViewFromExploreTest
python
tensorflow__tensorflow
tensorflow/python/keras/engine/data_adapter.py
{ "start": 14856, "end": 18336 }
class ____(TensorLikeDataAdapter): """Adapter that handles array-like data without forcing it into memory. This adapter handles array-like datasets that may be too big to fully fit into memory. Specifically, this adapter handles any Python class which implements: `__get_item__`, `__len__`, `shape`, and `dty...
GenericArrayLikeDataAdapter
python
getsentry__sentry
tests/sentry/web/frontend/test_vercel_extension_configuration.py
{ "start": 550, "end": 6302 }
class ____(TestCase): path = "/extensions/vercel/configure/" def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization() with assume_test_silo_mode(SiloMode.REGION): OrganizationMember.objects.create( user_id=self.user.id, o...
VercelExtensionConfigurationTest
python
realpython__materials
inheritance-and-composition/inheritance/productivity.py
{ "start": 0, "end": 306 }
class ____: def track(self, employees, hours): print("Tracking Employee Productivity") print("==============================") for employee in employees: result = employee.work(hours) print(f"{employee.name}: {result}") print("")
ProductivitySystem
python
openai__openai-python
src/openai/types/responses/response_computer_tool_call_output_item.py
{ "start": 639, "end": 1527 }
class ____(BaseModel): id: str """The unique ID of the computer call tool output.""" call_id: str """The ID of the computer tool call that produced the output.""" output: ResponseComputerToolCallOutputScreenshot """A computer screenshot image used with the computer use tool.""" type: Lite...
ResponseComputerToolCallOutputItem
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 17459, "end": 18905 }
class ____(TestCase): @classmethod def setUpTestData(cls): SearchFilterModel.objects.create(title='abc', text='def') SearchFilterModel.objects.create(title='ghi', text='jkl') def test_search_in_annotated_field(self): class SearchListView(generics.ListAPIView): queryset =...
SearchFilterAnnotatedFieldTests
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dlp.py
{ "start": 24936, "end": 25902 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook") def test_update_deidentify_template(self, mock_hook): mock_hook.return_value.update_deidentify_template.return_value = DeidentifyTemplate() operator = CloudDLPUpdateDeidentifyTemplateOperator( templa...
TestCloudDLPUpdateDeidentifyTemplateOperator
python
pyodide__pyodide
src/py/_pyodide/_core_docs.py
{ "start": 15300, "end": 17976 }
class ____(JsProxy, Generic[T]): """A :py:class:`~pyodide.ffi.JsProxy` of a :js:class:`Promise` or some other `thenable <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables>`_ JavaScript object. A JavaScript object is considered to be a :js:class:`Promise`...
JsPromise
python
PyCQA__pylint
tests/functional/i/inconsistent/inconsistent_returns_noreturn.py
{ "start": 1621, "end": 3641 }
class ____: def _no_return_method(self) -> typing.NoReturn: sys.exit(1) def _falsely_no_return_method(self) -> typing.NoReturn: return 1 def _does_return_method(self) -> int: return 1 def bug_pylint_8747(self, s: str) -> int: """Every return is consistent because self....
ClassUnderTest
python
hyperopt__hyperopt
hyperopt/mongoexp.py
{ "start": 21476, "end": 34662 }
class ____(Trials): """Trials maps on to an entire mongo collection. It's basically a wrapper around MongoJobs for now. As a concession to performance, this object permits trial filtering based on the exp_key, but I feel that's a hack. The case of `cmd` is similar-- the exp_key and cmd are semantic...
MongoTrials
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_export.py
{ "start": 15382, "end": 16533 }
class ____(AdminTestMixin, TestCase): fixtures = ["category", "book", "author"] def test_export_filters_by_form_param(self): # issue 1578 author = Author.objects.get(name="Ian Fleming") data = { "format": "0", "author": str(author.id), "ebookresource...
FilteredExportAdminIntegrationTest
python
pytorch__pytorch
torch/jit/frontend.py
{ "start": 22778, "end": 28769 }
class ____(Builder): augassign_map = { ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Mod: "%", ast.BitOr: "|", ast.BitAnd: "&", ast.BitXor: "^", ast.LShift: "<<", ast.RShift: ">>", ast.Pow: "**", } @stati...
StmtBuilder
python
doocs__leetcode
solution/0800-0899/0840.Magic Squares In Grid/Solution.py
{ "start": 0, "end": 1005 }
class ____: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: def check(i: int, j: int) -> int: if i + 3 > m or j + 3 > n: return 0 s = set() row = [0] * 3 col = [0] * 3 a = b = 0 for x in range(i, i + 3): ...
Solution
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 2400, "end": 6972 }
class ____(nn.Module): """This module produces sinusoidal positional embeddings of any length.""" def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None): super().__init__() self.offset = 2 self.embedding_dim = embedding_dim self.padding_idx...
NllbMoeSinusoidalPositionalEmbedding
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_dunder_call.py
{ "start": 1409, "end": 1864 }
class ____(dict): def __init__(self) -> None: super().__init__() self._entry_ids = {} def __setitem__(self, key, entry) -> None: super().__setitem__(key, entry) self._entry_ids.__setitem__(entry.id, entry) self._entry_ids.__delitem__(entry.id) def __delitem__(self, ...
CustomRegistry
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 30153, "end": 30523 }
class ____(BaseDataset): """ Feature: Datasets can use shuffling filter """ def test_shuffle(self): """ Enable shuffle filter """ dset = self.f.create_dataset(make_name(), (20, 30), shuffle=True) self.assertTrue(dset.shuffle) @ut.skipIf('fletcher32' not in h5py.filters.en...
TestCreateShuffle
python
readthedocs__readthedocs.org
readthedocs/builds/views.py
{ "start": 1537, "end": 2664 }
class ____( FilterContextMixin, ProjectSpamMixin, BuildBase, ListView, ): filterset_class = BuildListFilter def _get_versions(self, project): project.versions(manager=INTERNAL).public( user=self.request.user, ) def get_project(self): # Call ``.get_querys...
BuildList
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 77169, "end": 82857 }
class ____(EditTool, Drag, Tap): ''' *toolbar icon*: |line_edit_icon| The LineEditTool allows editing the intersection points of one or more ``Line`` glyphs. Glyphs to be edited are defined via the ``renderers`` property and a renderer for the intersections is set via the ``intersection_renderer`` ...
LineEditTool
python
airbytehq__airbyte
airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py
{ "start": 8876, "end": 9391 }
class ____(IssueWatchers, GeneratorMixin): """ https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-watchers/#api-rest-api-3-issue-issueidorkey-watchers-post """ def generate(self): issues_stream = Issues(authenticator=self._session.auth, domain=self._domain) for ...
IssueWatchersGenerator
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py
{ "start": 810, "end": 6355 }
class ____(HTTPAdapter): invalidating_methods = {"PUT", "PATCH", "DELETE"} def __init__( self, cache: BaseCache | None = None, cache_etags: bool = True, controller_class: type[CacheController] | None = None, serializer: Serializer | None = None, heuristic: BaseHe...
CacheControlAdapter
python
PrefectHQ__prefect
tests/_internal/compatibility/test_async_dispatch.py
{ "start": 6391, "end": 8685 }
class ____: def test_dispatches_to_async_in_async_flow(self): """ Verify that async_dispatch dispatches to async in async flow The test function is sync, but the flow is async, so we should dispatch to the async implementation. """ async def my_afunction() -> str: ...
TestIsInARunContext
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 3091, "end": 8265 }
class ____(TestCase): def count_unique_get_attr_nodes(self, gm, args, expected): subgraph_attr_names = set() for node in gm.graph.nodes: if node.op == "get_attr": subgraph_attr_names.add(node.target) self.assertEqual(len(subgraph_attr_names), expected) def te...
TestInvokeSubgraphCompile
python
scipy__scipy
benchmarks/benchmarks/array_api.py
{ "start": 202, "end": 967 }
class ____(XPBenchmark): def setup(self, backend): def f(x): _ = array_namespace(x) return x super().setup(backend, f) self.x = self.synchronize(self.xp.empty(0)) # Populate @lru_cache and jax.jit. Note that this benefits all backends. self.func(s...
ArrayNamespace
python
doocs__leetcode
solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py
{ "start": 0, "end": 275 }
class ____: def maxDistance(self, colors: List[int]) -> int: ans, n = 0, len(colors) for i in range(n): for j in range(i + 1, n): if colors[i] != colors[j]: ans = max(ans, abs(i - j)) return ans
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 60142, "end": 60492 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional["CollectionsResponse"] = Field(default=None, de...
InlineResponse2003
python
numba__numba
numba/tests/test_complex.py
{ "start": 253, "end": 2657 }
class ____(object): def basic_values(self): reals = [-0.0, +0.0, 1, -1, +1.5, -3.5, float('-inf'), float('+inf')] if sys.platform != 'win32': reals += [float('nan')] return [complex(x, y) for x, y in itertools.product(reals, reals)] def more_values(self): ...
BaseComplexTest
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 55612, "end": 55956 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional[List["Record"]] = Field(default=None, descripti...
InlineResponse20013