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
ansible__ansible
lib/ansible/plugins/vars/__init__.py
{ "start": 957, "end": 1331 }
class ____(AnsiblePlugin): """ Loads variables for groups and/or hosts """ is_stateless = False def __init__(self): """ constructor """ super(BaseVarsPlugin, self).__init__() self._display = display def get_vars(self, loader, path, entities): """ Gets variables...
BaseVarsPlugin
python
facebook__pyre-check
client/command_arguments.py
{ "start": 1498, "end": 1636 }
class ____(str, enum.Enum): _value_: str NONE = "none" CLIENT = "client" CLIENT_AND_BINARY = "client_and_binary"
VersionKind
python
Netflix__metaflow
test/core/tests/project_branch.py
{ "start": 72, "end": 904 }
class ____(MetaflowTest): PRIORITY = 1 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] HEADER = """...
ProjectBranchTest
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 97827, "end": 104155 }
class ____: async def test_can_not_nonblocking_pause_subflows( self, session, initialize_orchestration, ): initial_state_type = states.StateType.RUNNING proposed_state_type = states.StateType.PAUSED intended_transition = (initial_state_type, proposed_state_type) ...
TestPausingFlows
python
wandb__wandb
wandb/vendor/pygments/lexers/markup.py
{ "start": 15133, "end": 15561 }
class ____(MozPreprocHashLexer): """ Lexer for Mozilla Preprocessor files (with '%' as the marker). Other data is left untouched. .. versionadded:: 2.0 """ name = 'mozpercentpreproc' aliases = [name] filenames = [] mimetypes = [] tokens = { 'root': [ (r'^%'...
MozPreprocPercentLexer
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/vertex_ai/test_experiment_service.py
{ "start": 5681, "end": 6740 }
class ____: @mock.patch(VERTEX_AI_PATH.format("ExperimentRunHook")) def test_execute(self, mock_hook): op = UpdateExperimentRunStateOperator( task_id=TASK_ID, project_id=GCP_PROJECT, location=GCP_LOCATION, experiment_name=TEST_EXPERIMENT_NAME, ...
TestVertexAIUpdateExperimentRunStateOperator
python
django__django
django/contrib/gis/gdal/error.py
{ "start": 227, "end": 1575 }
class ____(Exception): pass # #### GDAL/OGR error checking codes and routine #### # OGR Error Codes OGRERR_DICT = { 1: (GDALException, "Not enough data."), 2: (GDALException, "Not enough memory."), 3: (GDALException, "Unsupported geometry type."), 4: (GDALException, "Unsupported operation."), ...
SRSException
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_custom_report.py
{ "start": 29079, "end": 35144 }
class ____(BaseTest): start_date = "2024-01-01" stream_name = "custom_report" records_number = 7 report_file = "custom_report_hour_of_day" custom_report_aggregation = "HourOfDay" @property def _config(self) -> dict[str, Any]: return ( ConfigBuilder() .with_r...
CustomReportHourOfDay
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/nn_functional.py
{ "start": 36157, "end": 39031 }
class ____(Operator): """Operator for torch.nn.functional.scaled_dot_product_attention.""" def __init__(self): super().__init__("torch.nn.functional.scaled_dot_product_attention") @property def torch_op_name(self) -> str | None: """Return the torch operation name.""" return "to...
ScaledDotProductAttentionOperator
python
pytorch__pytorch
torch/_export/serde/serialize.py
{ "start": 5498, "end": 14737 }
class ____(dict): """ Dictionary class for deferred instantiation of node metadata values. Purpose is to avoid creation of symbolic-shape tensors before relevant shape guards are parsed. """ def __init__(self): self.map = {} self.evaluated = set() def __setitem__(self, k, v): ...
LazyMap
python
PrefectHQ__prefect
src/prefect/artifacts.py
{ "start": 9341, "end": 10280 }
class ____(Artifact): table: Union[dict[str, list[Any]], list[dict[str, Any]], list[list[Any]]] type: Optional[str] = "table" @classmethod def _sanitize( cls, item: dict[str, Any] | list[Any] | float ) -> dict[str, Any] | list[Any] | int | float | None: """ Sanitize NaN valu...
TableArtifact
python
kubernetes-client__python
kubernetes/client/models/v1_client_ip_config.py
{ "start": 383, "end": 3945 }
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...
V1ClientIPConfig
python
Pylons__pyramid
tests/test_config/test_assets.py
{ "start": 37365, "end": 37899 }
class ____: def __call__(self, package, path, source, _info=''): self.package = package self.path = path self.source = source def read_(src): with open(src, 'rb') as f: contents = f.read() return contents def _assertBody(body, filename): # strip both \n and \r for win...
DummyUnderOverride
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/bind_override.py
{ "start": 494, "end": 985 }
class ____(App): BINDINGS = [ Binding("space", "app.bell", "Bell (App)"), Binding("c", "app.notify('c app')", "app"), Binding("a", "app.notify('a app')", "app"), Binding("b", "app.notify('b app')", "app"), ] def compose(self) -> ComposeResult: yield MyWidget() ...
BindApp
python
coleifer__peewee
tests/regressions.py
{ "start": 51311, "end": 51431 }
class ____(TestModel): id = IntegerField(primary_key=True) cpk = ForeignKeyField(CharPK, field=CharPK.name)
CharFK
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 122372, "end": 125470 }
class ____(TypedDict, total=False): body: str trace_id: str replay_id: str severity_text: str severity_number: int trace_flags: int item_id: int def scalar_to_any_value(value: Any) -> AnyValue: if isinstance(value, str): return AnyValue(string_value=value) if isinstance(val...
_OptionalOurLogData
python
tensorflow__tensorflow
tensorflow/python/data/ops/readers.py
{ "start": 19464, "end": 21807 }
class ____(dataset_ops.DatasetSource): """A `Dataset` of fixed-length records from one or more binary files.""" def __init__(self, filenames, record_bytes, header_bytes=None, footer_bytes=None, buffer_size=None, compression_t...
_FixedLengthRecordDataset
python
tensorflow__tensorflow
tensorflow/python/training/proximal_gradient_descent.py
{ "start": 1101, "end": 4517 }
class ____(optimizer.Optimizer): # pylint: disable=line-too-long """Optimizer that implements the proximal gradient descent algorithm. References: Efficient Learning using Forward-Backward Splitting: [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitti...
ProximalGradientDescentOptimizer
python
networkx__networkx
networkx/algorithms/tests/test_summarization.py
{ "start": 16598, "end": 19030 }
class ____(AbstractSNAP): def build_original_graph(self): nodes = { "A": {"color": "Red"}, "B": {"color": "Red"}, "C": {"color": "Red"}, "D": {"color": "Blue"}, "E": {"color": "Blue"}, "F": {"color": "Blue"}, "G": {"color": ...
TestSNAPUndirectedMulti
python
django__django
tests/template_tests/syntax_tests/test_autoescape.py
{ "start": 186, "end": 6535 }
class ____(SimpleTestCase): @setup({"autoescape-tag01": "{% autoescape off %}hello{% endautoescape %}"}) def test_autoescape_tag01(self): output = self.engine.render_to_string("autoescape-tag01") self.assertEqual(output, "hello") @setup({"autoescape-tag02": "{% autoescape off %}{{ first }}{...
AutoescapeTagTests
python
h5py__h5py
h5py/tests/test_big_endian_file.py
{ "start": 1010, "end": 1469 }
class ____(TestCase): def test_simple_int_be(self): name = make_name() fname = self.mktemp() arr = np.ndarray(shape=(1,), dtype=">i4", buffer=bytearray([0, 1, 3, 2])) be_number = 0 * 256 ** 3 + 1 * 256 ** 2 + 3 * 256 ** 1 + 2 * 256 ** 0 with File(fname, mode="w") as f: ...
TestEndianess
python
tensorflow__tensorflow
tensorflow/python/util/nest_test.py
{ "start": 2755, "end": 2822 }
class ____(MaskedTensor): pass @dataclasses.dataclass
MaskedTensor2
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 61830, "end": 62227 }
class ____(_PrintableStructure): _fields_ = [ ('fieldId', c_uint32), ('scopeId', c_uint32), ('timestamp', c_int64), ('latencyUsec', c_int64), ('valueType', _nvmlValueType_t), ('nvmlReturn', _nvmlReturn_t), ('value', c_nvmlValue_t) ] NVML_NVLINK_TOTAL_SUPP...
c_nvmlFieldValue_t
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_export.py
{ "start": 31002, "end": 33662 }
class ____(AdminTestMixin, TestCase): # Test that Dates, Booleans, numbers etc are retained as native types # when exporting to XLSX, XLS, ODS (see #1939) class DeclaredModelFieldBookResource(resources.ModelResource): # declare a field and enforce export output as str (coerce_to_string) id ...
ExportBinaryFieldsTest
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/regression.py
{ "start": 5694, "end": 6886 }
class ____(Regression): """Performs a non-linear transformation of the data before fitting the model and doing predictions which allows for doing non-linear regression. Parameters: ----------- degree: int The degree of the polynomial that the independent variable X will be transformed to. ...
PolynomialRegression
python
kamyu104__LeetCode-Solutions
Python/get-biggest-three-rhombus-sums-in-a-grid.py
{ "start": 64, "end": 1451 }
class ____(object): def getBiggestThree(self, grid): """ :type grid: List[List[int]] :rtype: List[int] """ K = 3 left = [[grid[i][j] for j in xrange(len(grid[i]))] for i in xrange(len(grid))] right = [[grid[i][j] for j in xrange(len(grid[i]))] for i in xrange...
Solution
python
gevent__gevent
examples/webpy.py
{ "start": 335, "end": 450 }
class ____(object): def GET(self): return '<html>Hello, world!<br><a href="/long">/long</a></html>'
index
python
getsentry__sentry
tests/sentry/plugins/test_repository_provider.py
{ "start": 241, "end": 1961 }
class ____(TestCase): def test_needs_auth_for_user(self) -> None: user = self.create_user() provider = DummyRepositoryProvider(id="dummy") # if no org is provided, user needs auth assert provider.needs_auth(user) is True UserSocialAuth.objects.create(provider="dummy", user=...
RepositoryProviderTest
python
walkccc__LeetCode
solutions/3326. Minimum Division Operations to Make Array Non Decreasing/3326.py
{ "start": 0, "end": 487 }
class ____: def minOperations(self, nums: list[int]) -> int: ans = 0 for i in range(len(nums) - 2, -1, -1): if nums[i] > nums[i + 1]: minDivisor = self._getMinDivisor(nums[i]) if minDivisor > nums[i + 1]: return -1 nums[i] = minDivisor ans += 1 return ans ...
Solution
python
pytorch__pytorch
torch/backends/cuda/__init__.py
{ "start": 1180, "end": 1711 }
class ____: # Like regular ContextProp, but uses the `.device_index` attribute from the # calling object as the first argument to the getter and setter. def __init__(self, getter, setter): self.getter = getter self.setter = setter def __get__(self, obj, objtype): return self.get...
cuFFTPlanCacheAttrContextProp
python
sphinx-doc__sphinx
sphinx/directives/admonitions.py
{ "start": 1298, "end": 1368 }
class ____(SphinxAdmonition): node_class = nodes.attention
Attention
python
pennersr__django-allauth
tests/apps/socialaccount/providers/google/tests.py
{ "start": 8787, "end": 13514 }
class ____(GoogleTests): """ Run the same set of tests but without having a SocialApp entry. """ pass def test_login_by_token(db, client, settings_with_google_provider): client.cookies.load({"g_csrf_token": "csrf"}) with patch( "allauth.socialaccount.internal.jwtkit.jwt.get_unverified...
AppInSettingsTests
python
openai__openai-python
src/openai/types/beta/assistant_update_params.py
{ "start": 6289, "end": 6612 }
class ____(TypedDict, total=False): file_ids: SequenceNotStr[str] """ Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. """
ToolResourcesCodeInterpreter
python
django__django
tests/migrations/migrations_test_apps/lookuperror_c/migrations/0002_c2.py
{ "start": 43, "end": 690 }
class ____(migrations.Migration): dependencies = [ ("lookuperror_a", "0002_a2"), ("lookuperror_c", "0001_initial"), ] operations = [ migrations.CreateModel( name="C2", fields=[ ( "id", models.AutoField( ...
Migration
python
realpython__materials
python-mixins/mixins.py
{ "start": 255, "end": 468 }
class ____: @classmethod def from_json(cls, json_string: str) -> Self: return cls(**json.loads(json_string)) def as_json(self) -> str: return json.dumps(vars(self))
JSONSerializableMixin
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-ai21/llama_index/llms/ai21/base.py
{ "start": 1708, "end": 15490 }
class ____(FunctionCallingLLM): """ AI21 Labs LLM. Examples: `pip install llama-index-llms-ai21` ```python from llama_index.llms.ai21 import AI21 llm = AI21(model="jamba-instruct", api_key=api_key) resp = llm.complete("Paul Graham is ") print(resp) ...
AI21
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-ibm/llama_index/llms/ibm/base.py
{ "start": 1604, "end": 23701 }
class ____(FunctionCallingLLM): """ IBM watsonx.ai large language models. Example: `pip install llama-index-llms-ibm` ```python from llama_index.llms.ibm import WatsonxLLM watsonx_llm = WatsonxLLM( model_id="google/flan-ul2", url="https://us-south.m...
WatsonxLLM
python
pandas-dev__pandas
pandas/tests/frame/test_unary.py
{ "start": 114, "end": 5744 }
class ____: # __pos__, __neg__, __invert__ @pytest.mark.parametrize( "df_data,expected_data", [ ([-1, 1], [1, -1]), ([False, True], [True, False]), (pd.to_timedelta([-1, 1]), pd.to_timedelta([1, -1])), ], ) def test_neg_numeric(self, df_data, ...
TestDataFrameUnaryOperators
python
tensorflow__tensorflow
tensorflow/python/ops/gradient_checker_v2_test.py
{ "start": 9532, "end": 12964 }
class ____(test.TestCase): # Gradient checker for MNIST. def _BuildAndTestMiniMNIST(self, param_index, tag): # Fix seed to avoid occasional flakiness np.random.seed(6) # Hyperparameters batch = 3 inputs = 16 features = 32 classes = 10 # Define the parameters inp_data = np.rand...
MiniMNISTTest
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 4226, "end": 5726 }
class ____(ModelOutput): r""" intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`): Stacked intermediate hidden states (output of each layer of the decoder). intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size,...
TestDetrDecoderOutput
python
OmkarPathak__pygorithm
tests/test_math.py
{ "start": 156, "end": 372 }
class ____(unittest.TestCase): def test_lcm(self): self.assertEqual(lcm.lcm([3, 12, 16]), 48) def test_lcm_using_gcd(self): self.assertEqual(lcm_using_gcd.lcm_using_gcd([3, 12, 16]), 48)
TestLCM
python
apache__thrift
lib/py/src/protocol/TJSONProtocol.py
{ "start": 1951, "end": 2301 }
class ____(object): def __init__(self, protocol): self.protocol = protocol self.first = True def doIO(self, function): pass def write(self): pass def read(self): pass def escapeNum(self): return False def __str__(self): return self.__...
JSONBaseContext
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 51889, "end": 54211 }
class ____(GradientCheckpointingLayer): def __init__(self, config: SeamlessM4TConfig, encoder_ffn_dim=None, encoder_attention_heads=None): super().__init__() encoder_ffn_dim = config.encoder_ffn_dim if encoder_ffn_dim is None else encoder_ffn_dim encoder_attention_heads = ( confi...
SeamlessM4TEncoderLayer
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 198245, "end": 198363 }
class ____(FileObjectClassTestCase): bufsize = 2 # Exercise the buffering code
SmallBufferedFileObjectClassTestCase
python
pypa__pip
src/pip/_vendor/packaging/markers.py
{ "start": 1058, "end": 1190 }
class ____(ValueError): """ An invalid operation was attempted on a value that doesn't support it. """
UndefinedComparison
python
yandexdataschool__Practical_RL
week07_seq2seq/basic_model_torch.py
{ "start": 313, "end": 7322 }
class ____(nn.Module): def __init__(self, inp_voc, out_voc, emb_size, hid_size,): super(self.__class__, self).__init__() self.inp_voc = inp_voc self.out_voc = out_voc self.emb_inp = nn.Embedding(len(inp_voc), emb_size) self.emb_out = nn.Embedding(len(out_voc...
BasicTranslationModel
python
numba__numba
numba/testing/main.py
{ "start": 22642, "end": 22728 }
class ____(runner.TextTestRunner): resultclass = RefleakTestResult
RefleakTestRunner
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 175478, "end": 181252 }
class ____(_CompressedMixin, sparse_test_class()): @classmethod def spcreator(cls, *args, **kwargs): with warnings.catch_warnings(): warnings.filterwarnings("ignore", WMSG, SparseEfficiencyWarning) return csc_array(*args, **kwargs) math_dtypes = [np.bool_, np.int_, np.float64...
TestCSC
python
numba__numba
numba/tests/test_comprehension.py
{ "start": 7500, "end": 17716 }
class ____(unittest.TestCase): _numba_parallel_test_ = False def check(self, pyfunc, *args, **kwargs): """A generic check function that run both pyfunc, and jitted pyfunc, and compare results.""" run_parallel = kwargs.get('run_parallel', False) assert_allocate_list = kwargs.get...
TestArrayComprehension
python
huggingface__transformers
src/transformers/models/dab_detr/configuration_dab_detr.py
{ "start": 900, "end": 13685 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DabDetrModel`]. It is used to instantiate a DAB-DETR model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar conf...
DabDetrConfig
python
automl__auto-sklearn
test/test_pipeline/components/regression/test_random_forests.py
{ "start": 161, "end": 990 }
class ____(BaseRegressionComponentTest): __test__ = True res = dict() res["default_boston"] = 0.8410063895401654 res["boston_n_calls"] = 9 res["default_boston_iterative"] = res["default_boston"] res["default_boston_sparse"] = 0.4194462097407078 res["default_boston_iterative_sparse"] = res["...
RandomForestComponentTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_write_col_breaks.py
{ "start": 301, "end": 1333 }
class ____(unittest.TestCase): """ Test the Worksheet _write_col_breaks() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_col_breaks_1(self): """Test the _write_col_breaks() metho...
TestWriteColBreaks
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/fifo_queue_test.py
{ "start": 15055, "end": 16396 }
class ____(test.TestCase): def testEnqueueWithShape(self): with test_util.use_gpu(): q = data_flow_ops.GPUCompatibleFIFOQueue( 10, dtypes_lib.float32, shapes=(3, 2)) self.evaluate(q.enqueue(([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],))) with self.assertRaises(ValueError): q.enqueue...
GPUCompatibleFIFOQueueTests
python
getsentry__sentry
tests/snuba/api/endpoints/test_discover_saved_queries.py
{ "start": 493, "end": 1396 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.create_organization(owner=self.user) self.projects = [ self.create_project(organization=self.org), self.create_project(organization=s...
DiscoverSavedQueryBase
python
tensorflow__tensorflow
tensorflow/python/eager/backprop_test.py
{ "start": 66718, "end": 68619 }
class ____(test_util.TensorFlowTestCase): def _assert_indexed_slices_equal(self, left, right): self.assertAllEqual( self.evaluate(ops.convert_to_tensor(left)), self.evaluate(ops.convert_to_tensor(right))) def testNoGradients(self): self.assertIsNone(backprop_util.AggregateIndexedSlicesGrad...
AggregateIndexedSlicesGradientsTest
python
protocolbuffers__protobuf
python/google/protobuf/internal/type_checkers.py
{ "start": 3773, "end": 4023 }
class ____(TypeChecker): def __init__(self, default_value, *acceptable_types): TypeChecker.__init__(self, *acceptable_types) self._default_value = default_value def DefaultValue(self): return self._default_value
TypeCheckerWithDefault
python
qdrant__qdrant-client
qdrant_client/uploader/grpc_uploader.py
{ "start": 2708, "end": 4936 }
class ____(BaseUploader): def __init__( self, host: str, port: int, collection_name: str, max_retries: int, wait: bool = False, shard_key_selector: Optional[types.ShardKeySelector] = None, update_filter: Optional[types.Filter] = None, **kwargs:...
GrpcBatchUploader
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 456174, "end": 460262 }
class ____(Request): """ Mark a task status as published. For Annotation tasks - if any changes were committed by this task, a new version in the dataset together with an output view are created. For Training tasks - if a model was created, it should be set to ready. :param force: If not true...
PublishRequest
python
pytorch__pytorch
test/nn/test_parametrization.py
{ "start": 854, "end": 82206 }
class ____(NNTestCase): _do_cuda_memory_leak_check = True _do_cuda_non_default_stream = True # FIXME: Rewrite this test using functions not depending on LAPACK # and remove the `@skipIfNoLapack` (see #70995) # torch/nn/utils/parametrize @skipIfNoLapack @swap([True, False]) def te...
TestNNParametrization
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol30.py
{ "start": 373, "end": 502 }
class ____(Protocol): v1: int def func2(c2: C2): # This should generate an error because v1 is invariant. x: P2 = c2
C2
python
pandas-dev__pandas
pandas/tests/io/test_feather.py
{ "start": 508, "end": 10407 }
class ____: def check_error_on_write(self, df, exc, err_msg, temp_file): # check that we are raising the exception # on writing with pytest.raises(exc, match=err_msg): to_feather(df, temp_file) def check_external_error_on_write(self, df, temp_file): # check that we ...
TestFeather
python
getsentry__sentry
tests/sentry/workflow_engine/handlers/detector/test_stateful.py
{ "start": 18498, "end": 21226 }
class ____(TestCase): def setUp(self) -> None: self.detector = self.create_detector( name="Redis Optimization Detector", project=self.project, ) self.handler = MockDetectorStateHandler( detector=self.detector, thresholds={ Level...
TestDetectorStateManagerRedisOptimization
python
google__pytype
pytype/rewrite/tests/test_basic.py
{ "start": 189, "end": 2049 }
class ____(RewriteTest): """Basic functional tests.""" def setUp(self): super().setUp() self.options.tweak(use_rewrite=True) def test_analyze_functions(self): self.Check(""" def f(): def g(): pass """) def test_analyze_function_with_nonlocal(self): self.Check(""" ...
BasicTest
python
networkx__networkx
networkx/algorithms/tests/test_graphical.py
{ "start": 1085, "end": 5366 }
class ____: @classmethod def setup_class(cls): global atlas from networkx.generators import atlas cls.GAG = atlas.graph_atlas_g() def test_atlas(self): for graph in self.GAG: deg = (d for n, d in graph.degree()) assert nx.is_graphical(deg, method="eg...
TestAtlas
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/float.py
{ "start": 11975, "end": 13155 }
class ____(BaseFloat[np.dtypes.Float64DType, np.float64]): """ A Zarr data type for arrays containing 64-bit floating point numbers. Wraps the [`np.dtypes.Float64DType`][numpy.dtypes.Float64DType] data type. Scalars for this data type are instances of [`np.float64`][numpy.float64]. Attributes ...
Float64
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 24587, "end": 24710 }
class ____(DagsterError): """When job execution completes with steps in an unknown state."""
DagsterUnknownStepStateError
python
pandas-dev__pandas
pandas/tests/indexes/test_any_index.py
{ "start": 3352, "end": 4842 }
class ____: def test_getitem_0d_ndarray(self, index): # GH#55601 if len(index) == 0: pytest.skip(reason="Test assumes non-empty index") key = np.array(0) result = index[key] assert result == index[0] def test_get_loc_listlike_raises_invalid_index_error(self,...
TestIndexing
python
ipython__ipython
IPython/extensions/deduperreload/deduperreload.py
{ "start": 1838, "end": 2398 }
class ____(NamedTuple): """ Each node represents a function. qualified_name: string which represents the namespace/name of the function abstract_syntax_tree: subtree of the overall module which corresponds to this function qualified_name is of the structure: (namespace1, namespace2, ..., name) ...
DependencyNode
python
huggingface__transformers
src/transformers/models/bros/modeling_bros.py
{ "start": 13926, "end": 16990 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = BrosAttention(config) self.is_decoder = config.is_decoder self.add_cross_attentio...
BrosLayer
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_multicolumn_sum_values_to_be_equal_to_single_column.py
{ "start": 672, "end": 2695 }
class ____(MulticolumnMapMetricProvider): # </snippet> # This is the id string that will be used to reference your metric. # <snippet> condition_metric_name = "multicolumn_values.sum_values_equal_to_single_column" # </snippet> # These point your metric at the provided keys to facilitate calculat...
MulticolumnValuesSumValuesEqualToSingleColumn
python
aio-libs__aiohttp
tests/test_web_middleware.py
{ "start": 6275, "end": 19054 }
class ____: @pytest.mark.parametrize( "path, status", [ ("/resource1", 200), ("/resource1/", 404), ("/resource2", 200), ("/resource2/", 200), ("/resource1?p1=1&p2=2", 200), ("/resource1/?p1=1&p2=2", 404), ("/resource...
TestNormalizePathMiddleware
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_engine.py
{ "start": 21692, "end": 23583 }
class ____(fixtures.TestBase): __only_on__ = "mssql" __backend__ = True @testing.variation("enable_comments", [True, False]) def test_comments_enabled_disabled( self, testing_engine, metadata, enable_comments ): Table( "tbl_with_comments", metadata, ...
MiscTest
python
readthedocs__readthedocs.org
readthedocs/projects/forms.py
{ "start": 32373, "end": 35992 }
class ____(forms.Form): """Project translation form.""" project = forms.ChoiceField() def __init__(self, *args, **kwargs): self.parent = kwargs.pop("parent", None) self.user = kwargs.pop("user") super().__init__(*args, **kwargs) self.fields["project"].choices = self.get_cho...
TranslationBaseForm
python
doocs__leetcode
solution/0400-0499/0471.Encode String with Shortest Length/Solution.py
{ "start": 0, "end": 751 }
class ____: def encode(self, s: str) -> str: def g(i: int, j: int) -> str: t = s[i : j + 1] if len(t) < 5: return t k = (t + t).index(t, 1) if k < len(t): cnt = len(t) // k return f"{cnt}[{f[i][i + k - 1]}]" ...
Solution
python
crytic__slither
slither/vyper_parsing/ast/types.py
{ "start": 181, "end": 251 }
class ____(ASTNode): doc_string: Optional[str] @dataclass
Definition
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 34449, "end": 34543 }
class ____(StringEnum): frame = "frame" source = "source" roi = "roi"
SchemaTypeEnum
python
pandas-dev__pandas
pandas/tests/internals/test_internals.py
{ "start": 30079, "end": 37736 }
class ____: # Nosetests-style data-driven tests. # # This test applies different indexing routines to block managers and # compares the outcome to the result of same operations on np.ndarray. # # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests # and are disable...
TestIndexing
python
nryoung__algorithms
algorithms/data_structures/singly_linked_list.py
{ "start": 843, "end": 2125 }
class ____: def __init__(self): self.head = None self.size = 0 def add(self, value): """ Add element to list Time Complexity: O(N) """ node = Node(value) node.set_next(self.head) self.head = node self.size += 1 def _search_...
SinglyLinkedList
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_annotations/allow_star_arg_any.py
{ "start": 439, "end": 1021 }
class ____: # OK def foo_method(self, a: int, *params: str, **options: str) -> int: pass # ANN401 def foo_method(self, a: Any, *params: str, **options: str) -> int: pass # ANN401 def foo_method(self, a: int, *params: str, **options: str) -> Any: pass # OK def f...
Bar
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py
{ "start": 291, "end": 462 }
class ____: def __hash__(self): print("ruff") # [invalid-hash-return] # TODO: Once Ruff has better type checking def return_int(): return "3"
HashNoReturn
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-convert-string-ii.py
{ "start": 8241, "end": 10751 }
class ____(object): def minimumCost(self, source, target, original, changed, cost): """ :type source: str :type target: str :type original: List[str] :type changed: List[str] :type cost: List[int] :rtype: int """ INF = float("inf") def ...
Solution4
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/higher_order_functions.py
{ "start": 449, "end": 1792 }
class ____: def method_to_sink(self, arg): _test_sink(arg) def self_to_sink(self): _test_sink(self) def higher_order_method(c: C, arg): higher_order_function(c.method_to_sink, arg) # Expect an issue (False negative) def test_higher_order_method(): higher_order_method(C(), _test_sou...
C
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 3813, "end": 4676 }
class ____(SentencePieceExtractor): def extract(self, vocab_scores=None) -> tuple[dict[str, int], list[tuple]]: """ By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to order the merges with respect to the piece scores instead. ...
GemmaSentencePieceExtractor
python
django__django
tests/check_framework/test_security.py
{ "start": 5243, "end": 6953 }
class ____(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. ...
CheckCSRFCookieSecureTest
python
aimacode__aima-python
deep_learning4e.py
{ "start": 1077, "end": 1285 }
class ____: def function(self, x): return NotImplementedError def derivative(self, x): return NotImplementedError def __call__(self, x): return self.function(x)
Activation
python
conda__conda
conda/models/records.py
{ "start": 20958, "end": 21446 }
class ____(PackageRecord): """Representation of a package that has been returned as part of a solver solution. This sits between :class:`PackageRecord` and :class:`PrefixRecord`, simply adding ``requested_spec`` so it can be used in lockfiles without requiring the artifact on disk. """ #: str:...
SolvedRecord
python
apache__airflow
task-sdk/tests/task_sdk/api/test_client.py
{ "start": 42827, "end": 53846 }
class ____: def test_trigger(self): # Simulate a successful response from the server when triggering a dag run def handle_request(request: httpx.Request) -> httpx.Response: if request.url.path == "/dag-runs/test_trigger/test_run_id": actual_body = json.loads(request.read(...
TestDagRunOperations
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict12.py
{ "start": 971, "end": 1034 }
class ____(TypedDict): foo: int baz: NotRequired[int]
TD3
python
sympy__sympy
sympy/polys/agca/extensions.py
{ "start": 5442, "end": 9633 }
class ____(Domain): r""" Finite extension generated by an integral element. The generator is defined by a monic univariate polynomial derived from the argument ``mod``. A shorter alias is ``FiniteExtension``. Examples ======== Quadratic integer ring $\mathbb{Z}[\sqrt2]$: >>> fro...
MonogenicFiniteExtension
python
ansible__ansible
lib/ansible/plugins/loader.py
{ "start": 4676, "end": 12272 }
class ____(object): def __init__(self, plugin_type: str, legacy_package_name: str) -> None: self.original_name: str | None = None self.redirect_list: list[str] = [] self.raw_error_list: list[Exception] = [] """All exception instances encountered during the plugin load.""" sel...
PluginLoadContext
python
sqlalchemy__sqlalchemy
test/typing/plain_files/orm/trad_relationship_uselist.py
{ "start": 1285, "end": 4443 }
class ____(Base): __tablename__ = "address" id = mapped_column(Integer, primary_key=True) user_id = mapped_column(ForeignKey("user.id")) email = mapped_column(String, nullable=False) user_style_one = relationship(User, uselist=False) user_style_one_typed: Mapped[User] = relationship(User, use...
Address
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/decorators/kubernetes_cmd.py
{ "start": 1268, "end": 4677 }
class ____(DecoratedOperator, KubernetesPodOperator): custom_operator_name = "@task.kubernetes_cmd" template_fields: Sequence[str] = KubernetesPodOperator.template_fields overwrite_rtif_after_execution: bool = True def __init__(self, *, python_callable: Callable, args_only: bool = False, **kwargs) -> ...
_KubernetesCmdDecoratedOperator
python
sqlalchemy__sqlalchemy
test/typing/plain_files/inspection_inspect.py
{ "start": 606, "end": 658 }
class ____(DeclarativeBaseNoMeta): pass
BaseNoMeta
python
huggingface__transformers
tests/models/roformer/test_modeling_roformer.py
{ "start": 1509, "end": 14065 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_head...
RoFormerModelTester
python
python-poetry__poetry
src/poetry/console/commands/env_command.py
{ "start": 181, "end": 544 }
class ____(Command): def __init__(self) -> None: # Set in poetry.console.application.Application.configure_env self._env: Env | None = None super().__init__() @property def env(self) -> Env: assert self._env is not None return self._env def set_env(self, env: E...
EnvCommand
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-drive/source_google_drive/spec.py
{ "start": 2042, "end": 2617 }
class ____(BaseModel): class Config(OneOfOptionConfig): title = "Service Account Key Authentication" discriminator = "auth_type" auth_type: Literal["Service"] = Field("Service", const=True) service_account_info: str = Field( title="Service Account Information", description='...
ServiceAccountCredentials
python
pandas-dev__pandas
pandas/tseries/holiday.py
{ "start": 3445, "end": 13437 }
class ____: """ Class that defines a holiday with start/end dates and rules for observance. """ start_date: Timestamp | None end_date: Timestamp | None days_of_week: tuple[int, ...] | None def __init__( self, name: str, year=None, month=None, day...
Holiday
python
openai__openai-python
src/openai/types/responses/response_function_shell_call_output_content_param.py
{ "start": 456, "end": 723 }
class ____(TypedDict, total=False): exit_code: Required[int] """The exit code returned by the shell process.""" type: Required[Literal["exit"]] """The outcome type. Always `exit`.""" Outcome: TypeAlias = Union[OutcomeTimeout, OutcomeExit]
OutcomeExit
python
huggingface__transformers
src/transformers/models/blip_2/configuration_blip_2.py
{ "start": 904, "end": 4660 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Blip2VisionModel`]. It is used to instantiate a BLIP-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar co...
Blip2VisionConfig
python
getsentry__sentry
tests/sentry/hybridcloud/rpc/test_sig.py
{ "start": 132, "end": 1350 }
class ____(TestCase): def test_signature(self) -> None: class AnObject(pydantic.BaseModel): a: int b: str def a_function(arg1: AnObject, arg2: AnObject) -> AnObject: raise NotImplementedError sig = SerializableFunctionSignature(a_function) arg_va...
SerializableFunctionSignatureTest