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/test_relationships.py
{ "start": 182179, "end": 191750 }
class ____(_fixtures.FixtureTest): run_inserts = "once" run_deletes = None def test_o2m_raiseload_mapper(self): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) s...
RaiseLoadTest
python
django__django
django/db/models/fields/__init__.py
{ "start": 92009, "end": 92764 }
class ____(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args...
URLField
python
kamyu104__LeetCode-Solutions
Python/smallest-string-starting-from-leaf.py
{ "start": 226, "end": 829 }
class ____(object): def smallestFromLeaf(self, root): """ :type root: TreeNode :rtype: str """ def dfs(node, candidate, result): if not node: return candidate.append(chr(ord('a') + node.val)) if not node.left and not node.r...
Solution
python
huggingface__transformers
tests/models/olmo3/test_modeling_olmo3.py
{ "start": 1417, "end": 1546 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = Olmo3Model @require_torch
Olmo3ModelTester
python
pytorch__pytorch
test/dynamo/test_regional_inductor.py
{ "start": 2867, "end": 16138 }
class ____(torch._inductor.test_case.TestCase): @parametrize("serialize", [False, True]) def test_simple(self, serialize): def fn(x, y): sin = torch.sin(x) with fx_traceback.annotate({"compile_with_inductor": 0}): mul = sin * y add = mul + 1 ...
RegionalInductorTests
python
kubernetes-client__python
kubernetes/client/models/v1beta1_resource_slice_list.py
{ "start": 383, "end": 7109 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1beta1ResourceSliceList
python
kamyu104__LeetCode-Solutions
Python/maximum-array-hopping-score-i.py
{ "start": 369, "end": 674 }
class ____(object): def maxScore(self, nums): """ :type nums: List[int] :rtype: int """ dp = [0]*len(nums) for i in xrange(1, len(nums)): for j in xrange(i): dp[i] = max(dp[i], dp[j]+(i-j)*nums[i]) return dp[-1]
Solution2
python
tensorflow__tensorflow
tensorflow/lite/python/lite_flex_test.py
{ "start": 8804, "end": 12151 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def _createGraphWithCustomOp(self, opname='CustomAdd'): custom_opdefs_str = ( 'name: \'' + opname + '\' input_arg: {name: \'Input1\' type: DT_FLOAT} ' 'input_arg: {name: \'Input2\' type: DT_FLOAT} output_arg: {name: ' '\'Ou...
WithCustomOpTest
python
wandb__wandb
wandb/sdk/launch/builder/noop.py
{ "start": 439, "end": 1900 }
class ____(AbstractBuilder): """NoOp builder.""" type = "noop" def __init__( self, builder_config: Dict[str, Any], environment: AbstractEnvironment, registry: AbstractRegistry, ) -> None: """Initialize a NoOpBuilder.""" self.environment = environment ...
NoOpBuilder
python
apache__airflow
providers/apache/spark/tests/unit/apache/spark/operators/test_spark_jdbc.py
{ "start": 1038, "end": 7718 }
class ____: _config = { "spark_app_name": "{{ task_instance.task_id }}", "spark_conf": {"parquet.compression": "SNAPPY"}, "spark_files": "hive-site.xml", "spark_py_files": "sample_library.py", "spark_jars": "parquet.jar", "num_executors": 4, "executor_cores": ...
TestSparkJDBCOperator
python
getsentry__sentry
src/sentry/statistical_detectors/detector.py
{ "start": 1659, "end": 1861 }
class ____: type: TrendType score: float payload: DetectorPayload state: DetectorState | None = None regression_group: RegressionGroup | None = None @dataclass(frozen=True)
TrendBundle
python
jina-ai__jina
jina/serve/stream/helper.py
{ "start": 535, "end": 3486 }
class ____: """Iterator to allow async iteration of blocking/non-blocking iterator from the Client""" def __init__( self, iterator: Union[Iterator, AsyncIterator], request_counter: Optional[_RequestsCounter] = None, prefetch: int = 0, iterate_sync_in_thread: bool = True,...
AsyncRequestsIterator
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 17464, "end": 18078 }
class ____(nn.Module): def __init__(self, input_dim, output_dim, hidden_act="gelu"): super().__init__() self.input_dim = input_dim self.output_dim = output_dim self.dense = nn.Linear(self.input_dim, self.output_dim) self.act_fn = ACT2FN[hidden_act] self.LayerNorm = ...
SplinterFullyConnectedLayer
python
keras-team__keras
keras/src/constraints/constraints.py
{ "start": 2359, "end": 3865 }
class ____(Constraint): """MaxNorm weight constraint. Constrains the weights incident to each hidden unit to have a norm less than or equal to a desired value. Also available via the shortcut function `keras.constraints.max_norm`. Args: max_value: the maximum norm value for the incoming w...
MaxNorm
python
numba__numba
numba/tests/test_alignment.py
{ "start": 147, "end": 1086 }
class ____(TestCase): def test_record_alignment(self): rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True) rec = from_dtype(rec_dtype) @njit((rec[:],)) def foo(a): for i in range(a.size): a[i].a = a[i].b a_recarray = np.recarray...
TestAlignment
python
mamba-org__mamba
micromamba/tests/test_config.py
{ "start": 24064, "end": 30736 }
class ____: @staticmethod def _roundtrip(rc_file_path, rc_contents): rc_file_path.write_text(rc_contents) return config("list", "--json", "--no-env", "--rc-file", rc_file_path) @classmethod def _roundtrip_attr(cls, rc_file_path, attr, config_expr): return cls._roundtrip(rc_file_...
TestConfigExpandVars
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 258426, "end": 258920 }
class ____(sgqlc.types.Input): """Ways in which lists of package files can be ordered upon return.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(PackageFileOrderField, graphql_name="field") """The field in which to order package files by.""" d...
PackageFileOrder
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/ranges.py
{ "start": 30578, "end": 30709 }
class ____(AbstractSingleRange[Decimal]): """Represent the PostgreSQL NUMRANGE type.""" __visit_name__ = "NUMRANGE"
NUMRANGE
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_layout08.py
{ "start": 315, "end": 1674 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_layout08.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with user defined layout.""" workbook...
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_mfa_removed_email.py
{ "start": 401, "end": 1254 }
class ____(View): def get(self, request: HttpRequest) -> HttpResponse: if isinstance(request.user, AnonymousUser): return HttpResponse(status=401) authenticator = Authenticator(id=0, type=3, user_id=request.user.id) # u2f email = generate_security_email( account=re...
DebugMfaRemovedEmailView
python
apache__airflow
providers/apache/spark/tests/unit/apache/spark/hooks/test_spark_submit.py
{ "start": 1127, "end": 44580 }
class ____: _spark_job_file = "test_application.py" _config = { "conf": {"parquet.compression": "SNAPPY"}, "conn_id": "default_spark", "files": "hive-site.xml", "py_files": "sample_library.py", "archives": "sample_archive.zip#SAMPLE", "jars": "parquet.jar", ...
TestSparkSubmitHook
python
apache__airflow
devel-common/src/tests_common/test_utils/mock_operators.py
{ "start": 1925, "end": 2216 }
class ____(BaseOperator): """ Empty test operator with extra link. Example of an Operator that has an extra operator link and will be overridden by the one defined in tests/plugins/test_plugin.py. """ operator_extra_links = (AirflowLink(),)
EmptyExtraLinkTestOperator
python
PrefectHQ__prefect
tests/server/orchestration/api/test_variables.py
{ "start": 16917, "end": 20660 }
class ____: async def test_update_variable( self, client: AsyncClient, variable, ): update = VariableUpdate( name="updated_variable", value="updated-value", tags=["updated-tag"] ) res = await client.patch( f"/variables/name/{variable.name}"...
TestUpdateVariableByName
python
psf__black
tests/data/cases/type_params.py
{ "start": 85, "end": 773 }
class ____[ T ] : pass def all_in[T : int,U : (bytes, str),* Ts,**P](): pass def really_long[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine](): pass def even_longer[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine: WhatIfItHadABound](): pass def it_gets_worse[What...
C
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 6154, "end": 10271 }
class ____(Generic[ReceiveMsgType, SendMsgType]): """Handle communication between the task in this process and the supervisor parent process.""" log: Logger = attrs.field(repr=False, factory=structlog.get_logger) socket: socket = attrs.field(factory=lambda: socket(fileno=0)) resp_decoder: msgspec.msgp...
CommsDecoder
python
donnemartin__system-design-primer
solutions/object_oriented_design/call_center/call_center.py
{ "start": 168, "end": 1006 }
class ____(metaclass=ABCMeta): def __init__(self, employee_id, name, rank, call_center): self.employee_id = employee_id self.name = name self.rank = rank self.call = None self.call_center = call_center def take_call(self, call): """Assume the employee will alway...
Employee
python
pypa__setuptools
setuptools/_vendor/typing_extensions.py
{ "start": 53727, "end": 53919 }
class ____: """Mixin for TypeVarLike defaults.""" __slots__ = () __init__ = _set_default # Classes using this metaclass must provide a _backported_typevarlike ClassVar
_DefaultMixin
python
sphinx-doc__sphinx
sphinx/cmd/make_mode.py
{ "start": 2279, "end": 8482 }
class ____: def __init__( self, *, source_dir: str | os.PathLike[str], build_dir: str | os.PathLike[str], opts: Sequence[str], ) -> None: self.source_dir = _StrPath(source_dir) self.build_dir = _StrPath(build_dir) self.opts = [*opts] def build...
Make
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_dialect.py
{ "start": 2935, "end": 12631 }
class ____(fixtures.TestBase): """python-side dialect tests.""" @testing.combinations( ( "FOREIGN KEY (tid) REFERENCES some_table(id)", _fk_expected("tid", "some_table", "id"), ), ( 'FOREIGN KEY (tid) REFERENCES "(2)"(id)', _fk_expected("t...
DialectTest
python
sphinx-doc__sphinx
sphinx/domains/std/__init__.py
{ "start": 3817, "end": 6687 }
class ____(ObjectDescription[str]): index_template: str = _('%s; configuration value') option_spec: ClassVar[OptionSpec] = { 'no-index': directives.flag, 'no-index-entry': directives.flag, 'no-contents-entry': directives.flag, 'no-typesetting': directives.flag, 'type': di...
ConfigurationValue
python
pikepdf__pikepdf
src/pikepdf/models/image.py
{ "start": 1509, "end": 3079 }
class ____(Exception): """This image is not valid according to the PDF 1.7 specification.""" def _array_str(value: Object | str | list): """Simplify pikepdf objects to array of str. Keep streams, dictionaries intact.""" def _convert(item): if isinstance(item, list | Array): return [_c...
InvalidPdfImageError
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_environment_schema.py
{ "start": 3331, "end": 7395 }
class ____(NonLaunchableGraphQLContextTestMatrix): def test_successful_run_config_schema(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "required_resource_job") result = execute_dagster_graphql( graphql_context, RUN_CONFIG_SCHE...
TestEnvironmentSchema
python
huggingface__transformers
tests/quantization/bnb/test_4bit.py
{ "start": 17309, "end": 19571 }
class ____(Base4bitTest): def setUp(self): super().setUp() # model_name self.model_name = "bigscience/bloom-560m" self.seq_to_seq_name = "google-t5/t5-small" # Different types of model self.base_model = AutoModel.from_pretrained( self.model_name, quantiz...
Classes4BitModelTest
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 22052, "end": 23031 }
class ____(Layer): """A layer that randomly sets a fraction p of the output units of the previous layer to zero. Parameters: ----------- p: float The probability that unit x is set to zero. """ def __init__(self, p=0.2): self.p = p self._mask = None self.inpu...
Dropout
python
huggingface__transformers
src/transformers/models/sam2/modular_sam2.py
{ "start": 15866, "end": 17002 }
class ____(nn.Module): r""" Turns pixel values into patch embeddings for transformer consumption. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`Sam...
Sam2PatchEmbeddings
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/decl_base.py
{ "start": 12588, "end": 29540 }
class ____(_ORMClassConfigurator): """Abstract base for a configurator that configures a class for a declarative mapping, or an unmapped ORM dataclass. Defines scanning of pep-484 annotations as well as ORM dataclass applicators """ __slots__ = () clsdict_view: _ClassDict collected_a...
_ClassScanAbstractConfig
python
Textualize__textual
src/textual/css/model.py
{ "start": 6363, "end": 8750 }
class ____: selector_set: list[SelectorSet] = field(default_factory=list) styles: Styles = field(default_factory=Styles) errors: list[tuple[Token, str | HelpText]] = field(default_factory=list) is_default_rules: bool = False tie_breaker: int = 0 selector_names: set[str] = field(default_factory=...
RuleSet
python
pallets__flask
src/flask/json/tag.py
{ "start": 5308, "end": 5599 }
class ____(JSONTag): __slots__ = () key = " u" def check(self, value: t.Any) -> bool: return isinstance(value, UUID) def to_json(self, value: t.Any) -> t.Any: return value.hex def to_python(self, value: t.Any) -> t.Any: return UUID(value)
TagUUID
python
celery__celery
t/unit/utils/test_functional.py
{ "start": 10884, "end": 12175 }
class ____: def test_starkwargs(self): assert fun_takes_argument('foo', lambda **kw: 1) def test_named(self): assert fun_takes_argument('foo', lambda a, foo, bar: 1) def fun(a, b, c, d): return 1 assert fun_takes_argument('foo', fun, position=4) def test_star...
test_fun_takes_argument
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chartsheet07.py
{ "start": 315, "end": 1869 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chartsheet07.xlsx") self.ignore_files = [ "xl/printerSettings/printerSettings1.bin", "xl/chartsheets/_rels/sheet1.xml.r...
TestCompareXLSXFiles
python
pytorch__pytorch
test/test_testing.py
{ "start": 93156, "end": 99204 }
class ____(TestCase): @classmethod def _check_python_output(cls, program) -> str: return subprocess.check_output( [sys.executable, "-W", "always", "-c", program], stderr=subprocess.STDOUT, # On Windows, opening the subprocess with the default CWD makes `import torch` ...
TestImports
python
jpadilla__pyjwt
jwt/exceptions.py
{ "start": 2099, "end": 2261 }
class ____(InvalidTokenError): """Raised when a token's ``sub`` claim is not a string or doesn't match the expected ``subject``""" pass
InvalidSubjectError
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 43790, "end": 44593 }
class ____(BiffRecord): """ This record contains a list of all strings used anywhere in the workbook. Each string occurs only once. The workbook uses indexes into the list to reference the strings. Record SST, BIFF8: Offset Size Contents 0 4 Total number of strings ...
SSTRecord
python
django__django
tests/custom_methods/tests.py
{ "start": 91, "end": 1200 }
class ____(TestCase): def test_custom_methods(self): a = Article.objects.create( headline="Parrot programs in Python", pub_date=date(2005, 7, 27) ) b = Article.objects.create( headline="Beatles reunite", pub_date=date(2005, 7, 27) ) self.assertFalse(a...
MethodsTests
python
ipython__ipython
IPython/core/profileapp.py
{ "start": 4172, "end": 4535 }
class ____(BaseIPythonApplication): description = """print the path to an IPython profile dir""" def parse_command_line(self, argv=None): super(ProfileLocate, self).parse_command_line(argv) if self.extra_args: self.profile = self.extra_args[0] def start(self): p...
ProfileLocate
python
Pylons__pyramid
src/pyramid/security.py
{ "start": 6694, "end": 7046 }
class ____(PermitsResult): """ An instance of ``Allowed`` is returned when a security-related API or other :app:`Pyramid` code allows an action unrelated to an ACL check. It evaluates equal to all boolean true types. It has an attribute named ``msg`` describing the circumstances for the allow....
Allowed
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 465170, "end": 481101 }
class ____(VegaLiteSchema): """ HeaderConfig schema wrapper. Parameters ---------- format : str, dict, :class:`Dict`, :class:`Format`, :class:`TimeFormatSpecifier` The text format specifier for formatting number and date/time in labels of guides (axes, legends, headers) and text mar...
HeaderConfig
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 236953, "end": 243093 }
class ____(test_util.TensorFlowTestCase): """Tests for MS-SSIM.""" _filenames = ["checkerboard1.png", "checkerboard2.png", "checkerboard3.png",] _msssim = np.asarray([[1.000000, 0.091016, 0.091025], [0.091016, 1.000000, 0.999567], [...
MultiscaleSSIMTest
python
pandas-dev__pandas
pandas/tests/frame/test_query_eval.py
{ "start": 822, "end": 2645 }
class ____: @pytest.fixture def df(self): return DataFrame({"A": [1, 2, 3]}) @pytest.fixture def expected1(self, df): return df[df.A > 0] @pytest.fixture def expected2(self, df): return df.A + 1 def test_query_default(self, df, expected1, expected2): # GH 1...
TestCompat
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/request.py
{ "start": 461, "end": 3169 }
class ____(Serializer): def __init__(self, sentry_app: SentryApp) -> None: self.sentry_app = sentry_app def get_attrs( self, item_list: Sequence[Any], user: Any, **kwargs: Any ) -> MutableMapping[Any, Any]: project_ids = {item.data.get("project_id") for item in item_list} pr...
RequestSerializer
python
huggingface__transformers
tests/models/efficientnet/test_modeling_efficientnet.py
{ "start": 1368, "end": 4307 }
class ____: def __init__( self, parent, batch_size=13, image_size=32, num_channels=3, kernel_sizes=[3, 3, 5], in_channels=[32, 16, 24], out_channels=[16, 24, 20], strides=[1, 1, 2], num_block_repeats=[1, 1, 2], expand_ratios=[1,...
EfficientNetModelTester
python
doocs__leetcode
solution/2100-2199/2185.Counting Words With a Given Prefix/Solution2.py
{ "start": 0, "end": 572 }
class ____: def __init__(self): self.children = [None] * 26 self.cnt = 0 def insert(self, w): node = self for c in w: i = ord(c) - ord('a') if node.children[i] is None: node.children[i] = Trie() node = node.children[i] ...
Trie
python
xlwings__xlwings
tests/test_range.py
{ "start": 27450, "end": 29072 }
class ____(TestBase): # 2d Range def test_slice1(self): r = self.wb1.sheets[0].range("B2:D4") self.assertEqual(r[0:, 1:].address, "$C$2:$D$4") def test_slice2(self): r = self.wb1.sheets[0].range("B2:D4") self.assertEqual(r[1:2, 1:2].address, "$C$3") def test_slice3(self...
TestRangeSlicing
python
tox-dev__tox
src/tox/config/loader/replacer.py
{ "start": 911, "end": 1228 }
class ____(ValueError): """Could not stabilize on replacement value.""" @staticmethod def check(depth: int, value: Any) -> None: if depth > MAX_REPLACE_DEPTH: msg = f"Could not expand {value} after recursing {depth} frames" raise MatchRecursionError(msg)
MatchRecursionError
python
google__pytype
pytype/tests/test_overriding.py
{ "start": 27883, "end": 30382 }
class ____(test_base.BaseTest): """Tests for @typing.override.""" def test_valid_override(self): self.Check(""" from typing_extensions import override class A: def f(self): pass class B(A): @override def f(self): pass """) def test_invalid_ov...
TypingOverrideTest
python
gevent__gevent
src/gevent/_ffi/watcher.py
{ "start": 1878, "end": 2757 }
class ____(int): def __repr__(self): return "<NoWatcher>" _NoWatcherResult = _NoWatcherResult(0) def events_to_str(event_field, all_events): result = [] for (flag, string) in all_events: c_flag = flag if event_field & c_flag: result.append(string) event_fie...
_NoWatcherResult
python
dagster-io__dagster
python_modules/dagster/dagster/_core/utils.py
{ "start": 5401, "end": 8166 }
class ____(FuturesAwareThreadPoolExecutor): """A ThreadPoolExecutor that copies over contextvars at submit time.""" def submit(self, fn, *args, **kwargs): ctx = copy_context() return super().submit(ctx.run, fn, *args, **kwargs) def is_valid_email(email: str) -> bool: regex = r"\b[A-Za-z0-...
InheritContextThreadPoolExecutor
python
django__django
tests/model_options/models/default_related_name.py
{ "start": 559, "end": 783 }
class ____(models.Model): name = models.CharField(max_length=128) address = models.CharField(max_length=128) class Meta: abstract = True default_related_name = "%(app_label)s_%(model_name)ss"
Store
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 6686, "end": 6871 }
class ____: def __aiter__(self) -> AsyncIterable[str]: ... # Y045 "__aiter__" methods should return an AsyncIterator, not an AsyncIterable
AsyncIteratorReturningAsyncIterable
python
pydata__xarray
xarray/tests/test_treenode.py
{ "start": 11522, "end": 14316 }
class ____: def test_parents(self) -> None: _, leaf_f = create_test_tree() expected = ["e", "b", "a"] assert [node.name for node in leaf_f.parents] == expected def test_lineage(self) -> None: _, leaf_f = create_test_tree() expected = ["f", "e", "b", "a"] with pyt...
TestAncestry
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-moorcheh/llama_index/vector_stores/moorcheh/utils.py
{ "start": 815, "end": 2402 }
class ____(BaseSparseEmbedding): """Default Moorcheh sparse embedding.""" tokenizer: Callable = Field( default_factory=get_default_tokenizer, description="A callable that returns token input ids.", ) def build_sparse_embeddings( self, input_batch: List[List[int]] ) -> List[...
DefaultMoorchehSparseEmbedding
python
pypa__warehouse
tests/common/db/oidc.py
{ "start": 3005, "end": 3371 }
class ____(WarehouseFactory): class Meta: model = ActiveStatePublisher id = factory.Faker("uuid4", cast_to=None) organization = factory.Faker("pystr", max_chars=12) activestate_project_name = factory.Faker("pystr", max_chars=12) actor = factory.Faker("pystr", max_chars=12) actor_id = fa...
ActiveStatePublisherFactory
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/newly_true_operator.py
{ "start": 688, "end": 3463 }
class ____(BuiltinAutomationCondition[T_EntityKey]): operand: AutomationCondition[T_EntityKey] @property def name(self) -> str: return "NEWLY_TRUE" @property def children(self) -> Sequence[AutomationCondition[T_EntityKey]]: return [self.operand] def _get_previous_child_true_su...
NewlyTrueCondition
python
pypa__setuptools
setuptools/_scripts.py
{ "start": 3157, "end": 6624 }
class ____: """ Encapsulates behavior around writing entry point scripts for console and gui apps. """ template = textwrap.dedent( r""" # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r import re import sys # for compatibility with easy_install; see #...
ScriptWriter
python
matplotlib__matplotlib
lib/matplotlib/axis.py
{ "start": 15037, "end": 17119 }
class ____(Tick): """ Contains all the Artists needed to make a Y tick - the tick line, the label text and the grid line """ __name__ = 'ytick' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # x in axes coords, y in data coords ax = self.axes ...
YTick
python
Textualize__textual
src/textual/_widget_navigation.py
{ "start": 464, "end": 5640 }
class ____(Protocol): """Non-widgets that have an enabled/disabled status.""" disabled: bool Direction: TypeAlias = Literal[-1, 1] """Valid values to determine navigation direction. In a vertical setting, 1 points down and -1 points up. In a horizontal setting, 1 points right and -1 points left. """ def g...
Disableable
python
google__jax
tests/scipy_optimize_test.py
{ "start": 1484, "end": 4184 }
class ____(jtu.JaxTestCase): @jtu.sample_product( maxiter=[None], func_and_init=[(rosenbrock, np.zeros(2, dtype='float32')), (himmelblau, np.ones(2, dtype='float32')), (matyas, np.ones(2) * 6.), (eggholder, np.ones(2) * 100.)], ) def test_minimize(...
TestBFGS
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table39.py
{ "start": 306, "end": 1214 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table39.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(s...
TestCompareXLSXFiles
python
numpy__numpy
numpy/lib/_index_tricks_impl.py
{ "start": 6989, "end": 8755 }
class ____(nd_grid): """ An instance which returns a dense multi-dimensional "meshgrid". An instance which returns a dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexi...
MGridClass
python
fluentpython__example-code-2e
13-protocol-abc/frenchdeck2.py
{ "start": 86, "end": 778 }
class ____(abc.MutableSequence): ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] def __len__(self): ...
FrenchDeck2
python
numpy__numpy
numpy/_core/tests/test_dtype.py
{ "start": 40071, "end": 47623 }
class ____: def test_complex_dtype_str(self): dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), ('rtile', '>f4', (64, 36))], (3,)), ('bottom', [('bleft', ('>f4', (8, 64)), (1,)), ('bright', '>f4', (8, 36))])]...
TestString
python
scrapy__scrapy
tests/test_downloadermiddleware_retry.py
{ "start": 8511, "end": 21511 }
class ____: def get_spider(self, settings=None): crawler = get_crawler(Spider, settings or {}) return crawler._create_spider("foo") def test_basic_usage(self): request = Request("https://example.com") spider = self.get_spider() with LogCapture() as log: new_r...
TestGetRetryRequest
python
kamyu104__LeetCode-Solutions
Python/sum-of-square-numbers.py
{ "start": 56, "end": 347 }
class ____(object): def judgeSquareSum(self, c): """ :type c: int :rtype: bool """ for a in xrange(int(math.sqrt(c))+1): b = int(math.sqrt(c-a**2)) if a**2 + b**2 == c: return True return False
Solution
python
langchain-ai__langchain
libs/core/langchain_core/tools/base.py
{ "start": 52107, "end": 52537 }
class ____(BaseModel, ABC): """Base class for toolkits containing related tools. A toolkit is a collection of related tools that can be used together to accomplish a specific task or work with a particular system. """ @abstractmethod def get_tools(self) -> list[BaseTool]: """Get all to...
BaseToolkit
python
PyCQA__pylint
pylint/extensions/no_self_use.py
{ "start": 627, "end": 3694 }
class ____(BaseChecker): name = "no_self_use" msgs = { "R6301": ( "Method could be a function", "no-self-use", "Used when a method doesn't use its bound instance, and so could " "be written as a function.", {"old_names": [("R0201", "old-no-self...
NoSelfUseChecker
python
catalyst-team__catalyst
tests/pipelines/test_multihead_classification.py
{ "start": 956, "end": 10390 }
class ____(nn.Module): def __init__(self, in_features: int, out_features1: int, out_features2: int): super().__init__() self.shared = nn.Linear(in_features, 128) self.head1 = nn.Linear(128, out_features1) self.head2 = nn.Linear(128, out_features2) def forward(self, x): x...
CustomModule
python
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 5327, "end": 5630 }
class ____: results: BatchResult = field(default_factory=BatchResult) failed_objects: List[ErrorObject] = field(default_factory=list) failed_references: List[ErrorReference] = field(default_factory=list) imported_shards: Set[Shard] = field(default_factory=set) @dataclass
_BatchDataWrapper
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 4348, "end": 4528 }
class ____(ShowFieldTypeAndContent, Model2A): objects = PolymorphicManager() my_objects = MyManager() field4 = models.CharField(max_length=30)
ModelWithMyManagerNoDefault
python
apache__thrift
lib/py/src/protocol/TCompactProtocol.py
{ "start": 2209, "end": 3006 }
class ____(object): STOP = 0x00 TRUE = 0x01 FALSE = 0x02 BYTE = 0x03 I16 = 0x04 I32 = 0x05 I64 = 0x06 DOUBLE = 0x07 BINARY = 0x08 LIST = 0x09 SET = 0x0A MAP = 0x0B STRUCT = 0x0C CTYPES = { TType.STOP: CompactType.STOP, TType.BOOL: CompactType.TRUE, # used f...
CompactType
python
getsentry__sentry
src/sentry/api/endpoints/organization_access_request_details.py
{ "start": 1446, "end": 1569 }
class ____(serializers.Serializer): isApproved = serializers.BooleanField() @region_silo_endpoint
AccessRequestSerializer
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 8683, "end": 8856 }
class ____(_ConfigUpdateModel): factor: Optional[int] asyncEnabled: Optional[bool] deletionStrategy: Optional[ReplicationDeletionStrategy]
_ReplicationConfigUpdate
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_project_forms.py
{ "start": 1440, "end": 5997 }
class ____(TestCase): def test_import_repo_url(self): """Validate different type of repository URLs on importing a Project.""" common_urls = [ # Invalid ("./path/to/relative/folder", False), ("../../path/to/relative/folder", False), ("../../path/to/@/...
TestProjectForms
python
aio-libs__aiohttp
aiohttp/tracing.py
{ "start": 9043, "end": 9193 }
class ____: """Parameters sent by the `on_dns_resolvehost_start` signal""" host: str @frozen_dataclass_decorator
TraceDnsResolveHostStartParams
python
realpython__materials
python-magic-methods/rectangle.py
{ "start": 0, "end": 621 }
class ____: def __init__(self, height, width): self.height = height self.width = width def area(self): return self.height * self.width def __eq__(self, other): return self.area() == other.area() def __lt__(self, other): return self.area() < other.area() de...
Rectangle
python
openai__openai-python
src/openai/types/chat/chat_completion_stream_options_param.py
{ "start": 213, "end": 1311 }
class ____(TypedDict, total=False): include_obfuscation: bool """When true, stream obfuscation will be enabled. Stream obfuscation adds random characters to an `obfuscation` field on streaming delta events to normalize payload sizes as a mitigation to certain side-channel attacks. These obfuscation...
ChatCompletionStreamOptionsParam
python
Netflix__metaflow
metaflow/plugins/cards/card_creator.py
{ "start": 172, "end": 1097 }
class ____: """ This class is responsible for managing the card creation processes. """ async_card_processes = { # "carduuid": { # "proc": subprocess.Popen, # "started": time.time() # } } @classmethod def _register_card_process(cls, carduuid, proc):...
CardProcessManager
python
ray-project__ray
java/serve/src/main/resources/test_python_deployment.py
{ "start": 170, "end": 427 }
class ____(object): def __init__(self, value): self.value = int(value) def increase(self, delta): self.value += int(delta) return str(self.value) def reconfigure(self, value_str): self.value = int(value_str)
Counter
python
huggingface__transformers
src/transformers/models/albert/modeling_albert.py
{ "start": 9924, "end": 10561 }
class ____(nn.Module): def __init__(self, config: AlbertConfig): super().__init__() self.albert_layers = nn.ModuleList([AlbertLayer(config) for _ in range(config.inner_group_num)]) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTenso...
AlbertLayerGroup
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_glue.py
{ "start": 4529, "end": 4751 }
class ____: @pytest.fixture(autouse=True) def mock_conn(self, monkeypatch): self.client = boto3.client("glue") monkeypatch.setattr(GlueJobHook, "conn", self.client)
TestGlueJobCompleteCustomWaiterBase
python
google__jax
tests/source_mapper_test.py
{ "start": 1516, "end": 4508 }
class ____(jtu.JaxTestCase): def setUp(self): if sys.platform == "win32": self.skipTest("Only works on non-Windows platforms") def test_jaxpr_pass(self): def jax_fn(x, y): return x + y test_x = jnp.array([1, 2, 3]) test_y = jnp.array([4, 5, 6]) source_maps = source_mapper.generate_...
SourceMapperTest
python
prabhupant__python-ds
data_structures/graphs/iterative_dfs.py
{ "start": 127, "end": 1050 }
class ____: def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def dfs(self): visited = [False] * self.vertices stack = [] for s in range(self.vertices): if ...
Graph
python
kamyu104__LeetCode-Solutions
Python/range-sum-query-2d-mutable.py
{ "start": 109, "end": 2390 }
class ____(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ if not matrix: return self.__matrix = matrix self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ for _ in...
NumMatrix
python
django__django
tests/lookup/test_lookups.py
{ "start": 243, "end": 1779 }
class ____(SimpleTestCase): def test_equality(self): lookup = Lookup(Value(1), Value(2)) self.assertEqual(lookup, lookup) self.assertEqual(lookup, Lookup(lookup.lhs, lookup.rhs)) self.assertEqual(lookup, mock.ANY) self.assertNotEqual(lookup, Lookup(lookup.lhs, Value(3))) ...
LookupTests
python
cython__cython
Cython/Compiler/TreeFragment.py
{ "start": 432, "end": 3360 }
class ____(Main.Context): def __init__(self, name, include_directories=None, compiler_directives=None, cpp=False): if include_directories is None: include_directories = [] if compiler_directives is None: compiler_directives = {} Main.Context.__init__(self, include_dir...
StringParseContext
python
python-markdown__markdown
markdown/util.py
{ "start": 7073, "end": 8928 }
class ____: """ This class is used for stashing HTML objects that we extract in the beginning and replace with place-holders. """ def __init__(self): """ Create an `HtmlStash`. """ self.html_counter = 0 # for counting inline html segments self.rawHtmlBlocks: list[str | etre...
HtmlStash
python
PyCQA__pylint
tests/functional/g/generic_class_syntax.py
{ "start": 508, "end": 616 }
class ____(Entity[int]): def __init__(self, data: int) -> None: Entity.__init__(self, data)
Switch
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 12711, "end": 14098 }
class ____(Request): """ Adds a task entry to the queue. :param queue: Queue id :type queue: str :param task: Task id :type task: str """ _service = "queues" _action = "add_task" _version = "2.9" _schema = { "definitions": {}, "properties": { "qu...
AddTaskRequest
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 468441, "end": 468980 }
class ____(UnopNode): # unary '~' operator def analyse_c_operation(self, env): if self.operand.type.is_int: self.type = PyrexTypes.widest_numeric_type( self.operand.type, PyrexTypes.c_int_type) elif self.operand.type.is_enum: self.type = PyrexTypes.c_int...
TildeNode
python
sqlalchemy__sqlalchemy
test/aaa_profiling/test_orm.py
{ "start": 9679, "end": 11553 }
class ____(NoCache, fixtures.MappedTest): __requires__ = ("python_profiling_backend",) __backend__ = True @classmethod def define_tables(cls, metadata): Table( "a", metadata, Column("id", Integer, primary_key=True), Column("x", String(5)), ...
DeferOptionsTest
python
getsentry__sentry
tests/sentry/integrations/github_enterprise/test_webhooks.py
{ "start": 21503, "end": 26977 }
class ____(APITestCase): def setUp(self) -> None: self.url = "/extensions/github-enterprise/webhook/" self.metadata = { "url": "35.232.149.196", "id": "2", "name": "test-app", "webhook_secret": "b3002c3e321d4b7880360d397db2ccfd", "private_k...
PullRequestEventWebhook