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
scipy__scipy
scipy/spatial/tests/test_distance.py
{ "start": 79562, "end": 82528 }
class ____: def test_pdist_jaccard_random(self): eps = 1e-8 X = eo['pdist-boolean-inp'] Y_right = eo['pdist-jaccard'] Y_test1 = wpdist(X, 'jaccard') assert_allclose(Y_test1, Y_right, rtol=eps) def test_pdist_jaccard_random_float32(self): eps = 1e-8 X = n...
TestJaccard
python
huggingface__transformers
examples/modular-transformers/modeling_roberta.py
{ "start": 24474, "end": 33715 }
class ____(RobertaPreTrainedModel): _no_split_modules = ["RobertaEmbeddings", "RobertaLayer"] def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config...
RobertaModel
python
sympy__sympy
sympy/functions/combinatorial/factorials.py
{ "start": 16377, "end": 22498 }
class ____(CombinatorialFunction): r""" Rising factorial (also called Pochhammer symbol [1]_) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by: .. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1) where ...
RisingFactorial
python
optuna__optuna
optuna/_transform.py
{ "start": 301, "end": 11926 }
class ____: """Transform a search space and parameter configurations to continuous space. The search space bounds and parameter configurations are represented as ``numpy.ndarray``s and transformed into continuous space. Bounds and parameters associated with categorical distributions are one-hot encoded...
_SearchSpaceTransform
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_tensor_slices_test.py
{ "start": 16021, "end": 17520 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def _build_tensor_slices_dataset(self, components, options=None): dataset = dataset_ops.Dataset.from_tensor_slices(components) if options: dataset = dataset.with_options(options) return...
FromTensorSlicesCheckpointTest
python
PrefectHQ__prefect
src/integrations/prefect-docker/prefect_docker/worker.py
{ "start": 2322, "end": 14625 }
class ____(BaseJobConfiguration): """ Configuration class used by the Docker worker. An instance of this class is passed to the Docker worker's `run` method for each flow run. It contains all the information necessary to execute the flow run as a Docker container. Attributes: name: The...
DockerWorkerJobConfiguration
python
aio-libs__aiohttp
tests/test_test_utils.py
{ "start": 2638, "end": 12649 }
class ____(AioHTTPTestCase): async def get_application(self) -> web.Application: return _create_example_app() async def test_example_with_loop(self) -> None: request = await self.client.request("GET", "/") assert request.status == 200 text = await request.text() assert _...
TestAioHTTPTestCase
python
walkccc__LeetCode
solutions/2254. Design Video Sharing Platform/2254.py
{ "start": 0, "end": 1704 }
class ____: def __init__(self): self.currVideoId = 0 self.usedIds = [] self.videoIdToVideo = {} self.videoIdToViews = collections.Counter() self.videoIdToLikes = collections.Counter() self.videoIdToDislikes = collections.Counter() def upload(self, video: str) -> int: videoId = self._get...
VideoSharingPlatform
python
pypa__pip
src/pip/_vendor/cachecontrol/cache.py
{ "start": 722, "end": 1291 }
class ____(BaseCache): def __init__(self, init_dict: MutableMapping[str, bytes] | None = None) -> None: self.lock = Lock() self.data = init_dict or {} def get(self, key: str) -> bytes | None: return self.data.get(key, None) def set( self, key: str, value: bytes, expires: in...
DictCache
python
python-visualization__folium
folium/map.py
{ "start": 768, "end": 2106 }
class ____(MacroElement): """The root class of the leaflet class hierarchy""" _includes: defaultdict[str, dict] = defaultdict(dict) @classmethod def include(cls, **kwargs): cls._includes[cls].update(**kwargs) @classproperty def includes(cls): return cls._includes[cls] @pr...
Class
python
openai__openai-python
src/openai/types/responses/function_tool_param.py
{ "start": 251, "end": 861 }
class ____(TypedDict, total=False): name: Required[str] """The name of the function to call.""" parameters: Required[Optional[Dict[str, object]]] """A JSON schema object describing the parameters of the function.""" strict: Required[Optional[bool]] """Whether to enforce strict parameter valida...
FunctionToolParam
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 141200, "end": 141597 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(SponsorableOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc....
SponsorableOrder
python
getsentry__sentry
src/sentry/integrations/slack/webhooks/base.py
{ "start": 4726, "end": 8981 }
class ____(MessagingIntegrationCommandDispatcher[Response]): endpoint: SlackDMEndpoint request: SlackDMRequest # Define mapping of messages to halt reasons @property def TEAM_HALT_MAPPINGS(self) -> dict[str, MessageCommandHaltReason]: from sentry.integrations.slack.webhooks.command import (...
SlackCommandDispatcher
python
tensorflow__tensorflow
third_party/xla/xla/tools/buffer_debug_log/checksum_mismatch_report.py
{ "start": 1515, "end": 1764 }
class ____: """Thunk metadata, read from ThunkMetadataListProto. Stored in a separate type to enable type checking. """ thunk_id: ThunkId thunk_kind: str profile_annotation: Optional[str] @dataclasses.dataclass(frozen=True)
ThunkMetadata
python
kamyu104__LeetCode-Solutions
Python/destroying-asteroids.py
{ "start": 33, "end": 386 }
class ____(object): def asteroidsDestroyed(self, mass, asteroids): """ :type mass: int :type asteroids: List[int] :rtype: bool """ asteroids.sort() for x in asteroids: if x > mass: return False mass += min(x, asteroids[-...
Solution
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/rich_jupyter_widget.py
{ "start": 1279, "end": 18210 }
class ____(RichIPythonWidget): """ An JupyterWidget that supports rich text, including lists, images, and tables. Note that raw performance will be reduced compared to the plain text version. """ # RichJupyterWidget protected class variables. _payload_source_plot = 'ipykernel.pylab.back...
RichJupyterWidget
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-document360/llama_index/readers/document360/base.py
{ "start": 428, "end": 12265 }
class ____(BaseReader): def __init__( self, api_key: str, should_process_project_version: Optional[ Callable[[ProjectVersion], bool] ] = None, should_process_category: Optional[ Callable[[Category, list[Category]], bool] ] = None, shoul...
Document360Reader
python
redis__redis-py
redis/maint_notifications.py
{ "start": 13539, "end": 18568 }
class ____: """ Configuration class for maintenance notifications handling behaviour. Notifications are received through push notifications. This class defines how the Redis client should react to different push notifications such as node moving, migrations, etc. in a Redis cluster. """ d...
MaintNotificationsConfig
python
spyder-ide__spyder
spyder/api/plugins/tests.py
{ "start": 654, "end": 3676 }
class ____(QMainWindow): """QMainWindow mock for plugin tests.""" def __init__(self): # This avoids using the cli options passed to pytest sys_argv = [sys.argv[0]] self._cli_options = get_options(sys_argv)[0] super().__init__() PLUGIN_REGISTRY.set_main(self) def reg...
MainWindowMock
python
walkccc__LeetCode
solutions/913. Cat and Mouse/913.py
{ "start": 92, "end": 1987 }
class ____: def catMouseGame(self, graph: list[list[int]]) -> int: n = len(graph) # result of (cat, mouse, move) # move := 0 (mouse) // 1 (cat) states = [[[0] * 2 for _ in range(n)] for _ in range(n)] outDegree = [[[0] * 2 for _ in range(n)] for _ in range(n)] q = collections.deque() # (cat, ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1597593, "end": 1597742 }
class ____(sgqlc.types.Union): """Any referencable object""" __schema__ = github_schema __types__ = (Issue, PullRequest)
ReferencedSubject
python
tiangolo__fastapi
docs_src/query_param_models/tutorial001.py
{ "start": 155, "end": 457 }
class ____(BaseModel): limit: int = Field(100, gt=0, le=100) offset: int = Field(0, ge=0) order_by: Literal["created_at", "updated_at"] = "created_at" tags: List[str] = [] @app.get("/items/") async def read_items(filter_query: FilterParams = Query()): return filter_query
FilterParams
python
pallets__werkzeug
src/werkzeug/middleware/lint.py
{ "start": 1223, "end": 3035 }
class ____: def __init__(self, stream: t.IO[bytes]) -> None: self._stream = stream def read(self, *args: t.Any) -> bytes: if len(args) == 0: warn( "WSGI does not guarantee an EOF marker on the input stream, thus making" " calls to 'wsgi.input.read()' ...
InputStream
python
celery__celery
t/unit/utils/test_collections.py
{ "start": 12898, "end": 13188 }
class ____: def test_observers_not_shared(self): a = ChainMap() b = ChainMap() callback = Mock() a.bind_to(callback) b.update(x=1) callback.assert_not_called() a.update(x=1) callback.assert_called_once_with(x=1)
test_ChainMap
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py
{ "start": 112, "end": 1132 }
class ____(GraphQLError): def __init__(self, source, position, description): location = get_location(source, position) super(GraphQLSyntaxError, self).__init__( message=u'Syntax Error {} ({}:{}) {}\n\n{}'.format( source.name, location.line, ...
GraphQLSyntaxError
python
openai__openai-python
examples/responses/background_streaming.py
{ "start": 192, "end": 1002 }
class ____(BaseModel): steps: List[Step] final_answer: str client = OpenAI() id = None with client.responses.stream( input="solve 8x + 31 = 2", model="gpt-4o-2024-08-06", text_format=MathResponse, background=True, ) as stream: for event in stream: if event.type == "response.created...
MathResponse
python
huggingface__transformers
src/transformers/models/flava/configuration_flava.py
{ "start": 10798, "end": 14809 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`FlavaMultimodalModel`]. It is used to instantiate an FLAVA model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simil...
FlavaMultimodalConfig
python
pytorch__pytorch
torch/distributed/remote_device.py
{ "start": 43, "end": 4706 }
class ____: """ Represents a device on a remote worker. Args: remote_device (str or torch.device): Represents a device on a remote worker. The string format should be one of the following: 1. "<workername>/<device>", where the device field can be parsed as torch.device ...
_remote_device
python
getsentry__sentry
src/sentry/metrics/middleware.py
{ "start": 743, "end": 3529 }
class ____(RuntimeError): pass def _filter_tags(key: str, tags: MutableTags) -> MutableTags: """Removes unwanted tags from the tag mapping and returns a filtered one.""" if key in _METRICS_THAT_CAN_HAVE_BAD_TAGS: return tags discarded = frozenset( key for key in tags i...
BadMetricTags
python
doocs__leetcode
solution/2000-2099/2022.Convert 1D Array Into 2D Array/Solution.py
{ "start": 0, "end": 226 }
class ____: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: if m * n != len(original): return [] return [original[i : i + n] for i in range(0, m * n, n)]
Solution
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-form-a-target-string-given-a-dictionary.py
{ "start": 781, "end": 1436 }
class ____(object): def numWays(self, words, target): """ :type words: List[str] :type target: str :rtype: int """ MOD = 10**9+7 # dp[i+1][j+1]: number of ways of target[0..j] using count[0..i]. dp = [[0]*(len(target)+1) for _ in xrange(2)] for...
Solution2
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/cli/test_ecs_worker.py
{ "start": 16949, "end": 29570 }
class ____: """Test work pool defaults update functionality.""" @pytest.fixture async def test_work_pool(self): """Create a test work pool with ECS base template.""" async with prefect.get_client() as client: work_pool = await client.create_work_pool( WorkPoolCre...
TestWorkPoolDefaults
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 104340, "end": 104577 }
class ____(Response): """ Response of models.move endpoint. """ _service = "models" _action = "move" _version = "2.13" _schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
MoveResponse
python
gevent__gevent
src/greentest/3.9/test_threading.py
{ "start": 51253, "end": 52413 }
class ____(unittest.TestCase): def test_interrupt_main_subthread(self): # Calling start_new_thread with a function that executes interrupt_main # should raise KeyboardInterrupt upon completion. def call_interrupt(): _thread.interrupt_main() t = threading.Thread(target=cal...
InterruptMainTests
python
python-poetry__poetry
src/poetry/console/commands/build.py
{ "start": 1171, "end": 5021 }
class ____: def __init__(self, poetry: Poetry, env: Env, io: IO) -> None: self.poetry = poetry self.env = env self.io = io def _build( self, fmt: DistributionType, executable: Path, target_dir: Path, config_settings: dict[str, Any], ) -> None:...
BuildHandler
python
kubernetes-client__python
kubernetes/client/models/v1_validation_rule.py
{ "start": 383, "end": 22970 }
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...
V1ValidationRule
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/ast_util.py
{ "start": 2319, "end": 4372 }
class ____(gast.NodeTransformer): """Transformer that can rename symbols to a simple names.""" def __init__(self, name_map): self.name_map = name_map def _process_name_node(self, node): qn = anno.getanno(node, anno.Basic.QN) if qn in self.name_map: new_node = gast.Name( str(self.name...
SymbolRenamer
python
doocs__leetcode
solution/0500-0599/0561.Array Partition/Solution.py
{ "start": 0, "end": 118 }
class ____: def arrayPairSum(self, nums: List[int]) -> int: nums.sort() return sum(nums[::2])
Solution
python
astropy__astropy
astropy/coordinates/tests/test_representation.py
{ "start": 26656, "end": 38310 }
class ____: def test_name(self): assert PhysicsSphericalRepresentation.name == "physicsspherical" assert PhysicsSphericalRepresentation.name in REPRESENTATION_CLASSES def test_empty_init(self): with pytest.raises(TypeError) as exc: s = PhysicsSphericalRepresentation() d...
TestPhysicsSphericalRepresentation
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/kubernetes_engine.py
{ "start": 1780, "end": 6962 }
class ____(KubernetesPodTrigger): """ Trigger for checking pod status until it finishes its job. :param pod_name: The name of the pod. :param pod_namespace: The namespace of the pod. :param cluster_url: The URL pointed to the cluster. :param ssl_ca_cert: SSL certificate that is used for authent...
GKEStartPodTrigger
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 8366, "end": 9634 }
class ____: """Test es_MX bank provider""" def test_bank(self, faker, num_samples): for _ in range(num_samples): assert faker.bank() in EsMxBankProvider.banks @pytest.mark.parametrize( "clabe,validity", [ ("002864631170560203", True), ("002864631...
TestEsMx
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_template_detail.py
{ "start": 2689, "end": 5198 }
class ____(ProjectTemplateAPIBase): endpoint = "sentry-api-0-organization-project-template-detail" method = "put" def test_put__no_feature(self) -> None: response = self.get_error_response( self.organization.id, self.project_template.id, status_code=404 ) assert response...
ProjectTemplateUpdateTest
python
pydantic__pydantic
pydantic-core/tests/serializers/test_union.py
{ "start": 29225, "end": 29325 }
class ____: def __init__(self, type_: Literal['cat']) -> None: self.type_ = 'cat'
ModelCat
python
huggingface__transformers
tests/models/lfm2_moe/test_modeling_lfm2_moe.py
{ "start": 1250, "end": 1641 }
class ____(CausalLMModelTester): if is_torch_available(): config_class = Lfm2MoeConfig base_model_class = Lfm2MoeModel causal_lm_class = Lfm2MoeForCausalLM def __init__( self, parent, layer_types=["full_attention", "conv"], ): super().__init__(parent)...
Lfm2MoeModelTester
python
pytorch__pytorch
test/dynamo/test_dicts.py
{ "start": 53637, "end": 54801 }
class ____(torch._dynamo.test_case.TestCase): def setUp(self): self._prev_trace_unittest = torch._dynamo.config.enable_trace_unittest torch._dynamo.config.enable_trace_unittest = True super().setUp() def tearDown(self): torch._dynamo.config.enable_trace_unittest = self._prev_tra...
OrderedDictSubclassOverload
python
pytorch__pytorch
torch/_inductor/codegen/triton.py
{ "start": 10338, "end": 20578 }
class ____: """ This is a base class that describes a block descriptor used in Triton kernels. It can be used to create either a tensor descriptor (with TensorDescriptorOptions) or a block pointer (with BlockPtrOptions). """ params: BlockParameters constant_offset: sympy.Expr order: lis...
BlockDescriptorOptions
python
PyCQA__pydocstyle
src/tests/test_cases/test.py
{ "start": 3963, "end": 11888 }
class ____: """Leading and trailing space missing.""" pass @expect('D205: 1 blank line required between summary line and description ' '(found 0)') @expect('D213: Multi-line docstring summary should start at the second line') def multi_line_zero_separating_blanks(): """Summary. Description. ...
LeadingAndTrailingSpaceMissing
python
modin-project__modin
modin/pandas/indexing.py
{ "start": 7338, "end": 22404 }
class ____(QueryCompilerCaster, ClassLogger): """ Base class for location indexer like loc and iloc. Parameters ---------- modin_df : Union[DataFrame, Series] DataFrame to operate on. """ df: Union[DataFrame, Series] qc: BaseQueryCompiler _extensions: EXTENSION_DICT_TYPE = ...
_LocationIndexerBase
python
django__django
tests/queries/models.py
{ "start": 4451, "end": 4571 }
class ____(models.Model): x = models.ForeignKey(LoopX, models.CASCADE) class Meta: ordering = ["x"]
LoopY
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 964056, "end": 964354 }
class ____(sgqlc.types.Type): """An individual package version""" __schema__ = github_schema __field_names__ = ("identifier",) identifier = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="identifier") """The package name or version"""
SecurityAdvisoryPackageVersion
python
rapidsai__cudf
python/cudf/cudf/pandas/fast_slow_proxy.py
{ "start": 23285, "end": 26268 }
class ____(_FastSlowProxy): """ Proxy type for a pair of "intermediate" types that appear as intermediate values when invoking operations on "final" types. The conversion between fast and slow types is done by keeping track of the sequence of operations that created the wrapped object, and "play...
_IntermediateProxy
python
huggingface__transformers
src/transformers/models/cohere2/modeling_cohere2.py
{ "start": 16879, "end": 20324 }
class ____(Cohere2PreTrainedModel): def __init__(self, config: Cohere2Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.l...
Cohere2Model
python
getsentry__sentry
src/sentry/api/endpoints/project_overview.py
{ "start": 769, "end": 913 }
class ____(ProjectPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin"], }
RelaxedProjectPermission
python
dagster-io__dagster
python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/base_scenario.py
{ "start": 3842, "end": 31145 }
class ____( NamedTuple( "_AssetReconciliationScenario", [ ("unevaluated_runs", Sequence[RunSpec]), ("assets", Optional[Sequence[Union[dg.SourceAsset, dg.AssetsDefinition]]]), ("asset_checks", Optional[Sequence[dg.AssetChecksDefinition]]), ("between_run...
AssetReconciliationScenario
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1388406, "end": 1392125 }
class ____(sgqlc.types.Type, Node): """Represents a Git reference.""" __schema__ = github_schema __field_names__ = ( "associated_pull_requests", "branch_protection_rule", "compare", "name", "prefix", "ref_update_rule", "repository", "target", ...
Ref
python
tensorflow__tensorflow
tensorflow/python/framework/op_def_library_test.py
{ "start": 1544, "end": 55117 }
class ____(test_util.TensorFlowTestCase): def Tensor(self, t, name="in"): return op_def_library.apply_op("OutT", T=t, name=name) def testNoRegisteredOpFails(self): with self.assertRaises(RuntimeError) as cm: op_def_library.apply_op("unknown") self.assertEqual(str(cm.exception), "Unrecognized Op ...
OpDefLibraryTest
python
getsentry__sentry
src/sentry/api/endpoints/organization_spans_fields.py
{ "start": 7189, "end": 8637 }
class ____(ABC): PROJECT_SLUG_KEYS = {"project", "project.name"} PROJECT_ID_KEYS = {"project.id"} def __init__( self, organization: Organization, snuba_params: SnubaParams, key: str, query: str | None, max_span_tag_values: int, ): self.organizatio...
BaseSpanFieldValuesAutocompletionExecutor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-sunshine/components.py
{ "start": 341, "end": 706 }
class ____(DeclarativeAuthenticator): config: Mapping[str, Any] basic_auth: BasicHttpAuthenticator oauth2: BearerAuthenticator def __new__(cls, basic_auth, oauth2, config, *args, **kwargs): if config["credentials"]["auth_method"] == "api_token": return basic_auth else: ...
AuthenticatorZendeskSunshine
python
jina-ai__jina
jina/helper.py
{ "start": 21036, "end": 29656 }
class ____: """Helper function for argparse.Namespace object.""" @staticmethod def kwargs2list(kwargs: Dict) -> List[str]: """ Convert dict to an argparse-friendly list. :param kwargs: dictionary of key-values to be converted :return: argument list """ args ...
ArgNamespace
python
mkdocs__mkdocs
mkdocs/config/config_options.py
{ "start": 31440, "end": 32174 }
class ____(Config): """An extra script to be added to the page. The `extra_javascript` config is a list of these.""" path = Type(str) """The value of the `src` tag of the script.""" type = Type(str, default='') """The value of the `type` tag of the script.""" defer = Type(bool, default=False) ...
ExtraScriptValue
python
pytorch__pytorch
test/test_tensor_creation_ops.py
{ "start": 184707, "end": 192736 }
class ____(TestCase): def _run_test(self, shape, dtype, count=-1, first=0, offset=None, **kwargs): numpy_dtype = torch_to_numpy_dtype_dict[dtype] if offset is None: offset = first * get_dtype_size(dtype) numpy_original = make_tensor(shape, dtype=dtype, device="cpu").numpy() ...
TestBufferProtocol
python
FactoryBoy__factory_boy
tests/test_declarations.py
{ "start": 5569, "end": 5775 }
class ____(unittest.TestCase): def test_transform(self): t = declarations.Transformer('foo', transform=str.upper) self.assertEqual("FOO", utils.evaluate_declaration(t))
TransformerTestCase
python
numba__numba
numba/core/ir.py
{ "start": 25614, "end": 26384 }
class ____(Stmt): """A raise statement inside a try-block. Similar to ``DynamicRaise`` but does not terminate. """ def __init__(self, exc_class, exc_args, loc): assert exc_class is None or isinstance(exc_class, type) assert isinstance(loc, Loc) assert exc_args is None or isinstan...
DynamicTryRaise
python
gevent__gevent
src/gevent/tests/test__makefile_ref.py
{ "start": 8653, "end": 16827 }
class ____(Test): def _ssl_connect_task(self, connector, port, accepted_event): connector.connect((DEFAULT_CONNECT, port)) try: # Note: We get ResourceWarning about 'x' # on Python 3 if we don't join the spawned thread x = ssl.SSLContext().wrap_socket(connector...
TestSSL
python
tiangolo__fastapi
docs_src/schema_extra_example/tutorial004.py
{ "start": 110, "end": 824 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item = Body( examples=[ { "name": "Foo", "descrip...
Item
python
networkx__networkx
networkx/algorithms/isomorphism/tests/test_ismags.py
{ "start": 19400, "end": 25325 }
class ____: def test_wikipedia_graph(self): edges1 = [ (1, 5), (1, 2), (1, 4), (3, 2), (6, 2), (3, 4), (7, 3), (4, 8), (5, 8), (6, 5), (6, 7), (7, 8), ] ...
TestDiGraphISO
python
pydantic__pydantic
pydantic/warnings.py
{ "start": 3925, "end": 4154 }
class ____(Warning): """A Pydantic specific experimental functionality warning. It is raised to warn users that the functionality may change or be removed in future versions of Pydantic. """
PydanticExperimentalWarning
python
Pylons__pyramid
tests/test_request.py
{ "start": 16739, "end": 18391 }
class ____(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def _callFUT(self, request, extensions=None): from pyramid.request import apply_request_extensions return apply_request_extensions(request, extensions=exten...
Test_apply_request_extensions
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels35.py
{ "start": 315, "end": 1482 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels35.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
spack__spack
lib/spack/spack/vendor/jinja2/ext.py
{ "start": 8361, "end": 20786 }
class ____(Extension): """This extension adds gettext support to Jinja.""" tags = {"trans"} # TODO: the i18n extension is currently reevaluating values in a few # situations. Take this example: # {% trans count=something() %}{{ count }} foo{% pluralize # %}{{ count }} fooss{% endtrans %...
InternationalizationExtension
python
google__pytype
pytype/overlays/abc_overlay.py
{ "start": 1352, "end": 1774 }
class ____(abstract.PyTDFunction): """Implements the @abc.abstractmethod decorator.""" @classmethod def make(cls, ctx, module): return super().make("abstractmethod", ctx, module) def call(self, node, func, args, alias_map=None): """Marks that the given function is abstract.""" del func, alias_map ...
AbstractMethod
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/cloud_memorystore.py
{ "start": 1617, "end": 1877 }
class ____(BaseGoogleLink): """Helper class for constructing Memorystore Memcached List of Instances Link.""" name = "Memorystore Memcached List of Instances" key = "memcached_instances" format_str = MEMCACHED_LIST_LINK
MemcachedInstanceListLink
python
doocs__leetcode
lcof/面试题44. 数字序列中某一位的数字/Solution.py
{ "start": 0, "end": 277 }
class ____: def findNthDigit(self, n: int) -> int: k, cnt = 1, 9 while k * cnt < n: n -= k * cnt k += 1 cnt *= 10 num = 10 ** (k - 1) + (n - 1) // k idx = (n - 1) % k return int(str(num)[idx])
Solution
python
bokeh__bokeh
tests/unit/bokeh/test_events.py
{ "start": 1735, "end": 13594 }
class ____: def __init__(self, attributes=[]) -> None: self.event_name = None self.attributes = attributes self.payload = {} def __call__(self, event): self.event_name = event.event_name self.payload = {attr:getattr(event, attr) for attr in self.attributes} def test_eve...
EventCallback
python
tensorflow__tensorflow
tensorflow/core/function/trace_type/serialization_test.py
{ "start": 2162, "end": 3206 }
class ____(serialization.Serializable): @classmethod def experimental_type_proto(cls): return serialization_test_pb2.MyMultiClassRepresentation @classmethod def experimental_from_proto(cls, proto): if proto.id == 1: return SerializableFromSuperClassOne() if proto.id == 2: return Seria...
MySerializableSuperClass
python
pypa__warehouse
warehouse/integrations/vulnerabilities/models.py
{ "start": 980, "end": 2049 }
class ____(db.ModelBase): __tablename__ = "vulnerabilities" source: Mapped[str] = mapped_column(primary_key=True) id: Mapped[str] = mapped_column(primary_key=True) # The URL for the vulnerability report at the source # e.g. "https://osv.dev/vulnerability/PYSEC-2021-314" link: Mapped[str | None...
VulnerabilityRecord
python
kamyu104__LeetCode-Solutions
Python/reach-end-of-array-with-max-score.py
{ "start": 38, "end": 296 }
class ____(object): def findMaximumScore(self, nums): """ :type nums: List[int] :rtype: int """ result = mx = 0 for x in nums: result += mx mx = max(mx, x) return result
Solution
python
pypa__pip
src/pip/_vendor/resolvelib/resolvers/resolution.py
{ "start": 21515, "end": 24212 }
class ____(AbstractResolver[RT, CT, KT]): """The thing that performs the actual resolution work.""" base_exception = ResolverException def resolve( # type: ignore[override] self, requirements: Iterable[RT], max_rounds: int = 100, ) -> Result[RT, CT, KT]: """Take a coll...
Resolver
python
ethereum__web3.py
web3/contract/async_contract.py
{ "start": 17617, "end": 19466 }
class ____(BaseContractCaller): # mypy types w3: "AsyncWeb3[Any]" def __init__( self, abi: ABI, w3: "AsyncWeb3[Any]", address: ChecksumAddress, transaction: TxParams | None = None, block_identifier: BlockIdentifier = None, ccip_read_enabled: bool | No...
AsyncContractCaller
python
astropy__astropy
astropy/units/tests/test_quantity_ufuncs.py
{ "start": 40284, "end": 40943 }
class ____: """Test the where argument in ufuncs.""" def test_where(self): q = np.arange(4.0) << u.m out = np.zeros(4) << u.m result = np.add(q, 1 * u.km, out=out, where=[True, True, True, False]) assert result is out assert_array_equal(result, [1000.0, 1001.0, 1002.0, 0...
TestWhere
python
h5py__h5py
h5py/tests/test_slicing.py
{ "start": 8951, "end": 10573 }
class ____(BaseSlicing): """ Field names for read & write """ dt = np.dtype([('a', 'f'), ('b', 'i'), ('c', 'f4')]) data = np.ones((100,), dtype=dt) def setUp(self): BaseSlicing.setUp(self) self.dset = self.f.create_dataset('x', (100,), dtype=self.dt) self.dset[...]...
TestFieldNames
python
matplotlib__matplotlib
lib/matplotlib/units.py
{ "start": 4266, "end": 5027 }
class ____(ConversionInterface): """Converter for decimal.Decimal data to float.""" @staticmethod def convert(value, unit, axis): """ Convert Decimals to floats. The *unit* and *axis* arguments are not used. Parameters ---------- value : decimal.Decimal or ...
DecimalConverter
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_utility_methods.py
{ "start": 2687, "end": 3044 }
class ____ { exampleMethod() { console.log("line1"); } } function baz() { console.log("bbq"); }""" ( indent_char, count_per_indent, first_indent_level, ) = CodeHierarchyNodeParser._get_indentation(text) assert indent_char == " " assert count_per_indent == 4 ...
Example
python
ray-project__ray
python/ray/serve/handle.py
{ "start": 1245, "end": 8827 }
class ____: def __init__( self, deployment_name: str, app_name: str, *, init_options: Optional[InitHandleOptionsBase] = None, handle_options: Optional[DynamicHandleOptionsBase] = None, _router: Optional[Router] = None, _create_router: Optional[CreateRo...
_DeploymentHandleBase
python
huggingface__transformers
src/transformers/integrations/integration_utils.py
{ "start": 62864, "end": 74980 }
class ____(TrainerCallback): """TrainerCallback that sends the logs to [Neptune](https://app.neptune.ai). Args: api_token (`str`, *optional*): Neptune API token obtained upon registration. You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment ...
NeptuneCallback
python
redis__redis-py
redis/asyncio/client.py
{ "start": 49892, "end": 50002 }
class ____(Protocol): def __call__(self, e: BaseException, pubsub: PubSub): ...
PubsubWorkerExceptionHandler
python
pyca__cryptography
src/cryptography/hazmat/primitives/_serialization.py
{ "start": 1947, "end": 2006 }
class ____(KeySerializationEncryption): pass
NoEncryption
python
getsentry__sentry
src/sentry/relay/config/metric_extraction.py
{ "start": 2408, "end": 34652 }
class ____(TypedDict): """Configuration for generic extraction of metrics from all data categories.""" version: int metrics: list[MetricSpec] def get_max_widget_specs(organization: Organization) -> int: if organization.id in options.get("on_demand.extended_widget_spec_orgs") and options.get( ...
MetricExtractionConfig
python
openai__openai-python
src/openai/types/video_download_content_params.py
{ "start": 216, "end": 405 }
class ____(TypedDict, total=False): variant: Literal["video", "thumbnail", "spritesheet"] """Which downloadable asset to return. Defaults to the MP4 video."""
VideoDownloadContentParams
python
kamyu104__LeetCode-Solutions
Python/intersection-of-two-arrays-ii.py
{ "start": 1459, "end": 2512 }
class ____(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ if len(nums1) > len(nums2): return self.intersect(nums2, nums1) def binary_search(compare, nums, left, right, target): ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 152745, "end": 153866 }
class ____(sgqlc.types.Input): """The filters that are available when fetching check runs.""" __schema__ = github_schema __field_names__ = ("check_type", "app_id", "check_name", "status", "statuses", "conclusions") check_type = sgqlc.types.Field(CheckRunType, graphql_name="checkType") """Filters th...
CheckRunFilter
python
getsentry__sentry
src/sentry/models/pullrequest.py
{ "start": 6548, "end": 6913 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded pull_request = FlexibleForeignKey("sentry.PullRequest") commit = FlexibleForeignKey("sentry.Commit", db_constraint=False) class Meta: app_label = "sentry" db_table = "sentry_pullrequest_commit" unique_together = ...
PullRequestCommit
python
django__django
tests/generic_relations/models.py
{ "start": 2832, "end": 2965 }
class ____(models.Model): has_tail = models.BooleanField(default=False) objects = GeckoManager() # To test fix for #11263
Gecko
python
getsentry__sentry
src/sentry/preprod/api/endpoints/project_preprod_artifact_delete.py
{ "start": 751, "end": 4614 }
class ____(PreprodArtifactEndpoint): owner = ApiOwner.EMERGE_TOOLS publish_status = { "DELETE": ApiPublishStatus.EXPERIMENTAL, } def delete( self, request: Request, project: Project, head_artifact_id: int, head_artifact: PreprodArtifact, ) -> Response...
ProjectPreprodArtifactDeleteEndpoint
python
psf__black
tests/data/cases/dummy_implementations.py
{ "start": 981, "end": 1137 }
class ____: async def async_method(self): ... async def async_function(self): ... @decorated async def async_function(self): ...
AsyncCls
python
openai__openai-python
src/openai/types/shared/custom_tool_input_format.py
{ "start": 299, "end": 402 }
class ____(BaseModel): type: Literal["text"] """Unconstrained text format. Always `text`."""
Text
python
apache__airflow
airflow-ctl/tests/airflow_ctl/api/test_operations.py
{ "start": 39251, "end": 40337 }
class ____: job_response = JobResponse( id=1, dag_id="dag_id", state="state", job_type="job_type", start_date=datetime.datetime(2024, 12, 31, 23, 59, 59), end_date=datetime.datetime(2025, 1, 1, 0, 0, 0), latest_heartbeat=datetime.datetime(2025, 1, 1, 0, 0, 0),...
TestJobsOperations
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/tuple7.py
{ "start": 1071, "end": 1154 }
class ____(Generic[_T]): def __init__(self): self._x: tuple[_T, ...] = ()
X
python
spack__spack
lib/spack/spack/error.py
{ "start": 6400, "end": 6513 }
class ____(SpackError): """Raised if something goes wrong when probing or querying a compiler."""
CompilerError
python
squidfunk__mkdocs-material
material/plugins/tags/config.py
{ "start": 1713, "end": 3859 }
class ____(Config): enabled = Type(bool, default = True) # Settings for filtering filters = SubConfig(FilterConfig) # Settings for tags tags = Type(bool, default = True) tags_slugify = Type(Callable, default = slugify(case = "lower")) tags_slugify_separator = Type(str, default = "-") t...
TagsConfig