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
aimacode__aima-python
text.py
{ "start": 7882, "end": 8326 }
class ____(IRSystem): """A trivial IR system over a small collection of Unix man pages.""" def __init__(self): IRSystem.__init__(self, stopwords="how do i the a of") import os aima_root = os.path.dirname(__file__) mandir = os.path.join(aima_root, 'aima-data/MAN/') man_f...
UnixConsultant
python
fastai__fastai
fastai/data/transforms.py
{ "start": 13784, "end": 14252 }
class ____(Categorize): "Transform of one-hot encoded multi-category that decodes with `vocab`" loss_func,order=BCEWithLogitsLossFlat(),1 def __init__(self, vocab): super().__init__(vocab, sort=vocab==None) self.c = len(vocab) def encodes(self, o): return TensorMultiCategory(tensor(o).fl...
EncodedMultiCategorize
python
openai__openai-python
src/openai/types/beta/chatkit/chat_session_history.py
{ "start": 186, "end": 467 }
class ____(BaseModel): enabled: bool """Indicates if chat history is persisted for the session.""" recent_threads: Optional[int] = None """Number of prior threads surfaced in history views. Defaults to null when all history is retained. """
ChatSessionHistory
python
numpy__numpy
numpy/lib/tests/test_arraypad.py
{ "start": 37287, "end": 42967 }
class ____: def test_check_simple(self): a = np.arange(100) a = np.pad(a, (25, 20), 'symmetric') b = np.array( [24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
TestSymmetric
python
kubernetes-client__python
kubernetes/base/dynamic/exceptions.py
{ "start": 3673, "end": 3763 }
class ____(DynamicApiError): """ 503: StatusServiceUnavailable """
ServiceUnavailableError
python
pytorch__pytorch
torch/_inductor/triton_bundler.py
{ "start": 1687, "end": 1903 }
class ____: """ Collection of artifacts for a particular kernel. """ kernel_hash: str device: int artifacts: list[TritonKernelArtifact] @dataclasses.dataclass(frozen=True)
TritonKernelArtifacts
python
networkx__networkx
networkx/classes/coreviews.py
{ "start": 2124, "end": 2738 }
class ____(AdjacencyView): """An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps. It is a View into a dict-of-dict-of-dict-of-dict data structure. The inner level of dict is read-write. But the outer levels are read-only. See Also ======== AtlasView: View into dict-of-dict ...
MultiAdjacencyView
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-together/llama_index/llms/together/base.py
{ "start": 98, "end": 1209 }
class ____(OpenAILike): """ Together LLM. Examples: `pip install llama-index-llms-together` ```python from llama_index.llms.together import TogetherLLM # set api key in env or in llm # import os # os.environ["TOGETHER_API_KEY"] = "your api key" llm...
TogetherLLM
python
Lightning-AI__lightning
tests/tests_pytorch/tuner/test_scale_batch_size.py
{ "start": 1200, "end": 1507 }
class ____(BoringDataModule): def __init__(self, batch_size): super().__init__() if batch_size is not None: self.batch_size = batch_size def train_dataloader(self): return DataLoader(self.random_train, batch_size=getattr(self, "batch_size", 1))
BatchSizeDataModule
python
facelessuser__pymdown-extensions
tests/test_extensions/test_snippets.py
{ "start": 15565, "end": 16075 }
class ____(util.MdCase): """Test snippet cases with path-like objects.""" extension = [ 'pymdownx.snippets' ] extension_configs = { 'pymdownx.snippets': { 'base_path': _PathLikeExampleObject() } } def test_inline(self): """Test inline.""" s...
TestSnippetsPathLike
python
eth-brownie__brownie
brownie/network/gas/strategies.py
{ "start": 6483, "end": 8091 }
class ____(BlockGasStrategy): """ Block based scaling gas strategy using the GraphQL and the Geth mempool. The yielded gas price is determined by sorting transactions in the mempool according to gas price, and returning the price of the transaction at `position`. This is the same technique used by ...
GethMempoolStrategy
python
fluentpython__example-code-2e
24-class-metaprog/checked/metaclass/checkedlib.py
{ "start": 2070, "end": 3095 }
class ____: def __init__(self, name: str, constructor: Callable) -> None: if not callable(constructor) or constructor is type(None): raise TypeError(f'{name!r} type hint must be callable') self.name = name self.storage_name = '_' + name # <1> self.constructor = construct...
Field
python
weaviate__weaviate-python-client
weaviate/exceptions.py
{ "start": 11855, "end": 12298 }
class ____(WeaviateBaseError): """Is raised when a client method tries to use a new feature with an old Weaviate version.""" def __init__(self, feature: str, current: str, minimum: str) -> None: msg = f"""{feature} is not supported by your connected server's Weaviate version. The current version is {cu...
WeaviateUnsupportedFeatureError
python
hynek__structlog
tests/test_dev.py
{ "start": 22507, "end": 24521 }
class ____: def test_default(self): """ If Rich is present, it's the default. """ assert dev.default_exception_formatter is dev.rich_traceback def test_does_not_blow_up(self, sio): """ We trust Rich to do the right thing, so we just exercise the function ...
TestRichTracebackFormatter
python
huggingface__transformers
examples/modular-transformers/modeling_roberta.py
{ "start": 22484, "end": 24474 }
class ____(PreTrainedModel): config_class = RobertaConfig base_model_prefix = "roberta" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _supports_attention_backend = True _can_record_outputs = { "hidden_states": ...
RobertaPreTrainedModel
python
numba__numba
numba/tests/test_entrypoints.py
{ "start": 347, "end": 509 }
class ____(object): def __init__(self, value): self.value = value def __repr__(self): return '_DummyClass(%f, %f)' % self.value
_DummyClass
python
pypa__warehouse
tests/unit/oidc/models/test_github.py
{ "start": 3206, "end": 28619 }
class ____: @pytest.mark.parametrize("environment", [None, "some_environment"]) def test_lookup_fails_invalid_workflow_ref(self, environment): signed_claims = { "repository": "foo/bar", "job_workflow_ref": ("foo/bar/.github/workflows/.yml@refs/heads/main"), "repositor...
TestGitHubPublisher
python
readthedocs__readthedocs.org
readthedocs/doc_builder/director.py
{ "start": 1501, "end": 33004 }
class ____: """ Encapsulates all the logic to perform a build for user's documentation. This class handles all the VCS commands, setup OS and language (e.g. only Python for now) environment (via virtualenv or conda), installs all the required basic and user packages, and finally execute the build c...
BuildDirector
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/glib2.py
{ "start": 10929, "end": 11394 }
class ____(glib_gresource_base): vars = ['GLIB_COMPILE_RESOURCES'] fun_h = Task.compile_fun_shell( glib_gresource_base.base_cmd + ' --target=${TGT[0].abspath()} --generate-header ${SRC}' ) fun_c = Task.compile_fun_shell( glib_gresource_base.base_cmd + ' --target=${TGT[1].abspath()} --gen...
glib_gresource_source
python
dagster-io__dagster
python_modules/automation/python_modules/automation/automation_tests/dagster_dev_tests/ai_review_tests/python_modules/automation/automation_tests/dagster_dev_tests/ai_review_tests/test_comprehensive.py
{ "start": 37042, "end": 41584 }
class ____: """Comprehensive tests for ai-review-update targeting 80% coverage.""" def test_import_and_basic_structure(self): """Test that command can be imported and has expected structure.""" from automation.dagster_dev.commands.ai_review_update import update_pr assert update_pr is n...
TestAiReviewUpdateComprehensive
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_set_row01.py
{ "start": 315, "end": 1157 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("set_row01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_fil...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 34170, "end": 34613 }
class ____(ChainedAssetSelection): def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: selection = self.child.resolve_inner(asset_graph, allow_missing=allow_missing) return fetch_sinks(asset_graph.asset_dep_graph, selection) def to_s...
SinksAssetSelection
python
apache__thrift
lib/py/src/server/TNonblockingServer.py
{ "start": 1299, "end": 2671 }
class ____(threading.Thread): """Worker is a small helper to process incoming connection.""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): """Process queries from task queue, stop if processor is None.""" while True: ...
Worker
python
huggingface__transformers
src/transformers/models/owlv2/modeling_owlv2.py
{ "start": 13001, "end": 16683 }
class ____(nn.Module): def __init__(self, config: Owlv2VisionConfig): super().__init__() self.patch_size = config.patch_size self.config = config self.embed_dim = config.hidden_size self.class_embedding = nn.Parameter(torch.randn(config.hidden_size)) self.patch_embed...
Owlv2VisionEmbeddings
python
scipy__scipy
scipy/optimize/tests/test_linprog.py
{ "start": 90533, "end": 93693 }
class ____(LinprogRSTests): options = {} def test_cyclic_bland(self): pytest.skip("Intermittent failure acceptable.") def test_nontrivial_problem_with_guess(self): c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, ...
TestLinprogRSCommon
python
django__django
tests/sitemaps_tests/urls/http.py
{ "start": 1633, "end": 1723 }
class ____(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0)
FixedLastmodSitemap
python
pytorch__pytorch
test/test_mps.py
{ "start": 430862, "end": 433284 }
class ____(TestCaseMPS): def test_slicing_with_step(self): # Slicing with step # https://github.com/pytorch/pytorch/issues/78886 x_mps = torch.zeros(10, dtype=torch.float32, device="mps") x_mps[::2] = 1.0 x_cpu = torch.zeros(10, dtype=torch.float32, device="cpu") x_c...
TestGatherScatter
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 7237, "end": 14767 }
class ____(BaseOperator): get_openlineage_facets: list[BaseFacet] = [] def execute(self, context) -> Any: pass def test_default_extraction(): extractor = ExtractorManager().get_extractor_class(OperatorWithoutFailure) assert extractor is DefaultExtractor metadata = extractor(OperatorWitho...
BrokenOperator
python
python__mypy
mypy/report.py
{ "start": 28660, "end": 30442 }
class ____(AbstractXmlReporter): """Public reporter that exports HTML via XSLT. This is slightly different than running `xsltproc` on the .xml files, because it passes a parameter to rewrite the links. """ def __init__(self, reports: Reports, output_dir: str) -> None: super().__init__(repo...
XsltHtmlReporter
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 45897, "end": 49361 }
class ____(Response): """ Response of models.delete_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "models" _action = "delete_many" _version = "2.20" _schema = { "definitions": {}, ...
DeleteManyResponse
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 8384, "end": 8507 }
class ____: arg: Annotated[CustomObjArgument, 10] custom_obj_name: Annotated[str, 20] @dataclass
InputToCustomObjSpec
python
matplotlib__matplotlib
lib/matplotlib/legend.py
{ "start": 1905, "end": 14038 }
class ____(DraggableOffsetBox): def __init__(self, legend, use_blit=False, update="loc"): """ Wrapper around a `.Legend` to support mouse dragging. Parameters ---------- legend : `.Legend` The `.Legend` instance to wrap. use_blit : bool, optional ...
DraggableLegend
python
kamyu104__LeetCode-Solutions
Python/paint-fence.py
{ "start": 517, "end": 941 }
class ____(object): def numWays(self, n, k): """ :type n: int :type k: int :rtype: int """ if n == 0: return 0 elif n == 1: return k ways = [0] * n ways[0] = k ways[1] = (k - 1) * ways[0] + k for i in xra...
Solution2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 99503, "end": 99812 }
class ____(sgqlc.types.Enum): """Severity of the vulnerability. Enumeration Choices: * `CRITICAL`: Critical. * `HIGH`: High. * `LOW`: Low. * `MODERATE`: Moderate. """ __schema__ = github_schema __choices__ = ("CRITICAL", "HIGH", "LOW", "MODERATE")
SecurityAdvisorySeverity
python
huggingface__transformers
src/transformers/models/nanochat/modular_nanochat.py
{ "start": 4592, "end": 4902 }
class ____(LlamaDecoderLayer): def __init__(self, config: NanoChatConfig, layer_idx: int): super().__init__() self.input_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps) self.post_attention_layernorm = NanoChatRMSNorm(eps=config.rms_norm_eps) @auto_docstring
NanoChatDecoderLayer
python
ansible__ansible
lib/ansible/_internal/_templating/_lazy_containers.py
{ "start": 9837, "end": 15778 }
class ____(_AnsibleTaggedDict, _AnsibleLazyTemplateMixin): __slots__ = _AnsibleLazyTemplateMixin._SLOTS def __init__(self, contents: t.Iterable | _LazyValueSource, /, **kwargs) -> None: if isinstance(contents, _AnsibleLazyTemplateDict): super().__init__(dict.items(contents), **kwargs) ...
_AnsibleLazyTemplateDict
python
doocs__leetcode
solution/1800-1899/1813.Sentence Similarity III/Solution.py
{ "start": 0, "end": 473 }
class ____: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: words1, words2 = sentence1.split(), sentence2.split() m, n = len(words1), len(words2) if m < n: words1, words2 = words2, words1 m, n = n, m i = j = 0 while i < n and wor...
Solution
python
kamyu104__LeetCode-Solutions
Python/groups-of-strings.py
{ "start": 873, "end": 1579 }
class ____(object): def groupStrings(self, words): """ :type words: List[str] :rtype: List[int] """ uf = UnionFind(len(words)) lookup = {} for i, x in enumerate(words): mask = reduce(lambda x, y: x|(1<<(ord(y)-ord('a'))), x, 0) if mask ...
Solution
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 541431, "end": 578033 }
class ____: """Create a new shape.""" @staticmethod def horizontal_angle(C, P): """Return the angle to the horizontal for the connection from C to P. This uses the arcus sine function and resolves its inherent ambiguity by looking up in which quadrant vector S = P - C is located. ...
Shape
python
Farama-Foundation__Gymnasium
docs/tutorials/training_agents/frozenlake_q_learning.py
{ "start": 3623, "end": 17295 }
class ____: def __init__(self, epsilon): self.epsilon = epsilon def choose_action(self, action_space, state, qtable): """Choose an action `a` in the current world state (s).""" # First we randomize a number explor_exploit_tradeoff = rng.uniform(0, 1) # Exploration ...
EpsilonGreedy
python
getsentry__sentry
src/sentry/deletions/defaults/platform_external_issue.py
{ "start": 174, "end": 402 }
class ____(ModelDeletionTask[PlatformExternalIssue]): def mark_deletion_in_progress(self, instance_list: Sequence[PlatformExternalIssue]) -> None: # No status to track this. pass
PlatformExternalIssueDeletionTask
python
google__pytype
pytype/rewrite/abstract/classes.py
{ "start": 618, "end": 5270 }
class ____(base.BaseValue): """Class with a name and members.""" def __init__( self, ctx: base.ContextType, name: str, members: dict[str, base.BaseValue], bases: Sequence['SimpleClass'] = (), keywords: Mapping[str, base.BaseValue] = datatypes.EMPTY_MAP, module: str | None ...
SimpleClass
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/tests/test_completion_widget.py
{ "start": 852, "end": 3343 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): """ Create the application for the test case. """ cls._app = QtWidgets.QApplication.instance() if cls._app is None: cls._app = QtWidgets.QApplication([]) cls._app.setQuitOnLastWindowClosed(False...
TestCompletionWidget
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 346686, "end": 350816 }
class ____(StatNode): """ Represents a Python with statement. Implemented by the WithTransform as follows: MGR = EXPR EXIT = MGR.__exit__ VALUE = MGR.__enter__() EXC = True try: try: TARGET = VALUE # optional BODY ...
WithStatNode
python
Textualize__textual
src/textual/widgets/_option_list.py
{ "start": 2615, "end": 3009 }
class ____: """Cached line information.""" lines: list[tuple[int, int]] = field(default_factory=list) heights: dict[int, int] = field(default_factory=dict) index_to_line: dict[int, int] = field(default_factory=dict) def clear(self) -> None: """Reset all caches.""" self.lines.clear(...
_LineCache
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/components/customizing-existing-component/7-component.py
{ "start": 183, "end": 580 }
class ____(SlingReplicationCollectionComponent): def execute( self, context: dg.AssetExecutionContext, sling: SlingResource, replication_spec_model: SlingReplicationSpecModel, ) -> Iterator: context.log.info("*******************CUSTOM*************************") re...
CustomSlingReplicationComponent
python
readthedocs__readthedocs.org
readthedocs/proxito/views/serve.py
{ "start": 25806, "end": 29560 }
class ____(CDNCacheControlMixin, CDNCacheTagsMixin, ServeDocsMixin, View): """Serve robots.txt from the domain's root.""" # Always cache this view, since it's the same for all users. cache_response = True # Extra cache tag to invalidate only this view if needed. project_cache_tag = "robots.txt" ...
ServeRobotsTXTBase
python
openai__openai-python
src/openai/types/beta/threads/refusal_content_block.py
{ "start": 197, "end": 310 }
class ____(BaseModel): refusal: str type: Literal["refusal"] """Always `refusal`."""
RefusalContentBlock
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 29112, "end": 30593 }
class ____(FunctionArg): def __init__( self, name: str, unquote: bool | None = False, unescape_quotes: bool | None = False, optional_unquote: bool | None = False, allowed_strings: list[str] | None = None, ): """ :param str name: The name of the fun...
StringArg
python
pytest-dev__pytest
src/_pytest/_code/code.py
{ "start": 48002, "end": 48240 }
class ____(TerminalRepr): lines: Sequence[str] style: ClassVar[TracebackStyle] = "native" def toterminal(self, tw: TerminalWriter) -> None: tw.write("".join(self.lines)) @dataclasses.dataclass(eq=False)
ReprEntryNative
python
getsentry__sentry
tests/sentry/eventtypes/test_nel.py
{ "start": 89, "end": 482 }
class ____(TestCase): def test_get_metadata(self) -> None: inst = NelEvent() data = { "logentry": {"formatted": "connection / tcp.refused"}, "request": {"url": "https://example.com/"}, } assert inst.get_metadata(data) == { "title": "connection / tc...
NelEventTest
python
getsentry__sentry-python
tests/integrations/tornado/test_tornado.py
{ "start": 1372, "end": 13707 }
class ____(RequestHandler): async def get(self): sentry_sdk.get_isolation_scope().set_tag("foo", "42") return b"hello" async def post(self): sentry_sdk.get_isolation_scope().set_tag("foo", "43") return b"hello" def test_basic(tornado_testcase, sentry_init, capture_events): ...
HelloHandler
python
getsentry__sentry
src/sentry/api/endpoints/organization_onboarding_tasks.py
{ "start": 744, "end": 3260 }
class ____(OrganizationEndpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, } owner = ApiOwner.TELEMETRY_EXPERIENCE permission_classes = (OnboardingTaskPermission,) def post(self, request: Request, organization) -> Response: task_i...
OrganizationOnboardingTaskEndpoint
python
django-debug-toolbar__django-debug-toolbar
tests/test_forms.py
{ "start": 369, "end": 572 }
class ____(forms.Form): value = forms.CharField() # Include a datetime in the tests because it's not serializable back # to a datetime by SignedDataForm date = forms.DateTimeField()
FooForm
python
getsentry__sentry
src/sentry/models/project.py
{ "start": 7006, "end": 35272 }
class ____(Model): from sentry.models.projectteam import ProjectTeam """ Projects are permission based namespaces which generally are the top level entry point for all data. """ __relocation_scope__ = RelocationScope.Organization slug = SentrySlugField(max_length=PROJECT_SLUG_MAX_LENGTH) ...
Project
python
tensorflow__tensorflow
tensorflow/python/keras/layers/core.py
{ "start": 60908, "end": 64421 }
class ____(InstanceProperty): """Wraps an instance method access (e.g. `x.foo(arg)` in a Keras Layer. This layer takes an attribute name `attr_name` in the constructor and, when called on input tensor `obj` with additional arguments `args` and `kwargs` returns `obj.attr_name(*args, **kwargs)`. KerasTensors ...
InstanceMethod
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py
{ "start": 96, "end": 1364 }
class ____(Benchmark): r""" Ackley01 objective function. The Ackley01 [1]_ global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{Ackley01}}(x) = -20 e^{-0.2 \sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2}} - e^{\frac{1}{n} \sum_{i=1}^n \co...
Ackley01
python
PrefectHQ__prefect
tests/test_serializers.py
{ "start": 689, "end": 756 }
class ____(BaseModel): x: int y: uuid.UUID @dataclass
MyModel
python
PyCQA__pylint
tests/functional/m/membership_protocol.py
{ "start": 1397, "end": 1590 }
class ____: stuff = None def get_stuff(self): return self.stuff def act(self, thing): stuff = self.get_stuff() if thing in stuff: pass
UsefulMixin
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/hooks/test_hive.py
{ "start": 13716, "end": 25068 }
class ____: def setup_method(self): self.next_day = (DEFAULT_DATE + datetime.timedelta(days=1)).isoformat()[:10] self.database = "airflow" self.partition_by = "ds" self.table = "static_babynames_partitioned" with ( mock.patch( "airflow.providers.ap...
TestHiveMetastoreHook
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_getitem.py
{ "start": 370, "end": 2222 }
class ____: def test_getitem_unused_level_raises(self): # GH#20410 mi = MultiIndex( levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]], codes=[[1, 0], [1, 0]], ) df = DataFrame(-1, index=range(3), columns=mi) with pytest.raises(KeyError, match="n...
TestGetitem
python
vyperlang__vyper
vyper/semantics/analysis/data_positions.py
{ "start": 2760, "end": 3940 }
class ____: storage_allocator: SimpleAllocator transient_storage_allocator: SimpleAllocator immutables_allocator: SimpleAllocator _global_nonreentrancy_key_slot: int def __init__(self): self.storage_allocator = SimpleAllocator(max_slot=2**256) self.transient_storage_allocator = Sim...
Allocators
python
run-llama__llama_index
llama-index-core/llama_index/core/storage/kvstore/types.py
{ "start": 2686, "end": 6295 }
class ____(Generic[MutableMappingT], BaseKVStore): """ MutableMapping Key-Value store. Args: mapping_factory (Callable[[], MutableMapping[str, dict]): the mutable mapping factory """ def __init__(self, mapping_factory: Callable[[], MutableMappingT]) -> None: """Initialize a Mutabl...
MutableMappingKVStore
python
openai__openai-python
src/openai/types/chat/chat_completion_system_message_param.py
{ "start": 356, "end": 815 }
class ____(TypedDict, total=False): content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] """The contents of the system message.""" role: Required[Literal["system"]] """The role of the messages author, in this case `system`.""" name: str """An optional name for the partic...
ChatCompletionSystemMessageParam
python
kamyu104__LeetCode-Solutions
Python/minimum-insertions-to-balance-a-parentheses-string.py
{ "start": 29, "end": 494 }
class ____(object): def minInsertions(self, s): """ :type s: str :rtype: int """ add, bal = 0, 0 for c in s: if c == '(': if bal > 0 and bal%2: add += 1 bal -= 1 bal += 2 e...
Solution
python
pypa__pip
src/pip/_internal/models/link.py
{ "start": 18984, "end": 21793 }
class ____(NamedTuple): """Convert link for equivalency check. This is used in the resolver to check whether two URL-specified requirements likely point to the same distribution and can be considered equivalent. This equivalency logic avoids comparing URLs literally, which can be too strict (e.g. "...
_CleanResult
python
zarr-developers__zarr-python
src/zarr/core/indexing.py
{ "start": 46673, "end": 47569 }
class ____(CoordinateIndexer): def __init__( self, selection: MaskSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid ) -> None: # some initial normalization selection_normalized = cast("tuple[MaskSelection]", ensure_tuple(selection)) selection_normalized = cast("tuple[MaskS...
MaskIndexer
python
spyder-ide__spyder
spyder/widgets/collectionseditor.py
{ "start": 3936, "end": 4780 }
class ____: AddDelete = 'add_delete_section' ViewAndRest = 'view_section' # Maximum length of a serialized variable to be set in the kernel MAX_SERIALIZED_LENGHT = 1e6 # To handle large collections LARGE_NROWS = 100 ROWS_TO_LOAD = 50 # Numeric types NUMERIC_TYPES = (int, float) + get_numeric_numpy_types() ...
CollectionsEditorToolbarSections
python
getsentry__sentry
src/sentry/apidocs/parameters.py
{ "start": 31550, "end": 32158 }
class ____: QUERY = OpenApiParameter( name="query", location="query", required=False, type=str, description="""The name of the Explore query you'd like to filter by.""", ) SORT = OpenApiParameter( name="sortBy", location="query", required=Fals...
ExploreSavedQueriesParams
python
huggingface__transformers
tests/pipelines/test_pipelines_object_detection.py
{ "start": 1368, "end": 12546 }
class ____(unittest.TestCase): model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING _dataset = None @classmethod def _load_dataset(cls): # Lazy loading of the dataset. Because it is a class method, it will only be loaded once per pytest process. if cls._dataset is None: # we u...
ObjectDetectionPipelineTests
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 150692, "end": 152759 }
class ____: # survival function references were computed with mpmath via # from mpmath import mp # x = mp.mpf(x) # c = mp.mpf(x) # float(mp.ncdf(-x)**c) @pytest.mark.parametrize("x, c, ref", [(9, 1, 1.1285884059538405e-19), (20, 2, 7.5...
TestPowerNorm
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 874506, "end": 874685 }
class ____(sgqlc.types.Type, ProjectV2FieldCommon, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ()
ProjectV2Field
python
chroma-core__chroma
chromadb/execution/executor/abstract.py
{ "start": 201, "end": 470 }
class ____(Component): @abstractmethod def count(self, plan: CountPlan) -> int: pass @abstractmethod def get(self, plan: GetPlan) -> GetResult: pass @abstractmethod def knn(self, plan: KNNPlan) -> QueryResult: pass
Executor
python
conda__conda
tests/plugins/test_transaction_hooks.py
{ "start": 306, "end": 492 }
class ____(Action): def verify(self): pass def execute(self): pass def reverse(self): pass def cleanup(self): pass
DummyTransactionAction
python
pytorch__pytorch
torch/_inductor/codegen/cpp_bmm_template.py
{ "start": 2293, "end": 9386 }
class ____(CppGemmTemplate): def __init__( self, input_nodes, layout: ir.Layout, num_threads: int, register_blocking: GemmBlocking, beta=1, alpha=1, has_bias=False, epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None, ...
CppBmmTemplate
python
celery__celery
t/unit/app/test_routes.py
{ "start": 3696, "end": 7372 }
class ____(RouteCase): def test_init_queues(self): router = Router(self.app, queues=None) assert router.queues == {} def test_lookup_takes_first(self): set_queues(self.app, foo=self.a_queue, bar=self.b_queue) R = routes.prepare(({self.mytask.name: {'queue': 'bar'}}, ...
test_lookup_route
python
spack__spack
lib/spack/spack/llnl/util/tty/log.py
{ "start": 23992, "end": 26601 }
class ____: """Wrapper class to handle redirection of io streams""" def __init__(self, sys_attr): self.sys_attr = sys_attr self.saved_stream = None if sys.platform.startswith("win32"): if hasattr(sys, "gettotalrefcount"): # debug build libc = ctypes.CDLL("uc...
StreamWrapper
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/types.py
{ "start": 1631, "end": 1939 }
class ____: operator_classes = OperatorClass.BASE | OperatorClass.COMPARISON def coerce_compared_value( self, op: Optional[OperatorType], value: Any ) -> TypeEngine[Any]: if TYPE_CHECKING: assert isinstance(self, TypeEngine) return self
_NetworkAddressTypeMixin
python
getsentry__sentry
tests/sentry/notifications/test_apps.py
{ "start": 174, "end": 1485 }
class ____(TestCase): def test_registers_legacy_providers(self) -> None: """ This django app doesn't actually register these legacy providers because it would result in some circular breakages from all the __init__.py imports. We'll still test it here to make sure it doesn't break i...
NotificationsDjangoAppTest
python
plotly__plotly.py
tests/test_core/test_colors/test_colors.py
{ "start": 106, "end": 7569 }
class ____(TestCase): def test_validate_colors(self): # test string input color_string = "foo" pattern = ( "If your colors variable is a string, it must be a " "Plotly scale, an rgb color or a hex color." ) self.assertRaisesRegex( PlotlyE...
TestColors
python
openai__openai-python
src/openai/types/responses/response_function_web_search.py
{ "start": 765, "end": 911 }
class ____(BaseModel): type: Literal["open_page"] """The action type.""" url: str """The URL opened by the model."""
ActionOpenPage
python
huggingface__transformers
src/transformers/models/flava/modeling_flava.py
{ "start": 26410, "end": 27201 }
class ____(nn.Module): def __init__(self, config: FlavaPossibleConfigs) -> None: super().__init__() self.attention = FlavaSelfAttention(config) self.output = FlavaSelfOutput(config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Te...
FlavaAttention
python
getsentry__sentry
tests/sentry/preprod/test_tasks.py
{ "start": 18996, "end": 24166 }
class ____(BaseAssembleTest): def setUp(self) -> None: super().setUp() self.preprod_artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.UPLOADED ) def _run_task_and_verify_status( self, content, checksum=None, chunks=N...
AssemblePreprodArtifactSizeAnalysisTest
python
google__pytype
pytype/block_environment_test.py
{ "start": 669, "end": 701 }
class ____: id: int
FakeVariable
python
getsentry__sentry
src/sentry/search/events/datasets/discover.py
{ "start": 2858, "end": 87923 }
class ____(DatasetConfig): custom_threshold_columns = { "apdex()", "count_miserable(user)", "user_misery()", } non_nullable_keys = {"event.type"} nullable_context_keys = {"thread.id"} use_entity_prefix_for_fields: bool = False def __init__(self, builder: BaseQueryBuilder...
DiscoverDatasetConfig
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/_stubs.py
{ "start": 587, "end": 673 }
class ____(TypedDict): DisplayName: Optional[str] ID: Optional[str]
OwnerTypeDef
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/context.py
{ "start": 4214, "end": 6984 }
class ____(NamedTuple): """ Context of parsing for the Dag. If these values are not None, they will contain the specific Dag and Task ID that Airflow is requesting to execute. You can use these for optimizing dynamically generated Dag files. You can obtain the current values via :py:func:`.get_par...
AirflowParsingContext
python
dask__dask
dask/dataframe/dask_expr/_collection.py
{ "start": 95143, "end": 148963 }
class ____(FrameBase): """DataFrame-like Expr Collection. The constructor takes the expression that represents the query as input. The class is not meant to be instantiated directly. Instead, use one of the IO connectors from Dask. """ _accessors: ClassVar[set[str]] = set() _partition_type...
DataFrame
python
google__pytype
pytype/metrics_test.py
{ "start": 3206, "end": 3934 }
class ____(unittest.TestCase): """Tests for StopWatch.""" def setUp(self): super().setUp() metrics._prepare_for_test() def test_stopwatch(self): c = metrics.StopWatch("foo") with c: pass self.assertGreaterEqual(c._total, 0) def test_merge(self): c1 = metrics.StopWatch("foo") ...
StopWatchTest
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 32906, "end": 44072 }
class ____: """Some tests to show that fisher_exact() works correctly. Note that in SciPy 0.9.0 this was not working well for large numbers due to inaccuracy of the hypergeom distribution (see #1218). Fixed now. Also note that R and SciPy have different argument formats for their hypergeometric di...
TestFisherExact
python
kamyu104__LeetCode-Solutions
Python/maximum-increasing-triplet-value.py
{ "start": 758, "end": 1297 }
class ____(object): def maximumTripletValue(self, nums): """ :type nums: List[int] :rtype: int """ left = SortedList() right = SortedList(nums[i] for i in xrange(1, len(nums))) result = 0 for i in xrange(1, len(nums)-1): left.add(nums[i-1])...
Solution2
python
doocs__leetcode
solution/1200-1299/1266.Minimum Time Visiting All Points/Solution.py
{ "start": 0, "end": 204 }
class ____: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: return sum( max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) for p1, p2 in pairwise(points) )
Solution
python
getsentry__sentry
src/sentry/monitors/serializers.py
{ "start": 4598, "end": 4935 }
class ____(TypedDict): schedule_type: Literal["crontab", "interval"] schedule: str | tuple[int, IntervalNames] checkin_margin: int | None max_runtime: int | None timezone: str | None failure_issue_threshold: int | None recovery_threshold: int | None alert_rule_id: int | None
MonitorConfigSerializerResponse
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/retrieval/metrics.py
{ "start": 3010, "end": 6010 }
class ____(BaseRetrievalMetric): """ MRR (Mean Reciprocal Rank) metric with two calculation options. - The default method calculates the reciprocal rank of the first relevant retrieved document. - The more granular method sums the reciprocal ranks of all relevant retrieved documents and divides by the ...
MRR
python
getsentry__sentry
tests/sentry/explore/endpoints/test_explore_saved_query_starred_order.py
{ "start": 175, "end": 2672 }
class ____(APITestCase, SnubaTestCase): feature_name = "organizations:visibility-explore-view" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.create_organization(owner=self.user) self.project_ids = [ self.create_project(organiz...
ExploreSavedQueryStarredOrderTest
python
getsentry__sentry
src/sentry/users/api/endpoints/user_details.py
{ "start": 7381, "end": 7638 }
class ____(serializers.Serializer[User]): organizations = serializers.ListField( child=serializers.CharField(required=False), required=True ) hardDelete = serializers.BooleanField(required=False) @control_silo_endpoint
DeleteUserSerializer
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 47380, "end": 55259 }
class ____: def test_webauthn_get_options_already_authenticated(self): request = pretend.stub(user=pretend.stub(), _=lambda a: a) result = views.webauthn_authentication_options(request) assert result == {"fail": {"errors": ["Already authenticated"]}} def test_webauthn_get_options_inva...
TestWebAuthn
python
redis__redis-py
tests/test_asyncio/test_cluster.py
{ "start": 1612, "end": 9736 }
class ____: """A class to proxy a node connection to a different port""" def __init__(self, addr, redis_addr): self.addr = addr self.redis_addr = redis_addr self.server = None self.task = None self.n_connections = 0 async def start(self): # test that we can ...
NodeProxy
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/bigquery.py
{ "start": 37558, "end": 50236 }
class ____(GoogleCloudBaseOperator, _BigQueryOperatorsEncryptionConfigurationMixin): """ Fetch data and return it, either from a BigQuery table, or results of a query job. Data could be narrowed down by specific columns or retrieved as a whole. It is returned in either of the following two formats, bas...
BigQueryGetDataOperator
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 119199, "end": 120585 }
class ____(Fittable1DModel): """ One dimensional exponential model. Parameters ---------- amplitude : float, optional tau : float, optional See Also -------- Logarithmic1D, Gaussian1D """ amplitude = Parameter(default=1) tau = Parameter(default=1) @staticmethod ...
Exponential1D