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
tensorflow__tensorflow
tensorflow/python/autograph/utils/type_registry.py
{ "start": 767, "end": 1955 }
class ____(object): """Provides a type registry for the python registry pattern. Contains mappings between types and type specific objects, to implement the registry pattern. Some example uses of this would be to register different functions depending on the type of object. """ def __init__(self): ...
TypeRegistry
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
{ "start": 1274, "end": 1428 }
class ____(BaseInfoResponse): """DagProcessor info serializer for responses.""" latest_dag_processor_heartbeat: str | None
DagProcessorInfoResponse
python
encode__django-rest-framework
tests/test_relations_pk.py
{ "start": 1198, "end": 1445 }
class ____(serializers.ModelSerializer): first_source = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = ForeignKeyTarget fields = ('id', 'name', 'first_source')
ForeignKeyTargetPropertySourceSerializer
python
PrefectHQ__prefect
src/prefect/server/schemas/sorting.py
{ "start": 3221, "end": 3756 }
class ____(AutoEnum): """Defines log sorting options.""" TIMESTAMP_ASC = AutoEnum.auto() TIMESTAMP_DESC = AutoEnum.auto() @db_injector def as_sql_sort(self, db: "PrefectDBInterface") -> Iterable[sa.ColumnElement[Any]]: """Return an expression used to sort task runs""" sort_mapping:...
LogSort
python
langchain-ai__langchain
libs/partners/ollama/tests/unit_tests/test_auth.py
{ "start": 3687, "end": 5881 }
class ____: """Test URL authentication integration with ChatOllama.""" @patch("langchain_ollama.chat_models.Client") @patch("langchain_ollama.chat_models.AsyncClient") def test_chat_ollama_url_auth_integration( self, mock_async_client: MagicMock, mock_client: MagicMock ) -> None: ""...
TestChatOllamaUrlAuth
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 31417, "end": 31695 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the resource is locked. code: 423, title: Locked """ # Note: from WebDAV code = 423 title = 'Locked' explanation = 'The resource is locked'
HTTPLocked
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_requests/posts_request_builder.py
{ "start": 302, "end": 1660 }
class ____(ZendeskSupportBaseRequestBuilder): @classmethod def posts_endpoint(cls, authenticator: Authenticator) -> "PostsRequestBuilder": return cls("d3v-airbyte", "community/posts").with_authenticator(authenticator) def __init__(self, subdomain: str, resource: str) -> None: super().__init...
PostsRequestBuilder
python
networkx__networkx
networkx/generators/tests/test_intersection.py
{ "start": 39, "end": 819 }
class ____: def test_random_intersection_graph(self): G = nx.uniform_random_intersection_graph(10, 5, 0.5) assert len(G) == 10 def test_k_random_intersection_graph(self): G = nx.k_random_intersection_graph(10, 5, 2) assert len(G) == 10 def test_k_random_intersection_graph_s...
TestIntersectionGraph
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 60409, "end": 63945 }
class ____(GeneratedAirbyteDestination): class Unencrypted: @public def __init__( self, ): self.encryption_method = "unencrypted" class NativeNetworkEncryptionNNE: @public def __init__(self, encryption_algorithm: Optional[str] = None): ...
OracleDestination
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/looker/customize-looker-assets.py
{ "start": 386, "end": 1330 }
class ____(DagsterLookerApiTranslator): def get_asset_spec( self, looker_structure: LookerApiTranslatorStructureData ) -> dg.AssetSpec: # We create the default asset spec using super() default_spec = super().get_asset_spec(looker_structure) # We customize the team owner tag for a...
CustomDagsterLookerApiTranslator
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type_test.py
{ "start": 39945, "end": 47257 }
class ____( test_util.TensorFlowTestCase, parameterized.TestCase ): def testSpecConstructor(self): values_spec = tensor.TensorSpec([4], dtypes.float32) mask_spec = tensor.TensorSpec([4], dtypes.bool) mt_spec = MaskedTensorV1.Spec(values_spec, mask_spec) self.assertEqual(mt_spec.values, values_spe...
ExtensionTypeSpecTest
python
walkccc__LeetCode
solutions/1786. Number of Restricted Paths From First to Last Node/1786.py
{ "start": 0, "end": 992 }
class ____: def countRestrictedPaths(self, n: int, edges: list[list[int]]) -> int: graph = [[] for _ in range(n)] for u, v, w in edges: graph[u - 1].append((v - 1, w)) graph[v - 1].append((u - 1, w)) return self._dijkstra(graph, 0, n - 1) def _dijkstra( self, graph: list[list[...
Solution
python
pytorch__pytorch
torch/_functorch/_aot_autograd/runtime_wrappers.py
{ "start": 41930, "end": 66474 }
class ____(CompilerWrapper): # Currently, the only reason we need to plumb this bool is because # the synthetic base code prohibits more cases in the autograd case than the inference case. trace_joint: bool # TODO: refactor trace_joint needs_post_compile: bool = True aliased_arg_idx_with_metadata_m...
AOTSyntheticBaseWrapper
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/processors.py
{ "start": 18980, "end": 19813 }
class ____(Processor): """ Append the auto suggestion to the input. (The user can then press the right arrow the insert the suggestion.) """ def __init__(self, style: str = "class:auto-suggestion") -> None: self.style = style def apply_transformation(self, ti: TransformationInput) -> T...
AppendAutoSuggestion
python
sqlalchemy__sqlalchemy
test/orm/test_subquery_relations.py
{ "start": 96577, "end": 103674 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL ): __dialect__ = "default" run_inserts = "once" run_deletes = None @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Director(Base): __tablename__ = "director" i...
SubqueryloadDistinctTest
python
django__django
tests/decorators/test_gzip.py
{ "start": 188, "end": 1605 }
class ____(SimpleTestCase): # Gzip ignores content that is too short. content = "Content " * 100 def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = gzip_page(sync_view) self.assertIs(iscoroutinefu...
GzipPageTests
python
scipy__scipy
benchmarks/benchmarks/spatial.py
{ "start": 15527, "end": 16562 }
class ____(Benchmark): params = (['euclidean', 'minkowski', 'cityblock', 'sqeuclidean', 'cosine', 'correlation', 'hamming', 'jaccard', 'chebyshev', 'canberra', 'braycurtis', 'yule', 'dice', 'rogerstanimoto', 'russellrao', 'sokalsneath', 'minkowski-P3']) param_names =...
SingleDistWeighted
python
kamyu104__LeetCode-Solutions
Python/minimum-incompatibility.py
{ "start": 6348, "end": 10052 }
class ____(object): P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation MAX_LEVEL = 32 # enough for 2^32 elements def __init__(self, end=float("inf"), can_duplicated=False, cmp=lambda x, y: x < y): seed(0) self.__head = SkipNode() self.__len = 0 self.__can_...
SkipList
python
sqlalchemy__sqlalchemy
test/orm/test_unitofworkv2.py
{ "start": 100684, "end": 113195 }
class ____( testing.AssertsExecutionResults, fixtures.TestBase ): __sparse_driver_backend__ = True @variation_fixture("eager_defaults", ["unspecified", "auto", True, False]) def eager_defaults_variations(self, request): yield request.param @variation_fixture("implicit_returning", [True, Fa...
EagerDefaultsSettingTest
python
numpy__numpy
numpy/f2py/tests/test_semicolon_split.py
{ "start": 329, "end": 1056 }
class ____(util.F2PyTest): suffix = ".pyf" module_name = "multiline" code = f""" python module {module_name} usercode ''' void foo(int* x) {{ char dummy = ';'; *x = 42; }} ''' interface subroutine foo(x) intent(c) foo integer intent(out) :: x end subro...
TestMultiline
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/compiler.py
{ "start": 19186, "end": 19579 }
class ____(IntEnum): COMPILING = 0 """statement is present, compilation phase in progress""" STRING_APPLIED = 1 """statement is present, string form of the statement has been applied. Additional processors by subclasses may still be pending. """ NO_STATEMENT = 2 """compiler does not ...
CompilerState
python
sympy__sympy
sympy/logic/algorithms/lra_theory.py
{ "start": 4813, "end": 5129 }
class ____(Exception): """ Raised while creating an LRASolver if non-linearity or non-rational numbers are present. """ # predicates that LRASolver understands and makes use of ALLOWED_PRED = {Q.eq, Q.gt, Q.lt, Q.le, Q.ge} # if true ~Q.gt(x, y) implies Q.le(x, y) HANDLE_NEGATION = True
UnhandledInput
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 39261, "end": 39445 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("ALL", "DAY", "MONTH", "WEEK")
SponsorsActivityPeriod
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/query.py
{ "start": 120161, "end": 120321 }
class ____(Query[Row[Unpack[_Ts]]]): if TYPE_CHECKING: def tuples(self) -> Query[Tuple[Unpack[_Ts]]]: # type: ignore ...
RowReturningQuery
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/deprecated2.py
{ "start": 406, "end": 1283 }
class ____: @deprecated("Don't temp me") def method1(self) -> None: ... @overload @deprecated("Int is no longer supported") def method2(self, a: int) -> None: ... @overload def method2(self, a: None = None) -> None: ... def method2(self, a: int | None = None) -> None: ... c1 = Class...
ClassC
python
neetcode-gh__leetcode
python/1299-replace-elements-with-greatest-element-on-right-side.py
{ "start": 0, "end": 265 }
class ____: def replaceElements(self, arr: List[int]) -> List[int]: rightMax = -1 for i in range(len(arr) -1, -1, -1): newMax = max(rightMax, arr[i]) arr[i] = rightMax rightMax = newMax return arr
Solution
python
python-openxml__python-docx
src/docx/styles/style.py
{ "start": 736, "end": 5131 }
class ____(ElementProxy): """Base class for the various types of style object, paragraph, character, table, and numbering. These properties and methods are inherited by all style objects. """ def __init__(self, style_elm: CT_Style): super().__init__(style_elm) self._style_elm = sty...
BaseStyle
python
scrapy__scrapy
tests/test_utils_defer.py
{ "start": 11398, "end": 12434 }
class ____: @deferred_f_from_coro_f async def test_deferred(self): d = Deferred() result = maybe_deferred_to_future(d) assert isinstance(result, Future) d.callback(42) future_result = await result assert future_result == 42 @deferred_f_from_coro_f async d...
TestMaybeDeferredToFutureAsyncio
python
pytorch__pytorch
tools/linter/adapters/_linter/file_linter.py
{ "start": 614, "end": 6459 }
class ____: """The base class that all token-based linters inherit from""" description: str linter_name: str epilog: str | None = None is_fixer: bool = True report_column_numbers: bool = False @abstractmethod def _lint(self, python_file: PythonFile) -> Iterator[LintResult]: ra...
FileLinter
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_dataprep.py
{ "start": 25093, "end": 35182 }
class ____: _url = "https://api.clouddataprep.com/v4/flows" def setup_method(self): self._flow_id = 1234567 self._create_flow_body_request = { "name": "test_name", "description": "Test description", } self._expected_copy_flow_hook_data = json.dumps( ...
TestGoogleDataprepFlowPathHooks
python
django-haystack__django-haystack
test_haystack/mocks.py
{ "start": 3844, "end": 4666 }
class ____(MockSearchBackend): @log_query def search(self, query_string, **kwargs): if kwargs.get("end_offset") and kwargs["end_offset"] > 30: kwargs["end_offset"] = 30 result_info = super().search(query_string, **kwargs) result_info["hits"] = 30 # Remove search res...
MixedMockSearchBackend
python
kamyu104__LeetCode-Solutions
Python/range-sum-query-immutable.py
{ "start": 60, "end": 527 }
class ____(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.accu = [0] for num in nums: self.accu.append(self.accu[-1] + num), def sumRange(self, i, j): """ sum of elements nums...
NumArray
python
tensorflow__tensorflow
tensorflow/python/framework/constant_op_test.py
{ "start": 1295, "end": 4853 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters( dtypes.bfloat16, dtypes.complex128, dtypes.complex64, dtypes.double, dtypes.float16, dtypes.float32, dtypes.float64, dtypes.half, dtypes.int16, dtypes.int32, dtypes.int64, ...
ConstantOpTest
python
astropy__astropy
astropy/table/row.py
{ "start": 236, "end": 7181 }
class ____: """A class to represent one row of a Table object. A Row object is returned when a Table object is indexed with an integer or when iterating over a table:: >>> from astropy.table import Table >>> table = Table([(1, 2), (3, 4)], names=('a', 'b'), ... dtype=('int3...
Row
python
GoogleCloudPlatform__python-docs-samples
appengine/flexible/django_cloudsql/polls/test_polls.py
{ "start": 632, "end": 832 }
class ____(TestCase): def test_index_view(self): response = self.client.get("/") assert response.status_code == 200 assert "Hello, world" in str(response.content)
PollViewTests
python
keras-team__keras
keras/src/layers/pooling/max_pooling2d.py
{ "start": 181, "end": 4128 }
class ____(BasePooling): """Max pooling operation for 2D spatial data. Downsamples the input along its spatial dimensions (height and width) by taking the maximum value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each...
MaxPooling2D
python
requests__requests-oauthlib
tests/examples/base.py
{ "start": 2985, "end": 4708 }
class ____(): def setUp(self): super().setUp() options = webdriver.ChromeOptions() options.add_argument("--headless=new") self.driver = webdriver.Chrome(options=options) self.user_username = os.environ.get("AUTH0_USERNAME") self.user_password = os.environ.get("AUTH0_P...
Browser
python
tensorflow__tensorflow
tensorflow/core/function/transform/transform_test.py
{ "start": 2398, "end": 15837 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.named_parameters( dict( testcase_name="transform", transform_fn=add_to_multiply, mlir_pipeline=None), dict( testcase_name="mlir_pipeline", transform_fn=None, mlir_pipeline="test-p...
TransformTest
python
PrefectHQ__prefect
src/prefect/settings/profiles.py
{ "start": 1448, "end": 3378 }
class ____(BaseModel): """A user profile containing settings.""" model_config: ClassVar[ConfigDict] = ConfigDict( extra="ignore", arbitrary_types_allowed=True ) name: str settings: Annotated[dict[Setting, Any], BeforeValidator(_cast_settings)] = Field( default_factory=dict ) ...
Profile
python
huggingface__transformers
src/transformers/models/evolla/modeling_evolla.py
{ "start": 15026, "end": 16242 }
class ____(nn.Module): def __init__(self, config, layer_idx=None, is_cross_attention=False): super().__init__() self.self = EvollaSaProtSelfAttention(config, layer_idx=layer_idx, is_cross_attention=is_cross_attention) self.output = EvollaSaProtSelfOutput(config) self.LayerNorm = nn....
EvollaSaProtAttention
python
astropy__astropy
astropy/io/ascii/fastbasic.py
{ "start": 10381, "end": 12634 }
class ____(FastBasic): """ A faster version of the :class:`CommentedHeader` reader, which looks for column names in a commented line. ``header_start`` denotes the index of the header line among all commented lines and is 0 by default. """ _format_name = "fast_commented_header" _description ...
FastCommentedHeader
python
tensorflow__tensorflow
tensorflow/compiler/tests/sparse_to_dense_op_test.py
{ "start": 1533, "end": 4615 }
class ____(xla_test.XLATestCase): def testInt(self): with self.session(), self.test_scope(): tf_ans = _SparseToDense([1, 3], [5], 1, 0) np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32) self.assertAllClose(np_ans, tf_ans) def testFloat(self): with self.session(), self.test_scope(): t...
SparseToDenseTest
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 139227, "end": 140500 }
class ____(Response): """ Response of events.next_debug_image_sample endpoint. """ _service = "events" _action = "next_debug_image_sample" _version = "2.20" _schema = { "$ref": "#/definitions/debug_image_sample_response", "definitions": { "debug_image_sample_res...
NextDebugImageSampleResponse
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_bitcoin_address.py
{ "start": 1921, "end": 4681 }
class ____(ColumnMapExpectation): """Expect column values to be valid Bitcoin addresses.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [ ...
ExpectColumnValuesToBeValidBitcoinAddress
python
Textualize__textual
docs/examples/widgets/data_table_sort.py
{ "start": 862, "end": 3234 }
class ____(App): BINDINGS = [ ("a", "sort_by_average_time", "Sort By Average Time"), ("n", "sort_by_last_name", "Sort By Last Name"), ("c", "sort_by_country", "Sort By Country"), ("d", "sort_by_columns", "Sort By Columns (Only)"), ] current_sorts: set = set() def compos...
TableApp
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 6703, "end": 7765 }
class ____(BiffRecord): """ Offset Size Contents 0 2 Version, contains 0600H for BIFF8 and BIFF8X 2 2 Type of the following data: 0005H = Workbook globals 0006H = Visual Basic module 0010H = Worksheet 0020H = Chart ...
Biff8BOFRecord
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/compute.py
{ "start": 1872, "end": 40483 }
class ____(GoogleBaseHook): """ Hook for Google Compute Engine APIs. All the methods in the hook where project_id is used must be called with keyword arguments rather than positional. """ def __init__( self, api_version: str = "v1", gcp_conn_id: str = "google_cloud_defa...
ComputeEngineHook
python
fastapi__sqlmodel
docs_src/tutorial/one/tutorial009_py310.py
{ "start": 63, "end": 1506 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, ec...
Hero
python
getsentry__sentry
src/sentry/integrations/github/integration.py
{ "start": 9203, "end": 32582 }
class ____( RepositoryIntegration, GitHubIssuesSpec, IssueSyncIntegration, CommitContextIntegration, RepoTreesIntegration, ): integration_name = IntegrationProviderSlug.GITHUB # IssueSyncIntegration configuration keys comment_key = "sync_comments" outbound_status_key = "sync_status_...
GitHubIntegration
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_select.py
{ "start": 57754, "end": 59371 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True __requires__ = ("supports_is_distinct_from",) @classmethod def define_tables(cls, metadata): Table( "is_distinct_test", metadata, Column("id", Integer, primary_key=True), Column("co...
IsOrIsNotDistinctFromTest
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 440810, "end": 441087 }
class ____(VegaLiteSchema): """ Geometry schema wrapper. Geometry object. https://tools.ietf.org/html/rfc7946#section-3 """ _schema = {"$ref": "#/definitions/Geometry"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
Geometry
python
ray-project__ray
python/ray/tests/test_actor_retry_1.py
{ "start": 40, "end": 89 }
class ____(Exception): pass @ray.remote
MyError
python
numba__numba
numba/core/controlflow.py
{ "start": 2651, "end": 23385 }
class ____(object): """ Generic (almost) implementation of a Control Flow Graph. """ def __init__(self): self._nodes = set() self._preds = _DictOfContainers(set) self._succs = _DictOfContainers(set) self._edge_data = {} self._entry_point = None def add_node(...
CFGraph
python
kamyu104__LeetCode-Solutions
Python/shortest-string-that-contains-three-strings.py
{ "start": 81, "end": 1521 }
class ____(object): def minimumString(self, a, b, c): """ :type a: str :type b: str :type c: str :rtype: str """ def getPrefix(pattern): prefix = [-1]*len(pattern) j = -1 for i in xrange(1, len(pattern)): whi...
Solution
python
bokeh__bokeh
src/bokeh/util/callback_manager.py
{ "start": 2324, "end": 4349 }
class ____: ''' A mixin class to provide an interface for registering and triggering event callbacks on the Python side. ''' document: Document | None id: ID subscribed_events: set[str] _event_callbacks: dict[str, list[EventCallback]] def __init__(self, *args: Any, **kw: Any) -> None:...
EventCallbackManager
python
xlwings__xlwings
xlwings/_xlmac.py
{ "start": 45353, "end": 48969 }
class ____(base_classes.Table): def __init__(self, parent, key): self._parent = parent self.xl = parent.xl.list_objects[key] @property def parent(self): return self._parent @property def api(self): return self.xl @property def name(self): return sel...
Table
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
{ "start": 11965, "end": 12431 }
class ____(PreTrainedModel): config: Qwen2_5_VLConfig base_model_prefix = "model" input_modalities = ("image", "video", "text") supports_gradient_checkpointing = True _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"] _skip_keys_device_placement = "past_key_values" _supp...
Qwen2_5_VLPreTrainedModel
python
doocs__leetcode
solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py
{ "start": 152, "end": 545 }
class ____: def levelOrder(self, root: 'Node') -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) while q: t = [] for _ in range(len(q)): root = q.popleft() t.append(root.val) ...
Solution
python
getsentry__sentry
src/sentry/models/files/fileblobowner.py
{ "start": 246, "end": 537 }
class ____(AbstractFileBlobOwner): __relocation_scope__ = RelocationScope.Excluded blob = FlexibleForeignKey("sentry.FileBlob") class Meta: app_label = "sentry" db_table = "sentry_fileblobowner" unique_together = (("blob", "organization_id"),)
FileBlobOwner
python
sanic-org__sanic
sanic/logging/formatter.py
{ "start": 732, "end": 3989 }
class ____(logging.Formatter): """ Automatically sets up the formatter based on the environment. It will switch between the Debug and Production formatters based upon how the environment is set up. Additionally, it will automatically detect if the output is a TTY and colorize the output accordingly...
AutoFormatter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_types07.py
{ "start": 315, "end": 1937 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("types07.xlsx") self.ignore_files = [ "xl/calcChain.xml", "[Content_Types].xml", "xl/_rels/workbook.xml.rels...
TestCompareXLSXFiles
python
scikit-learn__scikit-learn
doc/sphinxext/allow_nan_estimators.py
{ "start": 270, "end": 2187 }
class ____(Directive): @staticmethod def make_paragraph_for_estimator_type(estimator_type): intro = nodes.list_item() intro += nodes.strong(text="Estimators that allow NaN values for type ") intro += nodes.literal(text=f"{estimator_type}") intro += nodes.strong(text=":\n") ...
AllowNanEstimators
python
doocs__leetcode
solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/Solution.py
{ "start": 0, "end": 1124 }
class ____: def maxProduct(self, s: str) -> int: n = len(s) hlen = [0] * n center = right = 0 for i in range(n): if i < right: hlen[i] = min(right - i, hlen[2 * center - i]) while ( 0 <= i - 1 - hlen[i] and i + ...
Solution
python
mlflow__mlflow
mlflow/genai/scorers/builtin_scorers.py
{ "start": 9300, "end": 12023 }
class ____(Judge): """ Abstract base class for built-in scorers that share a common implementation. All built-in scorers should inherit from this class. """ name: str required_columns: set[str] = set() @property @abstractmethod def instructions(self) -> str: """ Get...
BuiltInScorer
python
dateutil__dateutil
src/dateutil/rrule.py
{ "start": 50715, "end": 54400 }
class ____(rrulebase): """ The rruleset type allows more complex recurrence setups, mixing multiple rules, dates, exclusion rules, and exclusion dates. The type constructor takes the following keyword arguments: :param cache: If True, caching of results will be enabled, improving perf...
rruleset
python
ray-project__ray
python/ray/train/v2/_internal/execution/worker_group/poll.py
{ "start": 3866, "end": 4111 }
class ____: """Represents a poll task for a worker. Attributes: start_time: The time when the poll task was started. task: The ObjectRef representing the poll task. """ start_time: float task: ObjectRef
PollTask
python
scrapy__scrapy
tests/mockserver/ftp.py
{ "start": 377, "end": 1638 }
class ____: """Creates an FTP server on port 2121 with a default passwordless user (anonymous) and a temporary root path that you can read from the :attr:`path` attribute.""" def __enter__(self): self.path = Path(mkdtemp()) self.proc = Popen( [sys.executable, "-u", "-m", "te...
MockFTPServer
python
ansible__ansible
lib/ansible/module_utils/urls.py
{ "start": 10513, "end": 10824 }
class ____(urllib.request.HTTPHandler): """Handler for Unix urls""" def __init__(self, unix_socket, **kwargs): super().__init__(**kwargs) self._unix_socket = unix_socket def http_open(self, req): return self.do_open(UnixHTTPConnection(self._unix_socket), req)
UnixHTTPHandler
python
huggingface__transformers
src/transformers/models/regnet/modeling_regnet.py
{ "start": 9341, "end": 10435 }
class ____(PreTrainedModel): config: RegNetConfig base_model_prefix = "regnet" main_input_name = "pixel_values" _no_split_modules = ["RegNetYLayer"] @torch.no_grad() def _init_weights(self, module): if isinstance(module, nn.Conv2d): init.kaiming_normal_(module.weight, mode="...
RegNetPreTrainedModel
python
joblib__joblib
joblib/externals/loky/backend/process.py
{ "start": 1683, "end": 2018 }
class ____(bytes): def __reduce__(self): try: assert_spawning(self) except RuntimeError: raise TypeError( "Pickling an AuthenticationKey object is " "disallowed for security reasons" ) return AuthenticationKey, (bytes(self),...
AuthenticationKey
python
walkccc__LeetCode
solutions/144. Binary Tree Preorder Traversal/144-2.py
{ "start": 0, "end": 341 }
class ____: def preorderTraversal(self, root: TreeNode | None) -> list[int]: if not root: return [] ans = [] stack = [root] while stack: node = stack.pop() ans.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left)...
Solution
python
pytorch__pytorch
test/distributed/checkpoint/test_dtensor_resharding.py
{ "start": 6060, "end": 12716 }
class ____(DTensorTestBase): """ Test DCP reshard for DTensor with placements changes and mesh_tensor change. """ @with_comms @with_temp_dir @skip_if_lt_x_gpu(2) def test_1d_to_2d_reshard_mesh_change(self) -> None: CHECKPOINT_DIR = self.temp_dir for placements_1d in ONE_D_PL...
TestDTensorReshardMeshChange
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 20912, "end": 21151 }
class ____: @classmethod def _type_fixture(cls): return MutableSet def teardown_test(self): # clear out mapper events Mapper.dispatch._clear() ClassManager.dispatch._clear()
_MutableSetTestFixture
python
facebook__pyre-check
tools/incremental_test/runner.py
{ "start": 6937, "end": 7330 }
class ____: full_check_output: List[PyreError] incremental_check_output: List[PyreError] def to_json(self) -> Dict[str, Any]: return { "full_check_output": [asdict(e) for e in self.full_check_output], "incremental_check_output": [ asdict(e) for e in self.incr...
InconsistentOutput
python
jina-ai__jina
jina/serve/executors/__init__.py
{ "start": 3404, "end": 5047 }
class ____(type(JAMLCompatible), type): """The class of Executor type, which is the metaclass of :class:`BaseExecutor`.""" def __new__(cls, *args, **kwargs): """ # noqa: DAR101 # noqa: DAR102 :return: Executor class """ _cls = super().__new__(cls, *args, **kwarg...
ExecutorType
python
walkccc__LeetCode
solutions/400. Nth Digit/400.py
{ "start": 0, "end": 528 }
class ____: def findNthDigit(self, n: int) -> int: def getDigit(num: int, pos: int, digitSize: int): if pos == 0: return num % 10 for _ in range(digitSize - pos): num //= 10 return num % 10 digitSize = 1 startNum = 1 count = 9 while digitSize * count < n: ...
Solution
python
pytorch__pytorch
test/inductor/test_compile_worker.py
{ "start": 3646, "end": 4826 }
class ____(TestCase): def test_basics(self): done = Event() def doit(): done.set() t = Timer(0.1, doit) t.sleep_time = 0.1 t.record_call() self.assertTrue(done.wait(4)) t.quit() def test_repeated_calls(self): done = Event() ...
TestTimer
python
chardet__chardet
chardet/chardistribution.py
{ "start": 5429, "end": 6195 }
class ____(CharDistributionAnalysis): def __init__(self) -> None: super().__init__() self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER self._table_size = EUCKR_TABLE_SIZE self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO def get_order(self, byte_str: Union[byt...
EUCKRDistributionAnalysis
python
realpython__materials
python-built-in-functions/shapes.py
{ "start": 247, "end": 345 }
class ____(Rectangle): def __init__(self, length): super().__init__(length, length)
Square
python
faif__python-patterns
patterns/structural/flyweight_with_metaclass.py
{ "start": 17, "end": 1117 }
class ____(type): def __new__(mcs, name, parents, dct): """ Set up object pool :param name: class name :param parents: class parents :param dct: dict: includes class attributes, class methods, static methods, etc :return: new class """ dct["po...
FlyweightMeta
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 193662, "end": 196349 }
class ____(rv_continuous): r"""A Levy continuous random variable. %(before_notes)s See Also -------- levy_stable, levy_l Notes ----- The probability density function for `levy` is: .. math:: f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{1}{2x}\right) for :math:`...
levy_gen
python
pennersr__django-allauth
allauth/headless/account/views.py
{ "start": 9796, "end": 10423 }
class ____(APIView): input_class = RequestPasswordResetInput def post(self, request, *args, **kwargs): r429 = ratelimit.consume_or_429( self.request, action="reset_password", key=self.input.cleaned_data["email"].lower(), ) if r429: return ...
RequestPasswordResetView
python
python-poetry__poetry
src/poetry/puzzle/solver.py
{ "start": 10160, "end": 20289 }
class ____(DFSNode): def __init__( self, package: Package, packages: list[Package], previous: PackageNode | None = None, dep: Dependency | None = None, marker: BaseMarker | None = None, ) -> None: self.package = package self.packages = packages ...
PackageNode
python
tensorflow__tensorflow
tensorflow/python/autograph/tests/cond_basic_test.py
{ "start": 3491, "end": 8321 }
class ____(reference_test_base.TestCase, parameterized.TestCase): @parameterized.parameters(*itertools.product( ( if_no_vars, if_else_no_vars, ), ( True, False, ), ( bool, tf.constant, ), )) def test_no_vars(self, tar...
ReferenceTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/image_ops/draw_bounding_box_op_test.py
{ "start": 1214, "end": 6369 }
class ____(test.TestCase): def _fillBorder(self, image, color): """Fill the border of the image. Args: image: Numpy array of shape [height, width, depth]. color: Numpy color of shape [depth] and either contents RGB/RGBA. Returns: image of original shape with border filled with "color"...
DrawBoundingBoxOpTest
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 11417, "end": 11561 }
class ____(desc_sig_element, _sig_element=True): """Node for a numeric literal in a signature.""" classes = ['m']
desc_sig_literal_number
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 11011, "end": 11142 }
class ____: fqn: Annotated[str, 10] signature: Annotated[Optional[ModuleCallSignature], 30] = None @dataclass
ModuleCallEntry
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 3033, "end": 4039 }
class ____(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def testBuildGraph(self): with self.cached_session(): pt = test_ops.stub_resource_handle_op(container="a", shared_name="b") test_ops.resource_create_op(pt).run() @test_util.run_deprecated_v1 def testInitialize(self): wi...
ResourceTest
python
kamyu104__LeetCode-Solutions
Python/shortest-distance-from-all-buildings.py
{ "start": 75, "end": 1625 }
class ____(object): def shortestDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ def bfs(grid, dists, cnts, x, y): dist, m, n = 0, len(grid), len(grid[0]) visited = [[False for _ in xrange(n)] for _ in xrange(m)] pre_l...
Solution
python
python__mypy
mypy/nodes.py
{ "start": 77304, "end": 78332 }
class ____(Expression): """Comparison expression (e.g. a < b > c < d).""" __slots__ = ("operators", "operands", "method_types") __match_args__ = ("operands", "operators") operators: list[str] operands: list[Expression] # Inferred type for the operator methods (when relevant; None for 'is'). ...
ComparisonExpr
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 579819, "end": 580394 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("admin", "client_mutation_id", "enterprise", "message", "viewer") admin = sgqlc.types.Field("User", graphql_name="admin") client_mutation_id = sgqlc.types.Field(String, graphq...
RemoveEnterpriseAdminPayload
python
virgili0__Virgilio
Tools/regex-bin/regexPrinter.py
{ "start": 1346, "end": 1607 }
class ____(object): def __init__(self, token, value, next_node): self.token = token self.value = value self.next_node = next_node def print(self): raise NotImplementedError("This should be overriden in subclasses")
TreeNode
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 7104, "end": 7202 }
class ____(GISLookup): lookup_name = "disjoint" @BaseSpatialField.register_lookup
DisjointLookup
python
optuna__optuna
tests/terminator_tests/test_terminator.py
{ "start": 419, "end": 2325 }
class ____(BaseImprovementEvaluator): def __init__(self, constant: float) -> None: super().__init__() self._constant = constant def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float: return self._constant def test_init() -> None: # Test that a pos...
_StaticImprovementEvaluator
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 42350, "end": 43143 }
class ____(BaseAsyncRealtimeConnectionResource): async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: """**WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to stop generating audio and emit a `output_audio_buffer.cleared` event. This...
AsyncRealtimeOutputAudioBufferResource
python
mahmoud__boltons
boltons/queueutils.py
{ "start": 3293, "end": 6774 }
class ____: """The abstract base class for the other PriorityQueues in this module. Override the ``_backend_type`` class attribute, as well as the :meth:`_push_entry` and :meth:`_pop_entry` staticmethods for custom subclass behavior. (Don't forget to use :func:`staticmethod`). Args: pri...
BasePriorityQueue
python
numpy__numpy
numpy/ma/tests/test_core.py
{ "start": 2684, "end": 40852 }
class ____: # Base test class for MaskedArrays. # message for warning filters def _create_data(self): # Base data definition. x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10...
TestMaskedArray
python
tensorflow__tensorflow
tensorflow/python/ops/nn_test.py
{ "start": 72975, "end": 76452 }
class ____(parameterized.TestCase, test_lib.TestCase): @test_util.run_in_graph_and_eager_modes def test_increasing_and_decreasing(self): x = constant_op.constant([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=dtypes.float64) y, segments = nn_ops.isotonic_regression(x, decreasing=Fal...
IsotonicTest
python
tornadoweb__tornado
tornado/httpserver.py
{ "start": 14927, "end": 16131 }
class ____(httputil.HTTPMessageDelegate): def __init__( self, delegate: httputil.HTTPMessageDelegate, request_conn: httputil.HTTPConnection, ) -> None: self.connection = request_conn self.delegate = delegate def headers_received( self, start_line: Uni...
_ProxyAdapter
python
huggingface__transformers
tests/models/bloom/test_modeling_bloom.py
{ "start": 1069, "end": 7232 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = BloomModel def create_and_check_bloom_model_past(self, config, *args): input_ids, _, input_mask, _, _, _ = args model = BloomModel(config=config) model.to(torch_device) model.eval() # ...
BloomModelTester