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
lazyprogrammer__machine_learning_examples
nlp_class2/rntn_tensorflow.py
{ "start": 1079, "end": 7953 }
class ____: def __init__(self, V, D, K, activation): self.D = D self.f = activation # word embedding We = init_weight(V, D) # quadratic terms W11 = np.random.randn(D, D, D) / np.sqrt(3*D) W22 = np.random.randn(D, D, D) / np.sqrt(3*D) W12 = np.random....
RNTN
python
tiangolo__fastapi
scripts/notify_translations.py
{ "start": 1638, "end": 1705 }
class ____(BaseModel): id: str url: str body: str
Comment
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 29434, "end": 29589 }
class ____(ProjectRedirectsMixin, DeleteViewWithMessage): http_method_names = ["post"] success_message = _("Redirect deleted")
ProjectRedirectsDelete
python
pytorch__pytorch
test/inductor/test_coordinate_descent_tuner.py
{ "start": 1449, "end": 4084 }
class ____(TestCase): def test_abs_function(self): """ The benchmark result is simply abs(XBLOCK - 15) """ tuner = CoordescTuner() baseline_config = triton.Config({"XBLOCK": 1}, num_warps=8, num_stages=1) def func(config): return abs(config.kwargs["XBLOCK...
TestCoordinateDescentTuner
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 35092, "end": 35858 }
class ____(nn.Module): """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) Used in lightweight SR to save parameters. Args: scale (int): Scale factor. Supported scales: 2^n and 3. in_channels (int): Channel numbe...
UpsampleOneStep
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 55615, "end": 62570 }
class ____(Hlist): """ A character as close to the given width as possible. When using a font with multiple width versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init...
AutoWidthChar
python
plotly__plotly.py
plotly/graph_objs/layout/ternary/_caxis.py
{ "start": 235, "end": 53738 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.ternary" _path_str = "layout.ternary.caxis" _valid_props = { "color", "dtick", "exponentformat", "gridcolor", "griddash", "gridwidth", "hoverformat", "labelalias", "layer"...
Caxis
python
pytorch__pytorch
test/distributed/pipelining/test_pipe.py
{ "start": 2025, "end": 3442 }
class ____(TestCase): @parametrize("ModelClass", [ExampleCode, MultiMLP, ModelWithParamAlias]) def test_model_split(self, ModelClass): mod = ModelClass() x = torch.randn(microbatch_size, d_hid) y = torch.randn(microbatch_size, d_hid) pipe = pipeline( mod, ...
PipeTests
python
ansible__ansible
lib/ansible/playbook/included_file.py
{ "start": 1378, "end": 12027 }
class ____: def __init__(self, filename, args, vars, task, is_role: bool = False) -> None: self._filename = filename self._args = args self._vars = vars self._task = task self._hosts: list[Host] = [] self._is_role = is_role self._results: list[_RawTaskResult]...
IncludedFile
python
openai__openai-python
src/openai/types/vector_store_search_params.py
{ "start": 445, "end": 1044 }
class ____(TypedDict, total=False): query: Required[Union[str, SequenceNotStr[str]]] """A query string for a search""" filters: Filters """A filter to apply based on file attributes.""" max_num_results: int """The maximum number of results to return. This number should be between 1 and 50...
VectorStoreSearchParams
python
numpy__numpy
numpy/polynomial/tests/test_chebyshev.py
{ "start": 17937, "end": 20629 }
class ____: def test_chebfromroots(self): res = cheb.chebfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5): roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2]) tgt = [0] * i + [1] res = cheb.chebfromroots(roots) * 2**(i - 1) ...
TestMisc
python
django-extensions__django-extensions
django_extensions/collision_resolvers.py
{ "start": 6262, "end": 6575 }
class ____(AppNameSuffixCR, InstalledAppsOrderCR): """ Collision resolver which is mixin of AppNameSuffixCR and InstalledAppsOrderCR. In case of collisions he sets aliases like AppNameSuffixCR, but sets default model using InstalledAppsOrderCR. """ # noqa: E501 pass
AppNameSuffixCustomOrderCR
python
numba__numba
numba/tests/test_optional.py
{ "start": 1140, "end": 6502 }
class ____(TestCase): _numba_parallel_test_ = False def test_return_double_or_none(self): pyfunc = return_double_or_none cfunc = njit((types.boolean,))(pyfunc) for v in [True, False]: self.assertPreciseEqual(pyfunc(v), cfunc(v)) def test_return_different_statement(sel...
TestOptional
python
huggingface__transformers
src/transformers/models/phi/modular_phi.py
{ "start": 12680, "end": 12914 }
class ____(LlamaForTokenClassification): pass __all__ = [ "PhiPreTrainedModel", # noqa: F822 "PhiModel", "PhiForCausalLM", "PhiForSequenceClassification", "PhiForTokenClassification", ]
PhiForTokenClassification
python
eventlet__eventlet
eventlet/greenthread.py
{ "start": 6605, "end": 13370 }
class ____(greenlet.greenlet): """The GreenThread class is a type of Greenlet which has the additional property of being able to retrieve the return value of the main function. Do not construct GreenThread objects directly; call :func:`spawn` to get one. """ def __init__(self, parent): gree...
GreenThread
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 120590, "end": 123694 }
class ____(TypedDict, total=False): type: Required[Literal['dataclass']] cls: Required[type[Any]] generic_origin: type[Any] schema: Required[CoreSchema] fields: Required[list[str]] cls_name: str post_init: bool # default: False revalidate_instances: Literal['always', 'never', 'subclass-...
DataclassSchema
python
huggingface__transformers
src/transformers/models/roberta/modeling_roberta.py
{ "start": 42745, "end": 47423 }
class ____(RobertaPreTrainedModel): def __init__(self, config): super().__init__(config) self.roberta = RobertaModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, 1) # Initialize weights and apply final process...
RobertaForMultipleChoice
python
PyCQA__pylint
tests/functional/n/no/no_member_dataclasses.py
{ "start": 497, "end": 731 }
class ____(metaclass=ABCMeta): type: str @abstractmethod def to_dict(self) -> Dict: """ Serializes given DeploymentState instance to Dict. :return: """ @dataclass(frozen=True)
DeploymentState
python
pytorch__pytorch
torch/utils/_sympy/symbol.py
{ "start": 569, "end": 3737 }
class ____(Enum): SIZE = auto() FLOAT = auto() UNBACKED_INT = auto() UNBACKED_FLOAT = auto() # Inductor: The intermediates in inner_fn tmp0, one generated per ops call. # If one of these shows up in an indexing expression, that means an # indirect load is happening. TMP = auto() # In...
SymT
python
bokeh__bokeh
src/bokeh/document/json.py
{ "start": 2156, "end": 2307 }
class ____(TypedDict): kind: Literal["ColumnDataChanged"] model: Ref attr: str data: DataDict cols: list[str] | None
ColumnDataChanged
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/rds.py
{ "start": 17495, "end": 19721 }
class ____(RdsBaseOperator): """ Cancels an export task in progress that is exporting a snapshot to Amazon S3. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:RdsCancelExportTaskOperator` :param export_task_identifier: The i...
RdsCancelExportTaskOperator
python
has2k1__plotnine
plotnine/themes/elements/element_rect.py
{ "start": 229, "end": 1767 }
class ____(element_base): """ Theme element: Rectangle Used for backgrounds and borders Parameters ---------- fill : str | tuple Rectangle background color color : str | tuple Line color colour : str | tuple Alias of color size : float Line thickness...
element_rect
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/N802.py
{ "start": 716, "end": 852 }
class ____(NodeTransformer): def visit_Constant(self, node): pass from http.server import BaseHTTPRequestHandler
Transformer
python
yandexdataschool__Practical_RL
week04_approx_rl/test_td_loss/compute_td_loss.py
{ "start": 481, "end": 6202 }
class ____(nn.Module): """ An nn.Module, which outputs a value which does not depend on its input. Designed to be used for testing the compute_td_loss function. """ def __init__(self, output_q_values: torch.Tensor): super().__init__() assert output_q_values.dtype == torch.float, out...
MockAgent
python
pypa__pip
src/pip/_internal/index/collector.py
{ "start": 8639, "end": 12546 }
class ____(HTMLParser): """ HTMLParser that keeps the first base HREF and a list of all anchor elements' attributes. """ def __init__(self, url: str) -> None: super().__init__(convert_charrefs=True) self.url: str = url self.base_url: str | None = None self.anchors: ...
HTMLLinkParser
python
apache__airflow
providers/openlineage/tests/unit/openlineage/utils/test_utils.py
{ "start": 2996, "end": 3050 }
class ____(BashOperator): pass
CustomOperatorForTest
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_init.py
{ "start": 36644, "end": 42796 }
class ____(FSDPTestMultiThread): @property def world_size(self) -> int: return 4 @skip_if_lt_x_gpu(1) def test_1d_process_group_init(self): assert self.world_size == 4, f"{self.world_size}" # For convenience, use device mesh's infra to construct the DP PG # (in practice,...
TestFullyShardProcessGroupInit
python
catalyst-team__catalyst
tests/pipelines/test_mnist_multicriterion.py
{ "start": 728, "end": 8951 }
class ____(dl.Runner): def predict_batch(self, batch): # model inference step return self.model(batch[0].to(self.device)) def on_loader_start(self, runner): super().on_loader_start(runner) self.meters = { key: metrics.AdditiveMetric(compute_on_call=False) ...
CustomRunner
python
realpython__materials
python-operator-module/attrgetter_sorting.py
{ "start": 63, "end": 699 }
class ____: id: int fname: str lname: str group: str musician_lists = [ [1, "Brian", "Wilson", "Beach Boys"], [2, "Carl", "Wilson", "Beach Boys"], [3, "Dennis", "Wilson", "Beach Boys"], [4, "Bruce", "Johnston", "Beach Boys"], [5, "Hank", "Marvin", "Shadows"], [6, "Bruce", "Welc...
Musician
python
scipy__scipy
benchmarks/benchmarks/integrate.py
{ "start": 790, "end": 2235 }
class ____(Benchmark): TOL = 1e-5 def fun_flow(self, x, y, p): A = p[0] return np.vstack(( y[1], y[2], 100 * (y[1] ** 2 - y[0] * y[2] - A), y[4], -100 * y[0] * y[4] - 1, y[6], -70 * y[0] * y[6] )) def bc_flow(self, ya, yb, p): return np.array([ ...
SolveBVP
python
astropy__astropy
astropy/modeling/tests/test_parameters.py
{ "start": 4730, "end": 5480 }
class ____(M2): m3d = Parameter(default=20.0) def test_parameter_inheritance(): mod = M3() assert mod.m1a == 1.0 assert mod.m1b == 5.0 assert mod.m2c == 11.0 assert mod.m3d == 20.0 for key in ["m1a", "m1b", "m2c", "m3d"]: assert key in mod.__dict__ assert mod.param_names == ("m...
M3
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/component_tree_tests/test_component_tree_reloading.py
{ "start": 239, "end": 658 }
class ____(dg.Component): """Forthright and by the book.""" def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: # this should only ever be called once sentinel_path = context.component_path.file_path / "sentinel.txt" assert not sentinel_path.exists() sentin...
SingletonComponent
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-kibela/llama_index/readers/kibela/base.py
{ "start": 373, "end": 494 }
class ____(BaseModel): startCursor: Optional[str] endCursor: Optional[str] hasNextPage: Optional[bool]
PageInfo
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 10942, "end": 11556 }
class ____(DelegatingLexer): """ Subclass of the `VelocityLexer` that highlights unlexed data with the `XmlLexer`. """ name = 'XML+Velocity' aliases = ['xml+velocity'] alias_filenames = ['*.xml', '*.vm'] mimetypes = ['application/xml+velocity'] def __init__(self, **options): ...
VelocityXmlLexer
python
falconry__falcon
tests/test_headers.py
{ "start": 3364, "end": 3679 }
class ____: URL1 = '/\u00e7runchy/bacon' URL2 = 'ab\u00e7' def on_get(self, req, resp): resp.location = self.URL1 resp.content_location = self.URL2 def on_head(self, req, resp): resp.location = self.URL2 resp.content_location = self.URL1
LocationHeaderUnicodeResource
python
huggingface__transformers
tests/models/ctrl/test_modeling_ctrl.py
{ "start": 1180, "end": 6335 }
class ____: def __init__( self, parent, batch_size=14, seq_length=7, is_training=True, use_token_type_ids=True, use_input_mask=True, use_labels=True, use_mc_token_ids=True, vocab_size=99, hidden_size=32, num_hidden_layer...
CTRLModelTester
python
vyperlang__vyper
vyper/cli/compile_archive.py
{ "start": 453, "end": 2836 }
class ____(Exception): pass def compile_from_zip(file_name, output_formats, settings, no_bytecode_metadata): compiler_data = compiler_data_from_zip(file_name, settings, no_bytecode_metadata) return outputs_from_compiler_data(compiler_data, output_formats) def compiler_data_from_zip(file_name, settings, ...
NotZipInput
python
django__django
django/db/models/functions/text.py
{ "start": 4834, "end": 5769 }
class ____(Func): function = "LEFT" arity = 2 output_field = CharField() def __init__(self, expression, length, **extra): """ expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string """ ...
Left
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 15619, "end": 21440 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, config: Optional[MllamaTextConfig] = None, layer_idx: Optional[int] = None, ): super().__init__() self.config = config self.num_heads = self.config....
MllamaTextCrossAttention
python
ray-project__ray
python/ray/tests/test_concurrency_group.py
{ "start": 5957, "end": 6325 }
class ____: def __init__(self): self._thread_local_data = threading.local() def set_thread_local(self, value: Any) -> int: self._thread_local_data.value = value return threading.current_thread().ident def get_thread_local(self) -> Tuple[Any, int]: return self._thread_local_...
Actor
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/resolvelib/providers.py
{ "start": 5049, "end": 5871 }
class ____(object): """The thing that performs the actual resolution work.""" base_exception = Exception def __init__(self, provider, reporter): self.provider = provider self.reporter = reporter def resolve(self, requirements, **kwargs): """Take a collection of constraints, sp...
AbstractResolver
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_reflection.py
{ "start": 113226, "end": 117740 }
class ____(fixtures.TablesTest): run_inserts = run_deletes = None __sparse_driver_backend__ = True __requires__ = ("identity_columns", "table_reflection") @classmethod def define_tables(cls, metadata): Table( "t1", metadata, Column("normal", Integer), ...
IdentityReflectionTest
python
huggingface__transformers
src/transformers/models/luke/configuration_luke.py
{ "start": 766, "end": 6628 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`LukeModel`]. It is used to instantiate a LUKE model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configurati...
LukeConfig
python
jamielennox__requests-mock
requests_mock/exceptions.py
{ "start": 548, "end": 619 }
class ____(Exception): """Base Exception for library"""
MockException
python
apache__airflow
helm-tests/tests/helm_tests/other/test_statsd.py
{ "start": 926, "end": 14198 }
class ____: """Tests statsd.""" def test_should_create_statsd_default(self): docs = render_chart(show_only=["templates/statsd/statsd-deployment.yaml"]) assert jmespath.search("metadata.name", docs[0]) == "release-name-statsd" assert jmespath.search("spec.template.spec.containers[0].na...
TestStatsd
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 16649, "end": 21614 }
class ____: def test_array(self): d = np.ones(6) r = np.array([d, d]) assert_equal(r, np.ones((2, 6))) d = np.ones(6) tgt = np.ones((2, 6)) r = np.array([d, d]) assert_equal(r, tgt) tgt[1] = 2 r = np.array([d, d + 1]) assert_equal(r, t...
TestArrayConstruction
python
kamyu104__LeetCode-Solutions
Python/find-the-substring-with-maximum-cost.py
{ "start": 77, "end": 626 }
class ____(object): def maximumCostSubstring(self, s, chars, vals): """ :type s: str :type chars: str :type vals: List[int] :rtype: int """ def kadane(s): result = curr = 0 for c in s: curr = max(curr+(lookup[c] if c in ...
Solution
python
huggingface__transformers
tests/models/idefics3/test_image_processing_idefics3.py
{ "start": 1243, "end": 6473 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, num_images=1, image_size=18, min_resolution=30, max_resolution=40, do_resize=True, size=None, max_image_size=None, do_rescale=True, rescale_fa...
Idefics3ImageProcessingTester
python
fastapi__sqlmodel
docs_src/tutorial/many_to_many/tutorial003_py310.py
{ "start": 681, "end": 3756 }
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) team_links: list[HeroTeamLink] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sqlite_ur...
Hero
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/activity.py
{ "start": 1056, "end": 8309 }
class ____(object): """Encloses local symbol definition and usage information. This can track for instance whether a symbol is modified in the current scope. Note that scopes do not necessarily align with Python's scopes. For example, the body of an if statement may be considered a separate scope. Caution -...
Scope
python
PyCQA__isort
tests/unit/test_exceptions.py
{ "start": 46, "end": 359 }
class ____: def setup_class(self): self.instance = exceptions.ISortError() def test_init(self): assert isinstance(self.instance, exceptions.ISortError) def test_pickleable(self): assert isinstance(pickle.loads(pickle.dumps(self.instance)), exceptions.ISortError)
TestISortError
python
pytorch__pytorch
test/inductor/test_efficient_conv_bn_eval.py
{ "start": 1289, "end": 2656 }
class ____(nn.Module): expected_optimization_count = 3 def __init__( self, conv_class, bn_class, use_bias, in_channels, out_channels, device, **kwargs, ): super().__init__() self.conv1 = conv_class(in_channels, out_channels, bi...
MultiUserConvOp
python
apache__thrift
lib/py/src/Thrift.py
{ "start": 1984, "end": 2208 }
class ____(Exception): """Base class for all thrift exceptions.""" def __init__(self, message=None): Exception.__init__(self, message) super(TException, self).__setattr__("message", message)
TException
python
tensorflow__tensorflow
tensorflow/python/saved_model/nested_structure_coder_test.py
{ "start": 21915, "end": 22218 }
class ____(type_spec.TypeSpec): value_type = property(lambda self: None) _component_specs = property(lambda self: ()) _to_components = lambda self, v: () _from_components = classmethod(lambda cls, c: cls()) _serialize = lambda self: () if __name__ == "__main__": test.main()
RegisteredTypeSpec
python
coleifer__peewee
tests/postgres.py
{ "start": 26830, "end": 26927 }
class ____(TestModel): id = IdentityField(generate_always=True) data = CharField()
IDAlways
python
ray-project__ray
python/ray/data/_internal/execution/operators/hash_aggregate.py
{ "start": 691, "end": 3769 }
class ____(StatefulShuffleAggregation): """Aggregation performing reduction of the shuffled sequence using provided list of aggregating functions. NOTE: That reductions are performed incrementally in a streaming fashion upon accumulation of pre-configured buffer of rows to run aggregation on.""" ...
ReducingShuffleAggregation
python
apache__airflow
providers/qdrant/tests/integration/qdrant/operators/test_qdrant_ingest.py
{ "start": 1173, "end": 2474 }
class ____: def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} self.dag = DAG("test_qdrant_dag_id", default_args=args) self.mock_context = MagicMock() self.channel = "test" def test_execute_hello(self): collection_name = "test-operator-coll...
TestQdrantIngestOperator
python
gevent__gevent
src/greentest/3.9/test_ssl.py
{ "start": 96877, "end": 110311 }
class ____(threading.Thread): class ConnectionHandler(threading.Thread): """A mildly complicated class, because we want it to work both with and without the SSL wrapper around the socket connection, so that we can test the STARTTLS functionality.""" def __init__(self, server, conn...
ThreadedEchoServer
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 27690, "end": 27848 }
class ____(_TargetArgsExpr): """ Matches a call_function node in the FX graphs: `fns[i](*args, **kwargs)` """ op = "call_function"
CallFunction
python
getsentry__sentry
tests/sentry/api/test_base.py
{ "start": 3827, "end": 14017 }
class ____(APITestCase): def test_basic_cors(self) -> None: org = self.create_organization() with assume_test_silo_mode(SiloMode.CONTROL): apikey = ApiKey.objects.create(organization_id=org.id, allowed_origins="*") request = self.make_request(method="GET") request.META["...
EndpointTest
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 9552, "end": 10056 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): num_categorical = float( metafeatures["NumberOfCategoricalFeatures"](X, y, logger, feat_type).value ) num_numerical = float( metafeatures["NumberOfNumericFeatures"](X, y, logger, feat_type).value ...
RatioNumericalToNominal
python
openai__openai-python
src/openai/types/beta/realtime/session.py
{ "start": 2052, "end": 2651 }
class ____(BaseModel): group_id: Optional[str] = None """ The group id to attach to this trace to enable filtering and grouping in the traces dashboard. """ metadata: Optional[object] = None """ The arbitrary metadata to attach to this trace to enable filtering in the traces dashboa...
TracingTracingConfiguration
python
numba__numba
numba/cuda/stubs.py
{ "start": 7168, "end": 7483 }
class ____(Stub): """ ffs(x) Returns the position of the first (least significant) bit set to 1 in x, where the least significant bit position is 1. ffs(0) returns 0. """ #------------------------------------------------------------------------------- # comparison and selection instructions
ffs
python
python-openxml__python-docx
src/docx/opc/oxml.py
{ "start": 2745, "end": 3652 }
class ____(BaseOxmlElement): """`<Default>` element that appears in `[Content_Types].xml` part. Used to specify a default content type to be applied to any part with the specified extension. """ @property def content_type(self): """String held in the ``ContentType`` attribute of this ``<De...
CT_Default
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_object/query/sync.py
{ "start": 310, "end": 453 }
class ____( Generic[Properties, References], _NearObjectQueryExecutor[ConnectionSync, Properties, References], ): pass
_NearObjectQuery
python
tensorflow__tensorflow
tensorflow/python/saved_model/save_context_test.py
{ "start": 889, "end": 3191 }
class ____(test.TestCase): def test_multi_thread(self): self.assertFalse(save_context.in_save_context()) with self.assertRaisesRegex(ValueError, 'Not in a SaveContext'): save_context.get_save_options() options = save_options.SaveOptions(save_debug_info=True) with save_context.save_context(opti...
SaveContextTest
python
pytorch__pytorch
torch/_dynamo/device_interface.py
{ "start": 17758, "end": 17818 }
class ____: multi_processor_count: int
CpuDeviceProperties
python
paramiko__paramiko
paramiko/channel.py
{ "start": 2041, "end": 47659 }
class ____(ClosingContextManager): """ A secure tunnel across an SSH `.Transport`. A Channel is meant to behave like a socket, and has an API that should be indistinguishable from the Python socket API. Because SSH2 has a windowing kind of flow control, if you stop reading data from a Channel ...
Channel
python
facebook__pyre-check
tools/upgrade/commands/command.py
{ "start": 756, "end": 1553 }
class ____: comment: Optional[str] max_line_length: Optional[int] truncate: bool unsafe: bool force_format_unsuppressed: bool lint: bool no_commit: bool should_clean: bool @staticmethod def from_arguments(arguments: argparse.Namespace) -> "CommandArguments": return Comma...
CommandArguments
python
encode__django-rest-framework
rest_framework/versioning.py
{ "start": 1931, "end": 3321 }
class ____(BaseVersioning): """ To the client this is the same style as `NamespaceVersioning`. The difference is in the backend - this implementation uses Django's URL keyword arguments to determine the version. An example URL conf for two views that accept two different versions. urlpatterns ...
URLPathVersioning
python
scrapy__scrapy
scrapy/extensions/debug.py
{ "start": 1983, "end": 2367 }
class ____: def __init__(self) -> None: # win32 platforms don't support SIGUSR signals with contextlib.suppress(AttributeError): signal.signal(signal.SIGUSR2, self._enter_debugger) # type: ignore[attr-defined] def _enter_debugger(self, signum: int, frame: FrameType | None) -> None:...
Debugger
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertsql.py
{ "start": 13652, "end": 13850 }
class ____(EachOf): def __init__(self, condition, rules, else_rules): if condition: super().__init__(*rules) else: super().__init__(*else_rules)
Conditional
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_D.py
{ "start": 9752, "end": 11237 }
class ____(Benchmark): r""" DeflectedCorrugatedSpring objective function. This class defines the Deflected Corrugated Spring [1]_ function global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{DeflectedCorrugatedSpring}}(x) = 0.1\...
DeflectedCorrugatedSpring
python
getsentry__sentry
src/sentry/db/models/base.py
{ "start": 17047, "end": 20284 }
class ____(SiloLimit): def __init__( self, *modes: SiloMode, read_only: SiloMode | Iterable[SiloMode] = (), ) -> None: super().__init__(*modes) self.read_only = frozenset([read_only] if isinstance(read_only, SiloMode) else read_only) @staticmethod def _recover_mo...
ModelSiloLimit
python
Textualize__textual
src/textual/canvas.py
{ "start": 3980, "end": 8420 }
class ____: """A character canvas.""" def __init__(self, width: int, height: int) -> None: """ Args: width: Width of the canvas (in cells). height Height of the canvas (in cells). """ self._width = width self._height = height blank_line =...
Canvas
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/local_to_s3.py
{ "start": 1079, "end": 4213 }
class ____(BaseOperator): """ Uploads a file from a local filesystem to Amazon S3. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:LocalFilesystemToS3Operator` :param filename: Path to the local file. Path can be either abso...
LocalFilesystemToS3Operator
python
fluentpython__example-code
13-op-overloading/vector_v8.py
{ "start": 6646, "end": 10087 }
class ____: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('[')...
Vector
python
tensorflow__tensorflow
tensorflow/python/profiler/profile_context.py
{ "start": 4136, "end": 13577 }
class ____(object): """A Context that captures RunMetadata and performs profiling. ```python # Trace steps 100~200, profile at [150, 200] and dump profile at 200. with profile_context.ProfileContext('/tmp/train_dir', trace_steps=range(100, 200, 3), ...
ProfileContext
python
Textualize__textual
tests/selection_list/test_over_wide_selections.py
{ "start": 183, "end": 821 }
class ____(App[None]): """Test selection list application.""" CSS = """ OptionList { width: 20; } """ def compose(self) -> ComposeResult: yield SelectionList[int](*[(f"{n} ", n) for n in range(10)]) async def test_over_wide_options() -> None: """Options wider than the wid...
SelectionListApp
python
davidhalter__jedi
jedi/plugins/stdlib.py
{ "start": 23779, "end": 24844 }
class ____(ValueWrapper): def __init__(self, instance, args_value_set): super().__init__(instance) self._args_value_set = args_value_set @repack_with_argument_clinic('item, /') def py__call__(self, item_value_set): value_set = NO_VALUES for args_value in self._args_value_set...
ItemGetterCallable
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/rich_jupyter_widget.py
{ "start": 18210, "end": 18478 }
class ____(RichJupyterWidget): """Deprecated class. Use RichJupyterWidget.""" def __init__(self, *a, **kw): warn("RichIPythonWidget is deprecated, use RichJupyterWidget", DeprecationWarning) super().__init__(*a, **kw)
RichIPythonWidget
python
huggingface__transformers
src/transformers/models/unispeech_sat/modular_unispeech_sat.py
{ "start": 3729, "end": 6015 }
class ____(Wav2Vec2GumbelVectorQuantizer): def __init__(self, config): super().__init__(config) self.weight_proj = nn.Linear(config.hidden_size, self.num_groups * self.num_vars) @staticmethod def _compute_perplexity(probs, mask=None): marginal_probs = probs.mean(dim=0) perpl...
UniSpeechSatGumbelVectorQuantizer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/optional1.py
{ "start": 81, "end": 1287 }
class ____: def __init__(self): self.value = 3 def do_stuff(self): pass def __enter__(self): return 3 def __exit__( self, t: Optional[type] = None, exc: Optional[BaseException] = None, tb: Optional[Any] = None, ) -> bool: return True...
Foo
python
openai__openai-python
src/openai/resources/audio/transcriptions.py
{ "start": 49925, "end": 50200 }
class ____: def __init__(self, transcriptions: AsyncTranscriptions) -> None: self._transcriptions = transcriptions self.create = _legacy_response.async_to_raw_response_wrapper( transcriptions.create, )
AsyncTranscriptionsWithRawResponse
python
django-extensions__django-extensions
django_extensions/collision_resolvers.py
{ "start": 8499, "end": 11085 }
class ____: def __init__(self): pass def run_collision_resolver(self, models_to_import): # type: (Dict[str, List[str]]) -> Dict[str, List[Tuple[str, str]]] dictionary_of_names = self._get_dictionary_of_names(models_to_import) # type: Dict[str, str] return self._get_dictionary_o...
CollisionResolvingRunner
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 67767, "end": 69432 }
class ____(BaseModel): type: Literal["SimpleRetriever"] record_selector: RecordSelector = Field( ..., description="Component that describes how to extract records from a HTTP response.", ) requester: Union[CustomRequester, HttpRequester] = Field( ..., description="Request...
SimpleRetriever
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 5832, "end": 6289 }
class ____(LocalizableStreamlitException): """Exception raised when an invalid value is specified for `initial_sidebar_state`.""" def __init__(self, initial_sidebar_state: str) -> None: super().__init__( '`initial_sidebar_state` must be `"auto"` or `"expanded"` or ' '`"collapsed...
StreamlitInvalidSidebarStateError
python
ray-project__ray
python/ray/serve/llm/__init__.py
{ "start": 1653, "end": 1807 }
class ____(_LLMServer): pass @Deprecated( old="ray.serve.llm.LLMRouter", new="ray.serve.llm.ingress.OpenAIIngress", error=False, )
LLMServer
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/widgets/base.py
{ "start": 12997, "end": 15812 }
class ____: """ Clickable button. :param text: The caption for the button. :param handler: `None` or callable. Called when the button is clicked. No parameters are passed to this callable. Use for instance Python's `functools.partial` to pass parameters to this callable if needed. :...
Button
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 6788, "end": 7098 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read", "org:write", "org:admin"], "POST": ["org:read", "org:write", "org:admin"], "PUT": ["org:read", "org:write", "org:admin"], "DELETE": ["org:read", "org:write", "org:admin"], }
OrganizationSearchPermission
python
tiangolo__fastapi
docs_src/websockets/tutorial003_py39.py
{ "start": 1335, "end": 2549 }
class ____: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websock...
ConnectionManager
python
streamlit__streamlit
lib/streamlit/components/v2/manifest_scanner.py
{ "start": 2264, "end": 20976 }
class ____: """Structured configuration for a single component entry. Parameters ---------- name Component name as declared in ``pyproject.toml``. asset_dir Optional relative directory containing component assets. """ name: str asset_dir: str | None = None @staticm...
ComponentConfig
python
neetcode-gh__leetcode
python/0200-number-of-islands.py
{ "start": 1432, "end": 2462 }
class ____: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 rows, cols = len(grid), len(grid[0]) visited = set() islands = 0 def bfs(r, c): q = deque() visited.add((r, c)) q.append((r, c)) ...
SolutionBFS
python
sqlalchemy__sqlalchemy
test/base/test_result.py
{ "start": 636, "end": 9174 }
class ____(fixtures.TestBase): def _fixture(self, values, labels): return result.result_tuple(labels)(values) def test_empty(self): keyed_tuple = self._fixture([], []) eq_(str(keyed_tuple), "()") eq_(len(keyed_tuple), 0) eq_(list(keyed_tuple._mapping.keys()), []) ...
ResultTupleTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 48969, "end": 52963 }
class ____(GoogleCloudBaseOperator): """ Gets an entry. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataCatalogGetEntryOperator` :param location: Required. The location of the entry to get. :param entry_group: R...
CloudDataCatalogGetEntryOperator
python
getsentry__sentry
tests/sentry/seer/assisted_query/test_issues_tools.py
{ "start": 16815, "end": 22395 }
class ____(APITestCase, SnubaTestCase): databases = {"default", "control"} def setUp(self): super().setUp() self.min_ago = before_now(minutes=1) def test_execute_issues_query_basic(self): """Test basic issues query""" # Create some issues self.store_event( ...
TestExecuteIssuesQuery
python
pydata__xarray
xarray/tests/test_dataset.py
{ "start": 6663, "end": 7445 }
class ____(backends.InMemoryDataStore): """ Store that does not allow any data access. """ def __init__(self): super().__init__() self._indexvars = set() def store(self, variables, *args, **kwargs) -> None: super().store(variables, *args, **kwargs) for k, v in varia...
InaccessibleVariableDataStore
python
dask__dask
dask/tests/test_layers.py
{ "start": 329, "end": 6472 }
class ____(SchedulerPlugin): """Plugin to help record which modules are imported on the scheduler""" name = "import-check" def __init__(self, pattern): self.pattern = pattern async def start(self, scheduler): # Record the modules that have been imported when the scheduler starts ...
SchedulerImportCheck
python
dask__dask
dask/dataframe/dask_expr/datasets.py
{ "start": 457, "end": 3572 }
class ____(PartitionsFiltered, BlockwiseIO): _absorb_projections = True _parameters = [ "start", "end", "dtypes", "freq", "partition_freq", "seed", "kwargs", "columns", "_partitions", "_series", ] _defaults = { "sta...
Timeseries
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_import_functionality.py
{ "start": 20940, "end": 22469 }
class ____(AdminTestMixin, TestCase): """Test preview order displayed correctly (issue 1784).""" fixtures = ["author"] def test_import_preview_order(self): author_id = Author.objects.first().id response = self._do_import_post( self.ebook_import_url, "ebooks.csv", ...
ConfirmImportPreviewOrderTest