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
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 52060, "end": 55797 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): global t1, t2 t1 = Table( "t1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("type", String(30...
CustomPKTest
python
django__django
tests/queries/models.py
{ "start": 11699, "end": 11832 }
class ____(models.Model): name = models.CharField(max_length=20, null=True) class Meta: ordering = ["id"]
NullableName
python
fsspec__filesystem_spec
fsspec/implementations/http_sync.py
{ "start": 26466, "end": 30332 }
class ____(AbstractBufferedFile): def __init__(self, fs, url, mode="rb", session=None, **kwargs): self.url = url self.session = session if mode != "rb": raise ValueError self.details = {"name": url, "size": None} super().__init__(fs=fs, path=url, mode=mode, cache_...
HTTPStreamFile
python
kamyu104__LeetCode-Solutions
Python/can-you-eat-your-favorite-candy-on-your-favorite-day.py
{ "start": 29, "end": 429 }
class ____(object): def canEat(self, candiesCount, queries): """ :type candiesCount: List[int] :type queries: List[List[int]] :rtype: List[bool] """ prefix = [0]*(len(candiesCount)+1) for i, c in enumerate(candiesCount): prefix[i+1] = prefix[i]+c ...
Solution
python
gevent__gevent
src/gevent/tests/test__queue.py
{ "start": 13059, "end": 15116 }
class ____(TestSimpleQueue): queue = queue def _getFUT(self): return queue.Queue def test_task_done(self): channel = self._makeOne() X = object() gevent.spawn(channel.put, X) result = channel.get() self.assertIs(result, X) self.assertEqual(1, channel...
TestQueue
python
ansible__ansible
test/lib/ansible_test/_internal/host_configs.py
{ "start": 17369, "end": 17528 }
class ____: """Details about controller fallback behavior.""" reason: FallbackReason message: str @dataclasses.dataclass(frozen=True)
FallbackDetail
python
ray-project__ray
rllib/env/external/rllink.py
{ "start": 199, "end": 3514 }
class ____(Enum): PROTOCOL_VERSION = Version("0.0.1") # Requests: Client (external env) -> Server (RLlib). # ---- # Ping command (initial handshake). PING = "PING" # List of episodes (similar to what an EnvRunner.sample() call would return). EPISODES = "EPISODES" # Request state (e.g. m...
RLlink
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk4agg.py
{ "start": 1186, "end": 1262 }
class ____(_BackendGTK4): FigureCanvas = FigureCanvasGTK4Agg
_BackendGTK4Agg
python
pytorch__pytorch
torch/testing/_internal/common_distributed.py
{ "start": 59359, "end": 70608 }
class ____(TestCase): # Class variables: MAIN_PROCESS_RANK = -1 # number of test processes world_size: int = -2 # unset state # rank of the current process rank: int = -2 # unset state # Rendezvous file rdvz_file: Optional[str] = None # timeout configured per class timeout: tim...
MultiProcContinuousTest
python
pytest-dev__pytest
doc/en/example/assertion/failure_demo.py
{ "start": 4226, "end": 5138 }
class ____: def test_complex_error(self): def f(): return 44 def g(): return 43 somefunc(f(), g()) def test_z1_unpack_error(self): items = [] a, b = items def test_z2_type_error(self): items = 3 a, b = items def test_st...
TestMoreErrors
python
tensorflow__tensorflow
tensorflow/python/training/sync_replicas_optimizer.py
{ "start": 1956, "end": 18742 }
class ____(optimizer.Optimizer): """Class to synchronize, aggregate gradients and pass them to the optimizer. This class is deprecated. For synchronous training, please use [Distribution Strategies](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute). In a typical asynchronous ...
SyncReplicasOptimizer
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_object_position11.py
{ "start": 315, "end": 999 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("object_position11.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook...
TestCompareXLSXFiles
python
airbytehq__airbyte
airbyte-integrations/connectors/source-prestashop/components.py
{ "start": 555, "end": 5523 }
class ____(RecordTransformation): """ Remove all "empty" (e.g. '0000-00-00', '0000-00-00 00:00:00') 'date' and 'date-time' fields from record """ config: Config parameters: InitVar[Optional[Mapping[str, Any]]] = None def __post_init__(self, parameters: Optional[Mapping[str, Any]] = None): ...
CustomFieldTransformation
python
plotly__plotly.py
plotly/graph_objs/_choroplethmap.py
{ "start": 215, "end": 64427 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "choroplethmap" _valid_props = { "autocolorscale", "below", "coloraxis", "colorbar", "colorscale", "customdata", "customdatasrc", "featureidkey", "geojson", "hoverinf...
Choroplethmap
python
getsentry__sentry
fixtures/safe_migrations_apps/decimal_to_float_app/migrations/0001_initial.py
{ "start": 106, "end": 831 }
class ____(CheckedMigration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Value", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, seria...
Migration
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_management_commands.py
{ "start": 896, "end": 1080 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, model_attr="name") def get_model(self): return MockTag
SolrMockTagSearchIndex
python
EpistasisLab__tpot
tpot/builtin_modules/nn.py
{ "start": 7131, "end": 7626 }
class ____(nn.Module): # pylint: disable=arguments-differ def __init__(self, input_size, num_classes): super(_MLP, self).__init__() self.hidden_size = round((input_size+num_classes)/2) self.fc1 = nn.Linear(input_size, self.hidden_size) self.relu = nn.Tanh() self.fc2 = n...
_MLP
python
huggingface__transformers
tests/models/dpr/test_tokenization_dpr.py
{ "start": 1008, "end": 1321 }
class ____(test_tokenization_bert.BertTokenizationTest): tokenizer_class = DPRContextEncoderTokenizer rust_tokenizer_class = DPRContextEncoderTokenizerFast test_rust_tokenizer = True from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base" @require_tokenizers
DPRContextEncoderTokenizationTest
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-google-sheets/destination_google_sheets/helpers.py
{ "start": 1202, "end": 2741 }
class ____: """ Performs connection test write operation to ensure the target spreadsheet is available for writing. Initiating the class itself, performs the connection test and stores the result in ConnectionTest.result property. """ def __init__(self, spreadsheet: Spreadsheet): self.sprea...
ConnectionTest
python
getsentry__sentry
src/sentry/db/models/fields/uuid.py
{ "start": 5778, "end": 6125 }
class ____: def __init__(self, value): if not isinstance(value, UUID): raise TypeError("UUIDAdapter only understands UUID objects.") self.value = value def getquoted(self): return ("'%s'" % self.value).encode("utf8") # Register the UUID type with psycopg2. register_adapter...
UUIDAdapter
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 4021, "end": 4190 }
class ____(LeafResource): def render_GET(self, request): n = getarg(request, b"n", 200, type_=int) request.setResponseCode(n) return b""
Status
python
langchain-ai__langchain
libs/core/langchain_core/documents/transformers.py
{ "start": 314, "end": 2543 }
class ____(ABC): """Abstract base class for document transformation. A document transformation takes a sequence of `Document` objects and returns a sequence of transformed `Document` objects. Example: ```python class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel): ...
BaseDocumentTransformer
python
readthedocs__readthedocs.org
readthedocs/projects/models.py
{ "start": 55300, "end": 56923 }
class ____(models.Model): """ Imported files model. This tracks files that are output from documentation builds, useful for things like CDN invalidation. """ id = models.BigAutoField(primary_key=True) project = models.ForeignKey( Project, verbose_name=_("Project"), ...
ImportedFile
python
celery__celery
t/unit/concurrency/test_prefork.py
{ "start": 16274, "end": 17152 }
class ____: def setup_method(self): pytest.importorskip('multiprocessing') def test_process_result(self): x = asynpool.ResultHandler( Mock(), Mock(), {}, Mock(), Mock(), Mock(), Mock(), Mock(), fileno_to_outq={}, on_process_alive=Mock(), ...
test_ResultHandler
python
numba__numba
numba/core/typing/npydecl.py
{ "start": 14241, "end": 21561 }
class ____(AbstractTemplate): """ A template redirecting a Numpy global function (e.g. np.sum) to an array method of the same name (e.g. ndarray.sum). """ # Arguments like *axis* can specialize on literals but also support # non-literals prefer_literal = True def generic(self, args, kw...
Numpy_method_redirection
python
kamyu104__LeetCode-Solutions
Python/search-suggestions-system.py
{ "start": 1508, "end": 1937 }
class ____(object): def __init__(self): self.__TOP_COUNT = 3 self.leaves = collections.defaultdict(TrieNode2) self.infos = [] def insert(self, words, i): curr = self for c in words[i]: curr = curr.leaves[c] curr.add_info(i) def add_info(self...
TrieNode2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 544982, "end": 545508 }
class ____(sgqlc.types.Type): """Autogenerated return type of CreateTeamDiscussionComment""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "team_discussion_comment") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the ...
CreateTeamDiscussionCommentPayload
python
walkccc__LeetCode
solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py
{ "start": 27, "end": 81 }
class ____(IntEnum): HORIZONTAL = 0 VERTICAL = 1
Pos
python
kamyu104__LeetCode-Solutions
Python/count-asterisks.py
{ "start": 38, "end": 375 }
class ____(object): def countAsterisks(self, s): """ :type s: str :rtype: int """ result = cnt = 0 for c in s: if c == '|': cnt = (cnt+1)%2 continue if c == '*' and cnt == 0: result += 1 r...
Solution
python
spack__spack
lib/spack/spack/build_environment.py
{ "start": 63186, "end": 65197 }
class ____: """The function :meth:`spack.package_base.PackageBase.setup_dependent_package` receives an instance of this class for the ``module`` argument. It's used to set global variables in the module of a package, and propagate those globals to the modules of all classes in the inheritance hierarchy ...
ModuleChangePropagator
python
getsentry__sentry
src/sentry/users/api/serializers/authenticator.py
{ "start": 1362, "end": 2698 }
class ____(Serializer): def serialize( self, obj: AuthenticatorInterface, attrs: Mapping[str, Any], user: User | RpcUser | AnonymousUser, **kwargs: Any, ) -> AuthenticatorInterfaceSerializerResponse: data: AuthenticatorInterfaceSerializerResponse = { "...
AuthenticatorInterfaceSerializer
python
google__python-fire
fire/test_components.py
{ "start": 1857, "end": 1975 }
class ____: def double(self, count): return 2 * count def triple(self, count): return 3 * count
NoDefaults
python
pypa__warehouse
tests/unit/metrics/test_services.py
{ "start": 281, "end": 1530 }
class ____: def test_verify_service(self): assert verifyClass(IMetricsService, NullMetrics) def test_create_service(self): assert isinstance( NullMetrics.create_service(pretend.stub(), pretend.stub()), NullMetrics ) @pytest.mark.parametrize( "method", [ ...
TestNullMetrics
python
getsentry__sentry
fixtures/safe_migrations_apps/bad_flow_add_column_with_notnull_default_app/migrations/0002_add_field_notnull_default.py
{ "start": 153, "end": 468 }
class ____(CheckedMigration): dependencies = [ ("bad_flow_add_column_with_notnull_default_app", "0001_initial"), ] operations = [ migrations.AddField( model_name="testtable", name="field", field=models.IntegerField(default=0), ), ]
Migration
python
coleifer__peewee
tests/regressions.py
{ "start": 17156, "end": 18644 }
class ____(TestModel): version = IntegerField(default=1, index=True) def save_optimistic(self): if not self.id: # This is a new record, so the default logic is to perform an # INSERT. Ideally your model would also have a unique # constraint that made it impossible fo...
BaseVersionedModel
python
django__django
django/contrib/gis/db/backends/mysql/base.py
{ "start": 251, "end": 498 }
class ____(MySQLDatabaseWrapper): SchemaEditorClass = MySQLGISSchemaEditor # Classes instantiated in __init__(). features_class = DatabaseFeatures introspection_class = MySQLIntrospection ops_class = MySQLOperations
DatabaseWrapper
python
vyperlang__vyper
vyper/builtins/_signatures.py
{ "start": 2759, "end": 6095 }
class ____(VyperType): typeclass = "builtin_function" _has_varargs = False _inputs: list[tuple[str, Any]] = [] _kwargs: dict[str, KwargSettings] = {} _modifiability: Modifiability = Modifiability.MODIFIABLE _return_type: Optional[VyperType] = None _equality_attrs = ("_id",) _is_terminus...
BuiltinFunctionT
python
kamyu104__LeetCode-Solutions
Python/transpose-matrix.py
{ "start": 406, "end": 572 }
class ____(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return zip(*A)
Solution2
python
ionelmc__pytest-benchmark
tests/test_sample.py
{ "start": 266, "end": 509 }
class ____: def __init__(self, factory): self.factory = factory self.object = empty def __str__(self): if self.object is empty: self.object = self.factory() return str(self.object)
SimpleProxy
python
networkx__networkx
networkx/algorithms/bipartite/tests/test_project.py
{ "start": 6282, "end": 15294 }
class ____: @classmethod def setup_class(cls): # Tore Opsahl's example # http://toreopsahl.com/2009/05/01/projecting-two-mode-networks-onto-weighted-one-mode-networks/ cls.G = nx.Graph() cls.G.add_edge("A", 1) cls.G.add_edge("A", 2) cls.G.add_edge("B", 1) ...
TestBipartiteWeightedProjection
python
tiangolo__fastapi
docs_src/extra_models/tutorial001.py
{ "start": 236, "end": 341 }
class ____(BaseModel): username: str email: EmailStr full_name: Union[str, None] = None
UserOut
python
ray-project__ray
python/ray/autoscaler/_private/fake_multi_node/test_utils.py
{ "start": 643, "end": 11692 }
class ____: """Docker cluster wrapper. Creates a directory for starting a fake multinode docker cluster. Includes APIs to update the cluster config as needed in tests, and to start and connect to the cluster. """ def __init__(self, config: Optional[Dict[str, Any]] = None): self._base_...
DockerCluster
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib_test.py
{ "start": 17407, "end": 21988 }
class ____(test.TestCase, parameterized.TestCase): def testMergeCall(self): _assert_in_default_state(self) def merge_fn(dist, s): self.assertIs(distribute_lib._get_default_strategy(), dist) self.assertIs(None, distribute_lib.get_replica_context()) self.assertIs(dist, distribute_lib.get_cro...
DefaultDistributionStrategyTest
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 27823, "end": 28127 }
class ____(VOTableSpecWarning): """ The attribute requires the value to be a valid XML token, as defined by `XML 1.0 <http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Nmtoken>`__. """ message_template = "'{}' is an invalid token for attribute '{}'" default_args = ("x", "y")
W34
python
PyCQA__pydocstyle
src/pydocstyle/parser.py
{ "start": 9996, "end": 11543 }
class ____: # A logical newline is where a new expression or statement begins. When # there is a physical new line, but not a logical one, for example: # (x + # y) # The token will be tk.NL, not tk.NEWLINE. LOGICAL_NEWLINES = {tk.NEWLINE, tk.INDENT, tk.DEDENT} def __init__(self, filelike):...
TokenStream
python
apache__airflow
providers/slack/src/airflow/providers/slack/hooks/slack.py
{ "start": 2579, "end": 18854 }
class ____(BaseHook): """ Creates a Slack API Connection to be used for calls. This class provide a thin wrapper around the ``slack_sdk.WebClient``. .. seealso:: - :ref:`Slack API connection <howto/connection:slack>` - https://api.slack.com/messaging - https://slack.dev/python-...
SlackHook
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 15292, "end": 15615 }
class ____(AbstractTemplate): key = cuda.atomic.compare_and_swap def generic(self, args, kws): assert not kws ary, old, val = args dty = ary.dtype if dty in integer_numba_types and ary.ndim == 1: return signature(dty, ary, dty, dty) @register
Cuda_atomic_compare_and_swap
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 592771, "end": 596424 }
class ____(CoercionNode): # This node is used to check that a generic Python # object is an instance of a particular extension type. # This node borrows the result of its argument node. # Builtin subtypes or compatible types (e.g. int/float) are coerced # to the base type automatically. ex...
PyTypeTestNode
python
getsentry__sentry
src/sentry/api/serializers/models/project.py
{ "start": 23792, "end": 25157 }
class ____(ProjectSerializer): def get_attrs( self, item_list: Sequence[Project], user: User | RpcUser | AnonymousUser, **kwargs: Any ) -> dict[Project, dict[str, Any]]: attrs = super().get_attrs(item_list, user) project_teams = list( ProjectTeam.objects.filter(project__in=i...
ProjectWithTeamSerializer
python
dask__distributed
distributed/diagnostics/plugin.py
{ "start": 23846, "end": 25336 }
class ____: INSTALLER = "pip" packages: list[str] pip_options: list[str] def __init__(self, packages: list[str], pip_options: list[str] | None = None): self.packages = packages self.pip_options = pip_options or [] def __call__(self) -> None: logger.info( "%s in...
_PipInstaller
python
tensorflow__tensorflow
tensorflow/examples/adding_an_op/cuda_op_test.py
{ "start": 814, "end": 1051 }
class ____(tf.test.TestCase): def test(self): if tf.test.is_built_with_cuda(): result = cuda_op.add_one([5, 4, 3, 2, 1]) self.assertAllEqual(result, [6, 5, 4, 3, 2]) if __name__ == '__main__': tf.test.main()
AddOneTest
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 71094, "end": 73433 }
class ____(BaseScaledMMConfigMixin): """Mixing for scaled mm with the regular mm template""" def get_extra_kwargs( self, kernel_inputs: KernelInputs, op_name: str, ) -> dict[str, Any]: kwargs = super().get_extra_kwargs(kernel_inputs, op_name) from ..kernel.mm_common ...
ScaledMMConfigMixin
python
getsentry__sentry
src/sentry/quotas/base.py
{ "start": 7734, "end": 8724 }
class ____: """ Return value of ``quotas.is_rate_limited``. """ __slots__ = ["is_limited", "retry_after", "reason", "reason_code"] def __init__(self, is_limited, retry_after=None, reason=None, reason_code=None): self.is_limited = is_limited # delta of seconds in the future to retry...
RateLimit
python
tensorflow__tensorflow
tensorflow/core/function/trace_type/default_types_test.py
{ "start": 1681, "end": 2121 }
class ____(MockSupertypes2With3): def is_subtype_of(self, other): return other._object == 2 def most_specific_common_supertype(self, others): if not all(isinstance(other, Mock2AsTopType) for other in others): return None return ( self if all(self._object == other._object for othe...
Mock2AsTopType
python
run-llama__llama_index
llama-index-core/llama_index/core/response_synthesizers/tree_summarize.py
{ "start": 642, "end": 8745 }
class ____(BaseSynthesizer): """ Tree summarize response builder. This response builder recursively merges text chunks and summarizes them in a bottom-up fashion (i.e. building a tree from leaves to root). More concretely, at each recursively step: 1. we repack the text chunks so that each chu...
TreeSummarize
python
PrefectHQ__prefect
src/prefect/server/utilities/database.py
{ "start": 11743, "end": 12268 }
class ____(functions.GenericFunction[datetime.timedelta]): """Platform-independent way to add two intervals.""" type: sa.Interval = sa.Interval() inherit_cache: bool = True def __init__( self, i1: _SQLExpressionOrLiteral[datetime.timedelta], i2: _SQLExpressionOrLiteral[datetime...
interval_add
python
PrefectHQ__prefect
src/prefect/server/events/schemas/events.py
{ "start": 3214, "end": 6671 }
class ____(PrefectBaseModel): """The client-side view of an event that has happened to a Resource""" occurred: prefect.types._datetime.DateTime = Field( description="When the event happened from the sender's perspective", ) event: Annotated[str, AfterValidator(_validate_event_name_length)] = Fi...
Event
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 117176, "end": 117471 }
class ____(sgqlc.types.Enum): """Properties by which team discussion connections can be ordered. Enumeration Choices: * `CREATED_AT`: Allows chronological ordering of team discussions. """ __schema__ = github_schema __choices__ = ("CREATED_AT",)
TeamDiscussionOrderField
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance2.py
{ "start": 277, "end": 375 }
class ____(ClassA): def calculate(self) -> int: return 2 * 2 TC = TypeVar("TC")
ChildB
python
pytorch__pytorch
torch/ao/quantization/quantizer/xnnpack_quantizer_utils.py
{ "start": 2252, "end": 41803 }
class ____(NamedTuple): # fix List[str] with List[List[Union[nn.Module, FunctionType, BuiltinFunctionType]]] # Basically we are mapping a quantization config to some list of patterns. # a pattern is defined as a list of nn module, function or builtin function names # e.g. [nn.Conv2d, torch.relu, torch.a...
OperatorConfig
python
scipy__scipy
scipy/stats/tests/test_morestats.py
{ "start": 34702, "end": 37383 }
class ____: def test_data(self, xp): # https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] args = [xp.asarray(arg) for arg in args] W, pval = stats.levene(*args) xp_assert_close(W, xp.asarray(1.7059176930008939)) ...
TestLevene
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/question_answering/chain.py
{ "start": 1126, "end": 9509 }
class ____(Protocol): """Interface for loading the combine documents chain.""" def __call__( self, llm: BaseLanguageModel, **kwargs: Any, ) -> BaseCombineDocumentsChain: """Callable to load the combine documents chain.""" def _load_map_rerank_chain( llm: BaseLanguageMo...
LoadingCallable
python
optuna__optuna
optuna/visualization/_slice.py
{ "start": 988, "end": 1235 }
class ____(NamedTuple): param_name: str x: list[Any] y: list[float] trial_numbers: list[int] is_log: bool is_numerical: bool constraints: list[bool] x_labels: tuple[CategoricalChoiceType, ...] | None
_SliceSubplotInfo
python
pyinstaller__pyinstaller
PyInstaller/building/splash.py
{ "start": 969, "end": 23950 }
class ____(Target): """ Bundles the required resources for the splash screen into a file, which will be included in the CArchive. A Splash has two outputs, one is itself and one is stored in splash.binaries. Both need to be passed to other build targets in order to enable the splash screen. """ ...
Splash
python
ipython__ipython
IPython/utils/syspathcontext.py
{ "start": 131, "end": 963 }
class ____: """A context for prepending a directory to sys.path for a second.""" dir: str added: bool def __init__(self, dir: str) -> None: self.dir = dir self.added = False def __enter__(self) -> Self: if self.dir not in sys.path: sys.path.insert(0, self.dir) ...
prepended_to_syspath
python
realpython__materials
directory-tree-generator-python/source_code_step_2/rptree/rptree.py
{ "start": 386, "end": 1830 }
class ____: def __init__(self, root_dir): self._root_dir = pathlib.Path(root_dir) self._tree = [] def build_tree(self): self._tree_head() self._tree_body(self._root_dir) return self._tree def _tree_head(self): self._tree.append(f"{self._root_dir}{os.sep}") ...
_TreeGenerator
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 124389, "end": 127654 }
class ____(nn.Module): """This class implements an attentive statistic pooling layer for each channel. It returns the concatenated mean and std of the input tensor. """ def __init__(self, channels, attention_channels=128): super().__init__() self.eps = 1e-12 self.tdnn = TimeDel...
AttentiveStatisticsPooling
python
keon__algorithms
tests/test_dfs.py
{ "start": 201, "end": 805 }
class ____(unittest.TestCase): def test_get_factors(self): self.assertEqual([[2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8]], get_factors(32)) def test_get_factors_iterative1(self): self.assertEqual([[2, 16], [4, 8], [2, 2, 8], [2, 4, 4], [2, 2, 2,...
TestAllFactors
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 10148, "end": 10234 }
class ____(Event): name: str = "traces_received_by_server"
TracesReceivedByServerEvent
python
numba__llvmlite
llvmlite/binding/ffi.py
{ "start": 8854, "end": 8953 }
class ____(object): """ Dummy class to make error messages more helpful. """
_DeadPointer
python
sqlalchemy__sqlalchemy
test/aaa_profiling/test_misc.py
{ "start": 4646, "end": 11380 }
class ____(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): __requires__ = ("cpython", "python_profiling_backend") @testing.fixture def t1(self, metadata): return Table( "t1", metadata, Column("id", Integer, primary_key=True), Column("x1", Intege...
CCLookupTest
python
Pylons__pyramid
src/pyramid/config/tweens.py
{ "start": 6979, "end": 7758 }
class ____: def __init__(self): self.sorter = TopologicalSorter( default_before=None, default_after=INGRESS, first=INGRESS, last=MAIN, ) self.explicit = [] def add_explicit(self, name, factory): self.explicit.append((name, factory)...
Tweens
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_format15.py
{ "start": 315, "end": 1644 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_format15.xlsx") def test_create_file(self): """Test the creation of a file with user defined default format""" workbook = ...
TestCompareXLSXFiles
python
davidhalter__jedi
jedi/inference/imports.py
{ "start": 5225, "end": 23087 }
class ____: def __init__(self, inference_state, import_path, module_context, level=0): """ An implementation similar to ``__import__``. Use `follow` to actually follow the imports. *level* specifies whether to use absolute or relative imports. 0 (the default) means only perf...
Importer
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001_py310.py
{ "start": 795, "end": 953 }
class ____(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) team: Team | None = Relationship(back_populates="heroes")
Hero
python
getsentry__sentry
src/sentry/api/endpoints/organization_recent_searches.py
{ "start": 581, "end": 737 }
class ____(serializers.Serializer): type = serializers.IntegerField(required=True) query = serializers.CharField(required=True)
RecentSearchSerializer
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_multi_hierarchy_base.py
{ "start": 354, "end": 1288 }
class ____(FlowMutator): """Simple mutator that logs flow information""" def pre_mutate(self, mutable_flow): print("LoggingMutator: Analyzing flow structure") param_count = sum(1 for _ in mutable_flow.parameters) config_count = sum(1 for _ in mutable_flow.configs) print(f" Foun...
LoggingMutator
python
huggingface__transformers
src/transformers/models/starcoder2/modular_starcoder2.py
{ "start": 6102, "end": 9148 }
class ____(MistralModel): def __init__(self, config: Starcoder2Config): super().__init__(config) self.layers = nn.ModuleList( [Starcoder2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = nn.LayerNorm(config.hidden_size, eps=co...
Starcoder2Model
python
ZoranPandovski__al-go-rithms
sort/bubble_sort_optimized/python/bubble_sort_optimized.py
{ "start": 0, "end": 408 }
class ____: def bubbleSortOptimized(self, nums): if len(nums) == 1: return nums else: swapped = False while not swapped: swapped = True for i in range(0, len(nums)-1): if nums[i] > nums[i+1]: ...
Solution
python
encode__starlette
starlette/routing.py
{ "start": 5813, "end": 7076 }
class ____: def matches(self, scope: Scope) -> tuple[Match, Scope]: raise NotImplementedError() # pragma: no cover def url_path_for(self, name: str, /, **path_params: Any) -> URLPath: raise NotImplementedError() # pragma: no cover async def handle(self, scope: Scope, receive: Receive, se...
BaseRoute
python
django__django
django/apps/registry.py
{ "start": 247, "end": 17707 }
class ____: """ A registry that stores the configuration of installed applications. It also keeps track of models, e.g. to provide reverse relations. """ def __init__(self, installed_apps=()): # installed_apps is set to None when creating the main registry # because it cannot be po...
Apps
python
walkccc__LeetCode
solutions/3524. Find X Value of Array I/3524.py
{ "start": 0, "end": 590 }
class ____: def resultArray(self, nums: list[int], k: int) -> list[int]: ans = [0] * k # dp[r] := the number of subarrays ending at current position with # product % k == r dp = [0] * k for num in nums: newDp = [0] * k numMod = num % k # Start new subarray with only `num` ...
Solution
python
networkx__networkx
networkx/algorithms/centrality/tests/test_group.py
{ "start": 84, "end": 3040 }
class ____: def test_group_betweenness_single_node(self): """ Group betweenness centrality for single node group """ G = nx.path_graph(5) C = [1] b = nx.group_betweenness_centrality( G, C, weight=None, normalized=False, endpoints=False ) b_...
TestGroupBetweennessCentrality
python
PyCQA__pylint
pylint/checkers/variables.py
{ "start": 47319, "end": 140475 }
class ____(BaseChecker): """BaseChecker for variables. Checks for * unused variables / imports * undefined variables * redefinition of variable from builtins or from an outer scope or except handler * use of variable before assignment * __all__ consistency * self/cls assignment """ ...
VariablesChecker
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 17278, "end": 17479 }
class ____(ProviderError): """ Raised when not connected to a provider. """ def __init__(self): super().__init__("Not connected to a network provider.")
ProviderNotConnectedError
python
altair-viz__altair
altair/utils/plugin_registry.py
{ "start": 1064, "end": 1291 }
class ____(Exception): def __init__(self, group, name): self.group = group self.name = name def __str__(self): return f"No {self.name!r} entry point found in group {self.group!r}"
NoSuchEntryPoint
python
joblib__joblib
joblib/memory.py
{ "start": 34897, "end": 45404 }
class ____(Logger): """A context object for caching a function's return value each time it is called with the same input arguments. All values are cached on the filesystem, in a deep directory structure. Read more in the :ref:`User Guide <memory>`. Parameters ---------- location: str,...
Memory
python
getsentry__sentry
src/sentry/release_health/metrics_sessions_v2.py
{ "start": 6998, "end": 9230 }
class ____(Field): """Base class for sum(sessions) and count_unique(user)""" status_to_metric_field: Mapping[SessionStatus | None, MetricField] = {} def get_all_field(self) -> MetricField: return self.status_to_metric_field[None] def _get_metric_fields( self, raw_groupby: Sequence[str...
CountField
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/pools.py
{ "start": 1910, "end": 2063 }
class ____(BaseModel): """Pool Collection serializer for responses.""" pools: Iterable[PoolResponse] total_entries: int
PoolCollectionResponse
python
huggingface__transformers
src/transformers/models/llava_next_video/modeling_llava_next_video.py
{ "start": 3445, "end": 5267 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the lan...
LlavaNextVideoCausalLMOutputWithPast
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 15201, "end": 15664 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) ...
EsmSelfOutput
python
pydantic__pydantic
.github/actions/people/people.py
{ "start": 6022, "end": 6304 }
class ____(BaseModel): """Represents a GitHub pull request with its metadata and interactions.""" number: int labels: Labels author: Author | None = None title: str createdAt: datetime state: str comments: Comments reviews: Reviews
PullRequestNode
python
pytorch__pytorch
test/distributed/checkpoint/test_consolidate_hf_safetensors.py
{ "start": 876, "end": 14312 }
class ____(DTensorTestBase): def _create_d_tensors(self) -> None: global_tensor = torch.arange(16, dtype=torch.float).view(4, 4) mesh_shape = (self.world_size,) mesh_1d = init_device_mesh(self.device_type, mesh_shape) # Create local tensor with row-wise sharding rows_per_ran...
TestConsolidateHFSafeTensors
python
django__django
django/utils/archive.py
{ "start": 6781, "end": 8301 }
class ____(BaseArchive): def __init__(self, file): self._archive = zipfile.ZipFile(file) def list(self, *args, **kwargs): self._archive.printdir(*args, **kwargs) def extract(self, to_path): namelist = self._archive.namelist() leading = self.has_leading_dir(namelist) ...
ZipArchive
python
django__django
tests/model_forms/tests.py
{ "start": 29508, "end": 32019 }
class ____(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form["name"]), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" ' "required></textarea>", ) self.asse...
TestFieldOverridesByFormMeta
python
oauthlib__oauthlib
oauthlib/openid/connect/core/grant_types/refresh_token.py
{ "start": 292, "end": 1035 }
class ____(GrantTypeBase): def __init__(self, request_validator=None, **kwargs): self.proxy_target = OAuth2RefreshTokenGrant( request_validator=request_validator, **kwargs) self.register_token_modifier(self.add_id_token) def add_id_token(self, token, token_handler, request): ...
RefreshTokenGrant
python
getsentry__sentry
tests/sentry/utils/sdk_crashes/test_sdk_crash_detection_cocoa.py
{ "start": 2943, "end": 20876 }
class ____(BaseSDKCrashDetectionMixin): def test_unhandled_is_detected(self, mock_sdk_crash_reporter: MagicMock) -> None: self.execute_test(get_crash_event(), True, mock_sdk_crash_reporter) def test_handled_is_not_detected(self, mock_sdk_crash_reporter: MagicMock) -> None: self.execute_test(get...
CococaSDKTestMixin
python
networkx__networkx
networkx/classes/tests/test_coreviews.py
{ "start": 6192, "end": 7833 }
class ____: # node->nbr->data def setup_method(self): dd = {"color": "blue", "weight": 1.2} self.nd = {0: dd, 1: {}, 2: {"color": 1}} self.s = {3: self.nd, 0: {}, 1: {}, 2: {3: {"color": 1}}} self.p = {3: {}, 0: {3: dd}, 1: {0: {}}, 2: {1: {"color": 1}}} self.adjview = nx...
TestUnionAdjacency
python
ApeWorX__ape
tests/functional/test_plugins.py
{ "start": 15248, "end": 17379 }
class ____: @parametrize_pip_cmd def test_prepare_package_manager_args_with_python_location(self, pip_command, mock_python_path): metadata = PluginMetadata(name="test", pip_command=pip_command) args = metadata.prepare_package_manager_args("install", python_location=mock_python_path) ex...
TestBuildPipArgs
python
eth-brownie__brownie
brownie/utils/_color.py
{ "start": 2272, "end": 8088 }
class ____: __cache__: Final[Dict[Optional[str], str]] = {} def __call__(self, color_str: Optional[str] = None) -> str: if not CONFIG.settings["console"]["show_colors"]: return "" try: return Color.__cache__[color_str] except KeyError: if not color_st...
Color