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 | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integrations.py | {
"start": 120,
"end": 4313
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-integrations"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.integration = self.create_integration(
organization=self.organization,
provider="example",
name="E... | OrganizationIntegrationsListTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/unit_tests/integration/test_assignees.py | {
"start": 820,
"end": 8570
} | class ____(TestCase):
def setUp(self) -> None:
"""Base setup for all tests. Add responses for:
1. rate limit checker
2. repositories
3. branches
"""
self.r_mock = HttpMocker()
self.r_mock.__enter__()
self.r_mock.get(
HttpRequest(
... | AssigneesTest |
python | ray-project__ray | python/ray/experimental/channel/serialization_context.py | {
"start": 234,
"end": 10055
} | class ____:
def __init__(self):
# If true, then tensors found in the data to serialize are extracted
# and the caller should send them through an external transport.
self._use_external_transport: bool = False
# If _use_external_transport is True, then these are
# the tensors ... | _SerializationContext |
python | django__django | django/contrib/postgres/aggregates/statistics.py | {
"start": 1277,
"end": 1339
} | class ____(StatAggregate):
function = "REGR_SLOPE"
| RegrSlope |
python | doocs__leetcode | solution/2300-2399/2390.Removing Stars From a String/Solution.py | {
"start": 0,
"end": 222
} | class ____:
def removeStars(self, s: str) -> str:
ans = []
for c in s:
if c == '*':
ans.pop()
else:
ans.append(c)
return ''.join(ans)
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/test_utils.py | {
"start": 10623,
"end": 11540
} | class ____(RunLauncher, ConfigurableClass):
def __init__(self, inst_data: Optional[ConfigurableClassData] = None):
self._inst_data = inst_data
super().__init__()
@property
def inst_data(self) -> Optional[ConfigurableClassData]:
return self._inst_data
@classmethod
def confi... | ExplodingRunLauncher |
python | pytorch__pytorch | torchgen/model.py | {
"start": 106289,
"end": 112143
} | class ____:
view: NativeFunction
# Note: the {view}_copy operator is optional because we currently don't generate copy variants
# for all view ops. Notably, we don't generate them for CompositeImplicitAutograd views
# (we already get them "for free" through decomposition)
view_copy: NativeFunction |... | NativeFunctionsViewGroup |
python | openai__openai-python | src/openai/types/responses/response_mcp_list_tools_failed_event.py | {
"start": 208,
"end": 604
} | class ____(BaseModel):
item_id: str
"""The ID of the MCP tool call item that failed."""
output_index: int
"""The index of the output item that failed."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.mcp_list_tools.failed"]
"""The type of the ev... | ResponseMcpListToolsFailedEvent |
python | has2k1__plotnine | plotnine/guides/guide_colorbar.py | {
"start": 938,
"end": 13533
} | class ____(guide):
"""
Guide colorbar
Notes
-----
To correctly place a rasterized colorbar when saving the plot as an `svg`
or `pdf`, you should set the `dpi` to 72 i.e. `theme(dpi=72)`{.py}.
"""
nbin: Optional[int] = None
"""
Number of bins for drawing a colorbar. A larger val... | guide_colorbar |
python | eventlet__eventlet | tests/queue_test.py | {
"start": 7988,
"end": 10594
} | class ____(tests.LimitedTestCase):
def test_put_nowait_simple(self):
hub = hubs.get_hub()
result = []
q = eventlet.Queue(1)
hub.schedule_call_global(0, store_result, result, q.put_nowait, 2)
hub.schedule_call_global(0, store_result, result, q.put_nowait, 3)
eventlet.s... | TestNoWait |
python | langchain-ai__langchain | libs/core/langchain_core/callbacks/manager.py | {
"start": 53019,
"end": 65324
} | class ____(BaseCallbackManager):
"""Async callback manager that handles callbacks from LangChain."""
@property
def is_async(self) -> bool:
"""Return whether the handler is async."""
return True
async def on_llm_start(
self,
serialized: dict[str, Any],
prompts: l... | AsyncCallbackManager |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-kaltura/llama_index/readers/kaltura_esearch/base.py | {
"start": 262,
"end": 12206
} | class ____(BaseReader):
"""Kaltura eSearch API Reader."""
def __init__(
self,
partner_id: int = 0,
api_secret: str = "INSERT_YOUR_ADMIN_SECRET",
user_id: str = "INSERT_YOUR_USER_ID",
ks_type: int = 2,
ks_expiry: int = 86400,
ks_privileges: str = "disablee... | KalturaESearchReader |
python | google__pytype | pytype/errors/error_types.py | {
"start": 5107,
"end": 5274
} | class ____(Exception):
def __init__(self, left_type, other_type):
super().__init__()
self.left_type = left_type
self.other_type = other_type
| ProtocolError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 562865,
"end": 563366
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DeleteVerifiableDomain"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "owner")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the m... | DeleteVerifiableDomainPayload |
python | encode__django-rest-framework | tests/test_encoders.py | {
"start": 355,
"end": 420
} | class ____:
def tolist(self):
return [1, 2, 3]
| MockList |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 191044,
"end": 194834
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
def _path(self, name):
base = "tensorflow/core/lib/webp/testdata/"
return os.path.join(base, name)
@parameterized.named_parameters([
("_rgbNoise", "RGB_noise_large_pixels_115x115.webp", (1, 115, 115, 3)),
("_lossless", "lossless... | WebpTest |
python | huggingface__transformers | src/transformers/models/jamba/modeling_jamba.py | {
"start": 30322,
"end": 32071
} | class ____(nn.Module):
"""
This implementation is
strictly equivalent to standard MoE with full capacity (no
dropped tokens). It's faster since it formulates MoE operations
in terms of block-sparse operations to accommodate imbalanced
assignments of tokens to experts, whereas standard MoE either... | JambaSparseMoeBlock |
python | doocs__leetcode | solution/0500-0599/0576.Out of Boundary Paths/Solution.py | {
"start": 0,
"end": 601
} | class ____:
def findPaths(
self, m: int, n: int, maxMove: int, startRow: int, startColumn: int
) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if not 0 <= i < m or not 0 <= j < n:
return int(k >= 0)
if k <= 0:
return 0
... | Solution |
python | encode__starlette | starlette/responses.py | {
"start": 9519,
"end": 9665
} | class ____(Exception):
def __init__(self, content: str = "Malformed range header.") -> None:
self.content = content
| MalformedRangeHeader |
python | tensorflow__tensorflow | tensorflow/python/training/optimizer.py | {
"start": 3709,
"end": 4176
} | class ____(metaclass=abc.ABCMeta):
"""Interface for abstracting over variables in the optimizers."""
@abc.abstractmethod
def target(self):
"""Returns the optimization target for this variable."""
raise NotImplementedError("Calling an abstract method.")
@abc.abstractmethod
def update_op(self, optimiz... | _OptimizableVariable |
python | catalyst-team__catalyst | tests/benchmarks/test_benchmark.py | {
"start": 520,
"end": 624
} | class ____(str, enum.Enum):
"""RunModes."""
catalyst = "catalyst"
pytorch = "pytorch"
| RunMode |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/claude/diagnostics.py | {
"start": 688,
"end": 12469
} | class ____:
"""Central diagnostics service for scaffold branch operations."""
def __init__(
self,
level: DiagnosticsLevel = "off",
output_dir: Optional[Path] = None,
correlation_id: Optional[str] = None,
):
self.level = level
self.correlation_id = correlation... | ClaudeDiagnostics |
python | spyder-ide__spyder | spyder/utils/color_system.py | {
"start": 1997,
"end": 2170
} | class ____:
"""
Colors for the Python and Spyder logos.
"""
B10 = '#3775a9'
B20 = '#ffd444'
B30 = '#414141'
B40 = '#fafafa'
B50 = '#8c0000' | Logos |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/serdes/serdes.py | {
"start": 19060,
"end": 20968
} | class ____:
"""values are unpacked bottom up."""
def __init__(self):
self.observed_unknown_serdes_values: set[UnknownSerdesValue] = set()
def assert_no_unknown_values(self, obj: UnpackedValue) -> PackableValue:
if isinstance(obj, UnknownSerdesValue):
raise DeserializationError(... | UnpackContext |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datastore.py | {
"start": 17286,
"end": 19385
} | class ____(GoogleCloudBaseOperator):
"""
Roll back a transaction.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDatastoreRollbackOperator`
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1... | CloudDatastoreRollbackOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol17.py | {
"start": 1496,
"end": 1684
} | class ____(Protocol[_T1_contra]):
# This should generate an error because a contravariant TypeVar
# should not be used as a return type.
def m1(self) -> _T1_contra: ...
| Protocol7 |
python | pypa__hatch | tests/backend/metadata/test_hatch.py | {
"start": 6265,
"end": 7131
} | class ____:
def test_default(self, isolation):
config = {}
metadata = HatchMetadata(str(isolation), config, None)
assert metadata.metadata.allow_ambiguous_features is metadata.metadata.allow_ambiguous_features is False
def test_not_boolean(self, isolation):
config = {"metadata"... | TestMetadataAllowAmbiguousFeatures |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/custom_nest_trace_type.py | {
"start": 1027,
"end": 5425
} | class ____(trace.TraceType):
"""Represents the TraceType of a class implmenting the CustomNestProtocol."""
def __init__(
self,
value_type: Type[Any],
metadata: Any,
components: PythonTuple[trace.TraceType],
):
if not issubclass(value_type, custom_nest_protocol.CustomNestProtocol):
... | CustomNestTraceType |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 7443,
"end": 7691
} | class ____:
def process_spider_output(self, response, result):
yield from result
async def process_spider_output_async(self, response, result):
async for r in result:
yield r
| ProcessSpiderOutputUniversalMiddleware |
python | redis__redis-py | redis/commands/core.py | {
"start": 250215,
"end": 250633
} | class ____(
AsyncBasicKeyCommands,
AsyncHyperlogCommands,
AsyncHashCommands,
AsyncGeoCommands,
AsyncListCommands,
AsyncScanCommands,
AsyncSetCommands,
AsyncStreamCommands,
AsyncSortedSetCommands,
):
"""
A class containing all of the implemented data access redis commands.
... | AsyncDataAccessCommands |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 329560,
"end": 333626
} | class ____:
"""link or outline destination details"""
def __init__(self, obj, rlink, document=None):
isExt = obj.is_external
isInt = not isExt
self.dest = ""
self.file_spec = ""
self.flags = 0
self.is_map = False
self.is_uri = False
self.kind = LI... | linkDest |
python | jina-ai__jina | jina/serve/runtimes/servers/load_balancer.py | {
"start": 77,
"end": 2225
} | class ____(BaseServer):
"""Base FastAPI server. Implement this abstract class in-case you want to build a fastapi-based server by
implementing the `app` property. This property should return a fastapi app. The base Gateway will handle starting
a server and serving the application using that server."""
... | LoadBalancingServer |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 8889,
"end": 10996
} | class ____:
def test_getitem_node(self) -> None:
folder1 = DataTree.from_dict(
{
"/results/highres": DataTree(),
}
)
assert folder1["results"].name == "results"
assert folder1["results/highres"].name == "highres"
def test_getitem_self(sel... | TestGetItem |
python | cherrypy__cherrypy | cherrypy/lib/cpstats.py | {
"start": 10077,
"end": 11781
} | class ____(object):
"""Wraps a file-like object, counting the number of bytes read."""
def __init__(self, rfile):
"""Initialize a read byte counter."""
self.rfile = rfile
self.bytes_read = 0
def read(self, size=-1):
"""Read from file, counting bytes."""
data = self.... | ByteCountWrapper |
python | doocs__leetcode | solution/3500-3599/3597.Partition String/Solution2.py | {
"start": 532,
"end": 895
} | class ____:
def partitionString(self, s: str) -> List[str]:
hashing = Hashing(s)
vis = set()
l = 1
ans = []
for r, c in enumerate(s, 1):
x = hashing.query(l, r)
if x not in vis:
vis.add(x)
ans.append(s[l - 1 : r])
... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-sigma/dagster_sigma/resource.py | {
"start": 31589,
"end": 33207
} | class ____(StateBackedDefinitionsLoader[SigmaOrganizationData]):
organization: SigmaOrganization
translator: DagsterSigmaTranslator
snapshot: Optional[RepositoryLoadData]
sigma_filter: Optional[SigmaFilter] = None
fetch_column_data: bool = True
fetch_lineage_data: bool = True
@property
... | SigmaOrganizationDefsLoader |
python | walkccc__LeetCode | solutions/1326. Minimum Number of Taps to Open to Water a Garden/1326.py | {
"start": 0,
"end": 436
} | class ____:
def minTaps(self, n: int, ranges: list[int]) -> int:
nums = [0] * (n + 1)
for i, range_ in enumerate(ranges):
l = max(0, i - range_)
r = min(n, range_ + i)
nums[l] = max(nums[l], r - l)
ans = 0
end = 0
farthest = 0
for i in range(n):
farthest = max(farthe... | Solution |
python | donnemartin__system-design-primer | solutions/object_oriented_design/call_center/call_center.py | {
"start": 1502,
"end": 1756
} | class ____(Employee):
def __init__(self, employee_id, name):
super(Operator, self).__init__(employee_id, name, Rank.DIRECTOR)
def escalate_call(self):
raise NotImplementedError('Directors must be able to handle any call')
| Director |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 87759,
"end": 98372
} | class ____(XLNetPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.start_n_top = config.start_n_top
self.end_n_top = config.end_n_top
self.transformer = XLNetModel(config)
self.start_logits = XLNetPoolerStartLogits(config)
self.end_logits = X... | XLNetForQuestionAnswering |
python | squidfunk__mkdocs-material | material/plugins/social/layout.py | {
"start": 2990,
"end": 3338
} | class ____(Config):
content = Type(str, default = "")
align = Choice(Origin, default = "start top")
overflow = Choice(Overflow, default = "truncate")
color = Type(str, default = "")
line = SubConfig(Line)
font = SubConfig(Font)
# -----------------------------------------------------------------... | Typography |
python | jazzband__django-oauth-toolkit | tests/test_client_credential.py | {
"start": 5912,
"end": 7310
} | class ____(BaseTest):
def test_client_resource_password_based(self):
"""
Request an access token using Resource Owner Password Based flow
"""
self.application.delete()
self.application = Application.objects.create(
name="test_client_credentials_app",
... | TestClientResourcePasswordBased |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 15848,
"end": 26409
} | class ____(_TestJointOps, __TestCase):
thetype = set
basetype = set
def test_init(self):
s = self.thetype()
s.__init__(self.word)
self.assertEqual(s, set(self.word))
s.__init__(self.otherword)
self.assertEqual(s, set(self.otherword))
self.assertRaises(TypeErr... | TestSet |
python | gevent__gevent | src/greentest/3.14/test_ssl.py | {
"start": 10108,
"end": 34930
} | class ____(unittest.TestCase):
def test_constants(self):
ssl.CERT_NONE
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
ssl.OP_CIPHER_SERVER_PREFERENCE
ssl.OP_SINGLE_DH_USE
ssl.OP_SINGLE_ECDH_USE
ssl.OP_NO_COMPRESSION
self.assertEqual(ssl.HAS_SNI, True)
se... | BasicSocketTests |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 58074,
"end": 58332
} | class ____(PrefectBaseModel):
"""A representation of an installed Prefect integration."""
name: str = Field(description="The name of the Prefect integration.")
version: str = Field(description="The version of the Prefect integration.")
| Integration |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/app_blur.py | {
"start": 113,
"end": 668
} | class ____(App[None]):
CSS = """
Screen {
align: center middle;
}
Input {
width: 50%;
margin-bottom: 1;
&:focus {
width: 75%;
border: thick green;
background: pink;
}
}
"""
def compose(self) -> ComposeResult:
... | AppBlurApp |
python | PrefectHQ__prefect | tests/client/test_prefect_client.py | {
"start": 88053,
"end": 99385
} | class ____:
@pytest.fixture
def automation(self):
return AutomationCore(
name="test-automation",
trigger=EventTrigger(
match={"flow_run_id": "123"},
posture=Posture.Reactive,
threshold=1,
within=0,
),
... | TestAutomations |
python | huggingface__transformers | src/transformers/models/jetmoe/modeling_jetmoe.py | {
"start": 9819,
"end": 12024
} | class ____(nn.Module):
"""
A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: JetMoeConfig):
super().__init__()
self.input_size =... | JetMoeMoE |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py | {
"start": 178,
"end": 982
} | class ____(ValidationRule):
def enter_Argument(self, node, key, parent, path, ancestors):
arg_def = self.context.get_argument()
if arg_def:
errors = is_valid_literal_value(arg_def.type, node.value)
if errors:
self.context.report_error(GraphQLError(
... | ArgumentsOfCorrectType |
python | keras-team__keras | integration_tests/dataset_tests/reuters_test.py | {
"start": 91,
"end": 1953
} | class ____(testing.TestCase):
def test_load_data_default(self):
(x_train, y_train), (x_test, y_test) = reuters.load_data()
# Check types
self.assertIsInstance(x_train, np.ndarray)
self.assertIsInstance(y_train, np.ndarray)
self.assertIsInstance(x_test, np.ndarray)
sel... | ReutersLoadDataTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 139603,
"end": 140226
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("repository_id", "limit", "expiry", "client_mutation_id")
repository_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="repositoryId"
)
limit = sgqlc... | SetRepositoryInteractionLimitInput |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 50253,
"end": 50835
} | class ____(Interface):
"""Class which provides code introspection capability associated with an
action. The ParserInfo class used by ZCML implements the same interface.
"""
file = Attribute('Filename of action-invoking code as a string')
line = Attribute(
'Starting line number in file (as ... | IActionInfo |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_property_types.py | {
"start": 6281,
"end": 6551
} | class ____(_ItemProperties):
obj_type: Literal['type']
_obj___name__: str | None
_obj___qualname__: str | None
_obj___value__: str # The aliased annotation
@property
def _groupwise_order_key(self) -> int:
return 70
| _TypeStatementProperties |
python | huggingface__transformers | src/transformers/models/fuyu/configuration_fuyu.py | {
"start": 919,
"end": 8839
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FuyuForCausalLM`]. It is used to instantiate an
Fuyu model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar conf... | FuyuConfig |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/schemas/role_and_permission_schema.py | {
"start": 1047,
"end": 1198
} | class ____(SQLAlchemySchema):
"""Action Schema."""
class Meta:
"""Meta."""
model = Action
name = auto_field()
| ActionSchema |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 3077,
"end": 3196
} | class ____(TypedDict):
type: Literal["slice"]
start: int | None
stop: int | None
step: int | None
| SliceRep |
python | jazzband__django-oauth-toolkit | oauth2_provider/contrib/rest_framework/permissions.py | {
"start": 4143,
"end": 6586
} | class ____(BasePermission):
"""
:attr:alternate_required_scopes: dict keyed by HTTP method name with value: iterable alternate scope lists
This fulfills the [Open API Specification (OAS; formerly Swagger)](https://www.openapis.org/)
list of alternative Security Requirements Objects for oauth2 or openId... | TokenMatchesOASRequirements |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/4_Sarsa_lambda_maze/maze_env.py | {
"start": 592,
"end": 4013
} | class ____(tk.Tk, object):
def __init__(self):
super(Maze, self).__init__()
self.action_space = ['u', 'd', 'l', 'r']
self.n_actions = len(self.action_space)
self.title('maze')
self.geometry('{0}x{1}'.format(MAZE_W * UNIT, MAZE_H * UNIT))
self._build_maze()
def _b... | Maze |
python | kubernetes-client__python | kubernetes/client/models/v1_node_config_source.py | {
"start": 383,
"end": 3507
} | 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... | V1NodeConfigSource |
python | mlflow__mlflow | mlflow/utils/autologging_utils/__init__.py | {
"start": 9014,
"end": 29492
} | class ____:
"""
The BatchMetricsLogger will log metrics in batch against an mlflow run.
If run_id is passed to to constructor then all recording and logging will
happen against that run_id.
If no run_id is passed into constructor, then the run ID will be fetched
from `mlflow.active_run()` each t... | BatchMetricsLogger |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 192003,
"end": 194101
} | class ____:
"""Tests kstest and ks_1samp agree with K-S various sizes, alternatives, modes."""
def _testOne(self, x, alternative, expected_statistic, expected_prob,
mode='auto', decimal=14):
result = stats.kstest(x, 'norm', alternative=alternative, mode=mode)
expected = np.arra... | TestKSTest |
python | dask__dask | dask/array/_array_expr/random.py | {
"start": 33036,
"end": 36204
} | class ____(IO):
_parameters = [
"rng",
"distribution",
"size",
"chunks",
"extra_chunks",
"args",
"kwargs",
]
_defaults = {"extra_chunks": ()}
@cached_property
def kwargs(self):
return self.operand("kwargs")
@property
def chunk... | Random |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 998393,
"end": 999141
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for TeamDiscussion."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("TeamDiscussionEdge"), graphql_name="edges")
"""A list of edges."""
... | TeamDiscussionConnection |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_stats.py | {
"start": 327,
"end": 4041
} | class ____(APITestCase, OutcomesSnubaTest):
def test_simple(self) -> None:
self.login_as(user=self.user)
org = self.create_organization(owner=self.user)
project = self.create_project(organization=org)
project_key = self.create_project_key(project=project)
self.store_outcomes... | OrganizationStatsTest |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py | {
"start": 10561,
"end": 11773
} | class ____(Benchmark):
r"""
Mishra 5 objective function.
This class defines the Mishra 5 [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Mishra05}}(x) = \left [ \sin^2 ((\cos(x_1) + \cos(x_2))^2)
+ \cos^2 ((\sin(x_1... | Mishra05 |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_adapter.py | {
"start": 876,
"end": 2822
} | class ____:
"""API to reshard a checkpoint value during restore.
When a ReshardCallback is attached to a CheckpointPosition, the restored value
of the checkpoint position is resharded based on this callback.
"""
def object_name(self) -> str:
"""Returns the local name of the object being restored.
O... | ReshardCallback |
python | doocs__leetcode | solution/2500-2599/2592.Maximize Greatness of an Array/Solution.py | {
"start": 0,
"end": 176
} | class ____:
def maximizeGreatness(self, nums: List[int]) -> int:
nums.sort()
i = 0
for x in nums:
i += x > nums[i]
return i
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/tuple7.py | {
"start": 153,
"end": 651
} | class ____(tuple[int, str, int, _T]):
def __new__(cls) -> Self: ...
objA = ClassA[complex]()
(a, b, c, d) = objA
aa1: int = a
bb1: str = b
cc1: int = c
dd1: complex = d
reveal_type(objA[0], expected_text="int")
reveal_type(objA[1], expected_text="str")
reveal_type(objA[2], expected_text="int")
reveal_type(objA... | ClassA |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py | {
"start": 5982,
"end": 6183
} | class ____(BaseFSHandler):
@web.authenticated
@authorized
def get(self):
result = self.fs_isdir(self.get_path_argument("path"))
self.write_json({"isdir": result})
| IsDirHandler |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 8273,
"end": 8327
} | class ____(XsdUnsignedInt):
pass
| ST_DrawingElementId |
python | tensorflow__tensorflow | tensorflow/python/platform/flags_test.py | {
"start": 1971,
"end": 4562
} | class ____(unittest.TestCase):
def setUp(self):
self.original_flags = flags.FlagValues()
self.wrapped_flags = flags._FlagValuesWrapper(self.original_flags)
flags.DEFINE_string(
'test', 'default', 'test flag', flag_values=self.wrapped_flags)
def test_attribute_overrides(self):
# Test that m... | FlagsTest |
python | django__django | tests/test_runner_apps/simple/tests.py | {
"start": 339,
"end": 447
} | class ____(SimpleTestCase):
def test_1(self):
pass
def test_2(self):
pass
| SimpleCase1 |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/relativity/relativity.py | {
"start": 9220,
"end": 10257
} | class ____(pTypes.GroupParameter):
def __init__(self, **kwds):
defs = dict(name="Grid", autoIncrementName=True, renamable=True, removable=True, children=[
dict(name='Number of Clocks', type='int', value=5, limits=[1, None]),
dict(name='Spacing', type='float', value=1.0, step=0.1),
... | GridParam |
python | doocs__leetcode | solution/3200-3299/3286.Find a Safe Walk Through a Grid/Solution.py | {
"start": 0,
"end": 701
} | class ____:
def findSafeWalk(self, grid: List[List[int]], health: int) -> bool:
m, n = len(grid), len(grid[0])
dist = [[inf] * n for _ in range(m)]
dist[0][0] = grid[0][0]
q = deque([(0, 0)])
dirs = (-1, 0, 1, 0, -1)
while q:
x, y = q.popleft()
... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_cloud_batch.py | {
"start": 1566,
"end": 5846
} | class ____:
def test_serialization(self, trigger):
classpath, kwargs = trigger.serialize()
assert classpath == "airflow.providers.google.cloud.triggers.cloud_batch.CloudBatchJobFinishedTrigger"
assert kwargs == {
"project_id": PROJECT_ID,
"job_name": JOB_NAME,
... | TestCloudBatchJobFinishedTrigger |
python | pytorch__pytorch | test/test_overrides.py | {
"start": 49662,
"end": 49989
} | class ____(TestCase):
# Regression test for gh-54457
def test_iterator(self):
t = torch.tensor([5, 6, 7]).as_subclass(SubTensor2)
it = iter(t)
self.assertIs(type(next(it)), SubTensor2)
self.assertIs(type(next(it)), SubTensor2)
self.assertIs(type(next(it)), SubTensor2)
| TestIterator |
python | walkccc__LeetCode | solutions/1365. How Many Numbers Are Smaller Than the Current Number/1365.py | {
"start": 0,
"end": 277
} | class ____:
def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:
MAX = 100
count = collections.Counter(nums)
for i in range(1, MAX + 1):
count[i] += count[i - 1]
return [0 if num == 0 else count[num - 1]
for num in nums]
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC201_google.py | {
"start": 3089,
"end": 3183
} | class ____:
# OK
def __new__(cls) -> 'Spam':
"""New!!"""
return cls()
| Spam |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_inheritance.py | {
"start": 1325,
"end": 1687
} | class ____(fixtures.TestBase, testing.AssertsExecutionResults):
def setup_test(self):
global Base
self.mapper_registry = registry()
Base = self.mapper_registry.generate_base()
def teardown_test(self):
close_all_sessions()
self.mapper_registry.dispose()
Base.metad... | DeclarativeTestBase |
python | getsentry__sentry | src/sentry/metrics/dogstatsd.py | {
"start": 690,
"end": 4573
} | class ____(MetricsBackend):
def __init__(self, prefix: str | None = None, **kwargs: Any) -> None:
# TODO(dcramer): it'd be nice if the initialize call wasn't a global
self.tags = kwargs.pop("tags", None)
kwargs["statsd_disable_buffering"] = False
initialize(**kwargs)
statsd.... | DogStatsdMetricsBackend |
python | cython__cython | Demos/benchmarks/bm_raytrace.py | {
"start": 9678,
"end": 11391
} | class ____(SimpleSurface):
def __init__(self, **kwargs):
SimpleSurface.__init__(self, **kwargs)
self.otherColour = kwargs.get('otherColour', (0, 0, 0))
self.checkSize = kwargs.get('checkSize', 1)
def baseColourAt(self, p):
v = p - Point.ZERO
v.scale(1.0 / self.checkSize... | CheckerboardSurface |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_page_view02.py | {
"start": 315,
"end": 1006
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("page_view02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with print options."""
workbook = ... | TestCompareXLSXFiles |
python | ansible__ansible | lib/ansible/galaxy/collection/gpg.py | {
"start": 4300,
"end": 4498
} | class ____(GpgBaseError):
"""The signature with the keyid is good, but the signature was made by a revoked key."""
keyid: str
username: str
@dataclass(frozen=True, slots=True)
| GpgRevKeySig |
python | apache__airflow | airflow-core/src/airflow/models/dag_favorite.py | {
"start": 992,
"end": 1327
} | class ____(Base):
"""Association table model linking users to their favorite DAGs."""
__tablename__ = "dag_favorite"
user_id: Mapped[str] = mapped_column(StringID(), primary_key=True)
dag_id: Mapped[str] = mapped_column(
StringID(), ForeignKey("dag.dag_id", ondelete="CASCADE"), primary_key=Tru... | DagFavorite |
python | pytransitions__transitions | transitions/extensions/nesting.py | {
"start": 3668,
"end": 6137
} | class ____(Event):
"""An event type to work with nested states.
This subclass is NOT compatible with simple Machine instances.
"""
def trigger(self, model, *args, **kwargs):
raise RuntimeError("NestedEvent.trigger must not be called directly. Call Machine.trigger_event instead.")
def t... | NestedEvent |
python | walkccc__LeetCode | solutions/1955. Count Number of Special Subsequences/1955-3.py | {
"start": 0,
"end": 546
} | class ____:
def countSpecialSubsequences(self, nums: list[int]) -> int:
MOD = 1_000_000_007
n = len(nums)
# dp[j] := the number of increasing subsequences of the numbers so far that
# end in j
dp = [0] * 3
if nums[0] == 0:
dp[0] = 1
for i in range(1, n):
if nums[i] == 0:
... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 1464,
"end": 1570
} | class ____:
"""Represents the details of an asset."""
id: str | None = None
@dataclass
| AssetDetails |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/components.py | {
"start": 1097,
"end": 2535
} | class ____(SubstreamPartitionRouter):
"""
We often require certain data to be fully retrieved from the parent stream before we begin requesting data from the child stream.
In this custom component, we execute stream slices twice: first, we retrieve all the parent_stream_fields,
and then we call stream s... | SprintIssuesSubstreamPartitionRouter |
python | fluentpython__example-code | 10-seq-hacking/vector_v1.py | {
"start": 1751,
"end": 2725
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components) # <1>
def __iter__(self):
return iter(self._components) # <2>
def __repr__(self):
components = reprlib.repr(self._components) # <3>
components = components... | Vector |
python | sanic-org__sanic | examples/request_stream/server.py | {
"start": 249,
"end": 1512
} | class ____(HTTPMethodView):
@stream_decorator
async def post(self, request):
result = ""
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.post("/stream", stre... | SimpleView |
python | numba__numba | numba/tests/test_target_extension.py | {
"start": 2121,
"end": 3874
} | class ____(CPUCodegen):
# This largely rips off the CPU for ease
_library_class = JITCodeLibrary
def _customize_tm_options(self, options):
# Customize the target machine options.
options["cpu"] = self._get_host_cpu_name()
arch = ll.Target.from_default_triple().name
if arch.... | JITDPUCodegen |
python | getsentry__sentry | src/sentry/tasks/summaries/utils.py | {
"start": 1176,
"end": 2432
} | class ____:
def __init__(
self, timestamp: float, duration: int, organization: Organization, daily: bool = False
):
self.timestamp = timestamp
self.duration = duration
self.start = to_datetime(timestamp - duration)
self.end = to_datetime(timestamp)
self.organiza... | OrganizationReportContext |
python | jina-ai__jina | tests/unit/serve/executors/test_executor.py | {
"start": 1006,
"end": 20697
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
docs.texts = ['foo' for _ in docs]
@requests(on='/bar')
def bar(self, docs, **kwargs):
docs.texts = ['bar' for _ in docs]
@pytest.fixture()
def exposed_port():
port = random_port()
yield port
@pytest.fixture(auto... | MyServeExec |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 11070,
"end": 12592
} | class ____(HasExpressionLookup, TypeEngine[int]):
"""A type for ``int`` integers."""
__visit_name__ = "integer"
operator_classes = OperatorClass.INTEGER
if TYPE_CHECKING:
@util.ro_memoized_property
def _type_affinity(self) -> Type[Integer]: ...
def get_dbapi_type(self, dbapi):
... | Integer |
python | Textualize__rich | benchmarks/benchmarks.py | {
"start": 314,
"end": 1828
} | class ____:
def setup(self):
self.console = Console(
file=StringIO(), color_system="truecolor", legacy_windows=False
)
self.len_lorem_ipsum = len(snippets.LOREM_IPSUM)
self.text = Text.from_markup(snippets.MARKUP)
def time_wrapping(self):
self.text.wrap(self.... | TextSuite |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/blobstore/gcs/main.py | {
"start": 2492,
"end": 3807
} | class ____(blobstore_handlers.BlobstoreDownloadHandler):
def get(self):
# Get the default Cloud Storage Bucket name and create a file name for
# the object in Cloud Storage.
bucket = app_identity.get_default_gcs_bucket_name()
# Cloud Storage file names are in the format /bucket/obje... | CreateAndServeFileHandler |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v3.0.0.d.py | {
"start": 805,
"end": 5827
} | class ____(BaseModel):
class TrialValueType(enum.Enum):
FINITE = 1
INF_POS = 2
INF_NEG = 3
__tablename__ = "trial_values"
trial_value_id = sa.Column(sa.Integer, primary_key=True)
value = sa.Column(sa.Float(precision=FLOAT_PRECISION), nullable=True)
value_type = sa.Column(sa.... | TrialValueModel |
python | mlflow__mlflow | tests/spark/test_spark_model_export.py | {
"start": 2621,
"end": 40635
} | class ____(NamedTuple):
model: Any
spark_df: Any
pandas_df: Any
predictions: Any
def _get_spark_session_with_retry(max_tries=3):
conf = pyspark.SparkConf()
for attempt in range(max_tries):
try:
return get_spark_session(conf)
except Exception as e:
if att... | SparkModelWithData |
python | apache__airflow | providers/dbt/cloud/tests/unit/dbt/cloud/hooks/test_dbt.py | {
"start": 4895,
"end": 50540
} | class ____:
# TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
# Connection with ``account_id`` specified
account_id_conn = Connection(
c... | TestDbtCloudHook |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/bug2437/autodoc_dummy_foo.py | {
"start": 0,
"end": 48
} | class ____:
"""Dummy class Foo."""
pass
| Foo |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 6789,
"end": 10107
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
bounding box loss. The latter is defined as a linear combination of... | Owlv2ObjectDetectionOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.