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 | apache__airflow | providers/amazon/tests/unit/amazon/aws/auth_manager/test_aws_auth_manager.py | {
"start": 3242,
"end": 25793
} | class ____:
def test_avp_facade(self, auth_manager):
assert hasattr(auth_manager, "avp_facade")
@pytest.mark.parametrize(
("details", "user", "expected_user", "expected_entity_id"),
[
(None, mock, ANY, None),
(ConfigurationDetails(section="test"), mock, mock, "te... | TestAwsAuthManager |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 3339,
"end": 5171
} | class ____(graphene.ObjectType):
id = graphene.NonNull(graphene.ID)
name = graphene.NonNull(graphene.String)
is_reload_supported = graphene.NonNull(graphene.Boolean)
environment_path = graphene.String()
repositories = non_null_list(lambda: GrapheneRepository)
server_id = graphene.String()
da... | GrapheneRepositoryLocation |
python | dagster-io__dagster | python_modules/libraries/dagster-deltalake-polars/dagster_deltalake_polars/deltalake_polars_type_handler.py | {
"start": 2299,
"end": 2592
} | class ____(DeltaLakeIOManager):
@staticmethod
def type_handlers() -> Sequence[DbTypeHandler]:
return [DeltaLakePolarsTypeHandler(), DeltaLakePyArrowTypeHandler()]
@staticmethod
def default_load_type() -> Optional[type]:
return pl.DataFrame
| DeltaLakePolarsIOManager |
python | doocs__leetcode | solution/2300-2399/2368.Reachable Nodes With Restrictions/Solution2.py | {
"start": 0,
"end": 516
} | class ____:
def reachableNodes(
self, n: int, edges: List[List[int]], restricted: List[int]
) -> int:
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = set(restricted + [0])
q = deque([0])
ans = 0
while q:... | Solution |
python | django__django | django/core/mail/backends/console.py | {
"start": 171,
"end": 1427
} | class ____(BaseEmailBackend):
def __init__(self, *args, **kwargs):
self.stream = kwargs.pop("stream", sys.stdout)
self._lock = threading.RLock()
super().__init__(*args, **kwargs)
def write_message(self, message):
msg = message.message()
msg_data = msg.as_bytes()
... | EmailBackend |
python | ray-project__ray | rllib/core/learner/learner_group.py | {
"start": 2503,
"end": 3070
} | class ____(BackendExecutor):
# Override `BackendExecutor` placement group creation logic. We need to pass our own
# to make sure the one of the Algorithm (Trainable) is used for all the
# Algorithm's actors.
def _create_placement_group(self):
pass
# TODO (sven): Change this once there is a ... | RLlibBackendExecutor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/integration/config.py | {
"start": 533,
"end": 2272
} | class ____:
def __init__(self) -> None:
self._config: MutableMapping[str, Any] = {
"account_ids": [ACCOUNT_ID],
"access_token": ACCESS_TOKEN,
"credentials": {
"auth_type": "Service",
"access_token": ACCESS_TOKEN,
},
... | ConfigBuilder |
python | pandas-dev__pandas | pandas/tests/series/methods/test_to_frame.py | {
"start": 107,
"end": 1992
} | class ____:
def test_to_frame_respects_name_none(self):
# GH#44212 if we explicitly pass name=None, then that should be respected,
# not changed to 0
# GH-45448 this is first deprecated & enforced in 2.0
ser = Series(range(3))
result = ser.to_frame(None)
exp_index =... | TestToFrame |
python | kamyu104__LeetCode-Solutions | Python/find-the-winner-of-an-array-game.py | {
"start": 29,
"end": 446
} | class ____(object):
def getWinner(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
result = arr[0]
count = 0
for i in xrange(1, len(arr)):
if arr[i] > result:
result = arr[i]
count = 0
... | Solution |
python | ipython__ipython | IPython/utils/_process_win32_controller.py | {
"start": 1769,
"end": 5124
} | class ____(ctypes.Structure):
_fields_ = [("hProcess", HANDLE),
("hThread", HANDLE),
("dwProcessId", DWORD),
("dwThreadId", DWORD)]
LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
# Win32 API constants needed
ERROR_HANDLE_EOF = 38
ERROR_BROKEN_PIPE = 109
ERROR_N... | PROCESS_INFORMATION |
python | openai__openai-python | src/openai/types/audio/transcription_text_done_event.py | {
"start": 1323,
"end": 1940
} | class ____(BaseModel):
text: str
"""The text that was transcribed."""
type: Literal["transcript.text.done"]
"""The type of the event. Always `transcript.text.done`."""
logprobs: Optional[List[Logprob]] = None
"""The log probabilities of the individual tokens in the transcription.
Only inc... | TranscriptionTextDoneEvent |
python | huggingface__transformers | src/transformers/models/phimoe/modeling_phimoe.py | {
"start": 9178,
"end": 12328
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: PhimoeConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size ... | PhimoeAttention |
python | pypa__setuptools | setuptools/_vendor/autocommand/autoparse.py | {
"start": 1464,
"end": 11642
} | class ____(DocstringError):
'''
The docstring had too many ---- section splits. Currently we only support
using up to a single split, to split the docstring into description and
epilog parts.
'''
def _get_type_description(annotation):
'''
Given an annotation, return the (type, description)... | TooManySplitsError |
python | apache__airflow | airflow-core/src/airflow/utils/event_scheduler.py | {
"start": 948,
"end": 1654
} | class ____(scheduler, LoggingMixin):
"""General purpose event scheduler."""
def call_regular_interval(
self,
delay: float,
action: Callable,
arguments=(),
kwargs=None,
):
"""Call a function at (roughly) a given interval."""
def repeat(*args, **kwargs... | EventScheduler |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/metrics_test.py | {
"start": 61017,
"end": 66188
} | class ____(test.TestCase):
def setUp(self):
np.random.seed(1)
ops.reset_default_graph()
@test_util.run_deprecated_v1
def testVars(self):
metrics.sensitivity_at_specificity(
predictions=array_ops.ones((10, 1)),
labels=array_ops.ones((10, 1)),
specificity=0.7)
_assert_metri... | SensitivityAtSpecificityTest |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 5362,
"end": 6647
} | class ____:
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.G.nodes[3]["foo"] = "bar"
cls.nv = cls.G.nodes
def n_its(self, nodes):
return set(nodes)
def test_len(self):
G = self.G.copy()
nv = G.nodes
assert len(nv) == 9
G.... | TestNodeViewSetOps |
python | django-extensions__django-extensions | django_extensions/management/commands/admin_generator.py | {
"start": 3505,
"end": 9569
} | class ____(UnicodeMixin):
PRINTABLE_PROPERTIES = (
"list_display",
"list_filter",
"raw_id_fields",
"search_fields",
"prepopulated_fields",
"date_hierarchy",
)
def __init__(
self,
model,
raw_id_threshold=RAW_ID_THRESHOLD,
list_f... | AdminModel |
python | networkx__networkx | networkx/classes/tests/test_multidigraph.py | {
"start": 15272,
"end": 16342
} | class ____(TestMultiDiGraph):
def setup_method(self):
self.Graph = MultiDiGraphSubClass
# build K3
self.k3edges = [(0, 1), (0, 2), (1, 2)]
self.k3nodes = [0, 1, 2]
self.K3 = self.Graph()
self.K3._succ = self.K3.adjlist_outer_dict_factory(
{
... | TestMultiDiGraphSubclass |
python | huggingface__transformers | src/transformers/models/fuyu/image_processing_fuyu.py | {
"start": 2002,
"end": 2563
} | class ____(ImagesKwargs, total=False):
r"""
patch_size (`dict[str, int]`, *optional*, defaults to `{"height": 30, "width": 30}`):
Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
padding_value (`float`, *optional*, defaults to 1.0):
The value to pa... | FuyuImagesKwargs |
python | apache__airflow | providers/common/sql/src/airflow/providers/common/sql/operators/sql.py | {
"start": 42490,
"end": 46308
} | class ____(BaseSQLOperator):
"""
Performs a value check using sql code against a minimum threshold and a maximum threshold.
Thresholds can be in the form of a numeric value OR a sql statement that results a numeric.
:param sql: the sql to be executed. (templated)
:param conn_id: the connection ID ... | SQLThresholdCheckOperator |
python | mlflow__mlflow | tests/llama_index/sample_code/simple_workflow.py | {
"start": 208,
"end": 860
} | class ____(Workflow):
llm = OpenAI()
@step
async def generate_joke(self, ev: StartEvent) -> JokeEvent:
topic = ev.topic
prompt = f"Write your best joke about {topic}."
response = await self.llm.acomplete(prompt)
return JokeEvent(joke=str(response))
@step
async def c... | JokeFlow |
python | rushter__MLAlgorithms | mla/neuralnet/constraints.py | {
"start": 501,
"end": 584
} | class ____(object):
def clip(self, p):
return np.clip(p, -5, 5)
| SmallNorm |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 2670,
"end": 8557
} | class ____(AsyncFixture):
def test_requires_async_engine(self, async_engine):
testing.assert_raises_message(
exc.ArgumentError,
"AsyncEngine expected, got Engine",
AsyncSession,
bind=async_engine.sync_engine,
)
def test_info(self, async_session):
... | AsyncSessionTest |
python | pypa__setuptools | setuptools/_distutils/tests/test_install_data.py | {
"start": 220,
"end": 2464
} | class ____(
support.TempdirManager,
):
def test_simple_run(self):
pkg_dir, dist = self.create_dist()
cmd = install_data(dist)
cmd.install_dir = inst = os.path.join(pkg_dir, 'inst')
# data_files can contain
# - simple files
# - a Path object
# - a tuple... | TestInstallData |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_cleanup_pods.py | {
"start": 914,
"end": 2392
} | class ____:
"""Tests cleanup pods deployments."""
def test_should_have_a_schedule_with_defaults(self):
doc = render_chart(
values={
"cleanup": {"enabled": True},
},
show_only=["templates/cleanup/cleanup-cronjob.yaml"],
)[0]
assert doc... | TestCleanupDeployment |
python | ray-project__ray | python/ray/air/tests/test_integration_wandb.py | {
"start": 3397,
"end": 22405
} | class ____:
def test_wandb_logger_project_group(self, monkeypatch):
monkeypatch.setenv(WANDB_PROJECT_ENV_VAR, "test_project_from_env_var")
monkeypatch.setenv(WANDB_GROUP_ENV_VAR, "test_group_from_env_var")
# Read project and group name from environment variable
logger = WandbTestExpe... | TestWandbLogger |
python | getsentry__sentry | src/sentry/plugins/bases/notify.py | {
"start": 698,
"end": 7129
} | class ____(Plugin):
slug = ""
description = (
"Notify project members when a new event is seen for the first time, or when an "
"already resolved event has changed back to unresolved."
)
project_conf_form: type[forms.Form] = NotificationConfigurationForm
def get_plugin_type(self) ->... | NotificationPlugin |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/status.py | {
"start": 2125,
"end": 5094
} | class ____(StatusBarWidget):
"""Status bar widget for system vcs."""
ID = "vcs_status"
def __init__(self, parent):
super().__init__(parent)
self._worker_manager = WorkerManager(max_threads=1)
self._git_is_working = None
self._git_job_queue = None
self._last_git_job =... | VCSStatus |
python | mlflow__mlflow | tests/utils/test_async_artifacts_logging_queue.py | {
"start": 259,
"end": 6334
} | class ____:
def __init__(self, throw_exception_on_artifact_number=None):
if throw_exception_on_artifact_number is None:
throw_exception_on_artifact_number = []
self.received_run_id = ""
self.received_artifacts = []
self.received_filenames = []
self.received_artifa... | RunArtifacts |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_general_zipcode.py | {
"start": 984,
"end": 2062
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_general_zipcode"
condition_value_keys = ("country_code",)
# This method implements the core logic for the PandasExecutionEngine
@column_condition_par... | ColumnValuesToBeValidGeneralZipcode |
python | numba__numba | numba/core/annotations/pretty_annotate.py | {
"start": 7757,
"end": 9540
} | class ____:
"""
Construct syntax highlighted annotation for a given jitted function:
Example:
>>> import numba
>>> from numba.pretty_annotate import Annotate
>>> @numba.jit
... def test(q):
... res = 0
... for i in range(q):
... res += i
... return res
... | Annotate |
python | kamyu104__LeetCode-Solutions | Python/remove-one-element-to-make-the-array-strictly-increasing.py | {
"start": 29,
"end": 503
} | class ____(object):
def canBeIncreasing(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
deleted = False
for i in xrange(1, len(nums)):
if nums[i] > nums[i-1]:
continue
if deleted:
return False
... | Solution |
python | dask__dask | dask/dataframe/dask_expr/io/parquet.py | {
"start": 7862,
"end": 8471
} | class ____(Blockwise):
_parameters = ToParquet._parameters
@property
def io_func(self):
return ToParquetFunctionWrapper(
self.engine,
self.path,
self.fs,
self.partition_on,
self.write_metadata_file,
self.offset,
sel... | ToParquetData |
python | graphql-python__graphene | graphene/relay/tests/test_mutation.py | {
"start": 403,
"end": 647
} | class ____(ClientIDMutation):
class Input:
what = String()
phrase = String()
@staticmethod
def mutate_and_get_payload(self, info, what, client_mutation_id=None):
return SaySomething(phrase=str(what))
| SaySomething |
python | google__jax | jax/_src/errors.py | {
"start": 1394,
"end": 4724
} | class ____(JAXTypeError):
"""
This error occurs when a JAX Tracer object is used in a context where a
concrete value is required (see :ref:`faq-different-kinds-of-jax-values`
for more on what a Tracer is). In some situations, it can be easily fixed by
marking problematic values as static; in others, it may in... | ConcretizationTypeError |
python | django__django | tests/gis_tests/geo3d/models.py | {
"start": 638,
"end": 722
} | class ____(NamedModel):
line = models.LineStringField(srid=32140)
| InterstateProj2D |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/disconnected.py | {
"start": 282,
"end": 844
} | class ____(BlockSlackMessageBuilder):
def get_docs_block(self) -> SlackBlock:
return self.get_action_block(
[
(
"Sentry Docs",
"https://docs.sentry.io/product/alerts-notifications/alerts/",
"sentry_docs_link_clicked",
... | SlackDisconnectedMessageBuilder |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py | {
"start": 985,
"end": 1435
} | class ____(Visitor):
__slots__ = 'usages', 'type_info'
def __init__(self, usages, type_info):
self.usages = usages
self.type_info = type_info
def enter_VariableDefinition(self, node, key, parent, path, ancestors):
return False
def enter_Variable(self, node, key, parent, path, ... | UsageVisitor |
python | getsentry__sentry | src/sentry/core/endpoints/team_members.py | {
"start": 1408,
"end": 2538
} | class ____(Serializer):
def __init__(self, *args, **kwargs):
self.team = kwargs.pop("team", None)
super().__init__(*args, **kwargs)
def get_attrs(self, item_list, user, **kwargs):
prefetch_related_objects(item_list, "organizationmember")
org_member_set = serialize(
... | DetailedOrganizationMemberTeamSerializer |
python | pypa__warehouse | warehouse/cache/services.py | {
"start": 317,
"end": 1418
} | class ____:
"""
A Redis-based query results cache.
Anything using this service must assume that the key results may be empty,
and handle the case where the key is not found in the cache.
The key is a string, and the value is a JSON-serialized object as a string.
"""
def __init__(self, red... | RedisQueryResults |
python | openai__openai-python | src/openai/types/responses/tool_choice_function_param.py | {
"start": 223,
"end": 450
} | class ____(TypedDict, total=False):
name: Required[str]
"""The name of the function to call."""
type: Required[Literal["function"]]
"""For function calling, the type is always `function`."""
| ToolChoiceFunctionParam |
python | huggingface__transformers | src/transformers/integrations/tensor_parallel.py | {
"start": 19309,
"end": 20747
} | class ____:
"""
General tensor parallel layer for transformers.
"""
use_dtensor = True
device_mesh = None
rank = None
# Used to compare the shape of the original tensor
empty_param = None
# Used to init the corresponding DTensor
shard = None
def __init__(self, device_mesh... | TensorParallelLayer |
python | huggingface__transformers | src/transformers/models/ovis2/modular_ovis2.py | {
"start": 1797,
"end": 1870
} | class ____(LlavaNextModelOutputWithPast):
pass
| Ovis2ModelOutputWithPast |
python | airbytehq__airbyte | airbyte-ci/connectors/erd/src/erd/relationships.py | {
"start": 160,
"end": 364
} | class ____(TypedDict):
name: str
relations: dict[str, str]
false_positives: NotRequired[dict[str, str]]
Relationships = TypedDict("Relationships", {"streams": List[Relationship]})
| Relationship |
python | pytorch__pytorch | torch/_inductor/codegen/cpp.py | {
"start": 182582,
"end": 183985
} | class ____(CppKernel):
def __init__(self, kernel_group):
super().__init__(kernel_group.args, kernel_group.ws.num_threads)
self.inner: list[LoopNest] = []
def decide_parallel_depth(self, max_parallel_depth, threads):
kernels_parallel_depth = []
nested_kernels: list[CppKernel] = [... | OuterLoopFusedKernel |
python | sympy__sympy | sympy/printing/cxx.py | {
"start": 2850,
"end": 4211
} | class ____:
printmethod = "_cxxcode"
language = 'C++'
_ns = 'std::' # namespace
def __init__(self, settings=None):
super().__init__(settings or {})
@requires(headers={'algorithm'})
def _print_Max(self, expr):
from sympy.functions.elementary.miscellaneous import Max
if ... | _CXXCodePrinterBase |
python | Textualize__textual | tests/notifications/test_all_levels_notifications.py | {
"start": 215,
"end": 387
} | class ____(Screen):
def on_mount(self) -> None:
self.notify("test", timeout=60)
def compose(self) -> ComposeResult:
yield NotifyWidget()
| NotifyScreen |
python | pandas-dev__pandas | pandas/tests/io/parser/conftest.py | {
"start": 230,
"end": 2058
} | class ____:
engine: str | None = None
low_memory = True
float_precision_choices: list[str | None] = []
def update_kwargs(self, kwargs):
kwargs = kwargs.copy()
kwargs.update({"engine": self.engine, "low_memory": self.low_memory})
return kwargs
def read_csv(self, *args, **kw... | BaseParser |
python | python-visualization__folium | folium/elements.py | {
"start": 4520,
"end": 5025
} | class ____(MacroElement):
"""Generate an include statement on a class."""
_template = Template(
"""
{{ this.leaflet_class_name }}.include(
{{ this.options | tojavascript }}
)
"""
)
def __init__(self, leaflet_class_name: str, **kwargs):
super().__init__()... | IncludeStatement |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/image_processing_deepseek_vl_hybrid.py | {
"start": 1997,
"end": 3734
} | class ____(ImagesKwargs, total=False):
r"""
min_size (`int`, *optional*, defaults to 14):
The minimum allowed size for the resized image. Ensures that neither the height nor width
falls below this value after resizing.
high_res_size (`dict`, *optional*, defaults to `{"height": 1024, "width"... | DeepseekVLHybridImageProcessorKwargs |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_access.py | {
"start": 8045,
"end": 8563
} | class ____(OrganizationAccessMixin, TestCase):
"""Test organization paths with authed but non-org user."""
url_responses = {
"/organizations/": {"status_code": 200},
}
def assertResponse(self, path, method=None, data=None, **kwargs):
kwargs["status_code"] = 404
super().assertR... | OrganizationNonmemberAccess |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/smooth.py | {
"start": 1005,
"end": 1400
} | class ____(BaseOperator):
"""Operator that logs a YouTube link to Sade song "Smooth Operator"."""
ui_color = "#e8f7e4"
yt_link: str = "https://www.youtube.com/watch?v=4TYv2PhG89A"
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
def execute(self, context: Context):
... | SmoothOperator |
python | pytorch__pytorch | torch/distributed/_tools/mem_tracker.py | {
"start": 1252,
"end": 1397
} | class ____(str, Enum):
"""Base Class for defining memory reference types, categorizing tensors based on their usage within a model."""
| _RefType |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 57521,
"end": 58875
} | class ____(ExtensionType):
oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS
def __init__(
self,
signed_certificate_timestamps: Iterable[SignedCertificateTimestamp],
) -> None:
signed_certificate_timestamps = list(signed_certificate_timestamps)
if not all(
isinsta... | SignedCertificateTimestamps |
python | openai__openai-python | src/openai/resources/completions.py | {
"start": 58448,
"end": 58705
} | class ____:
def __init__(self, completions: AsyncCompletions) -> None:
self._completions = completions
self.create = _legacy_response.async_to_raw_response_wrapper(
completions.create,
)
| AsyncCompletionsWithRawResponse |
python | pypa__pip | src/pip/_internal/metadata/pkg_resources.py | {
"start": 2247,
"end": 8415
} | class ____(BaseDistribution):
def __init__(self, dist: pkg_resources.Distribution) -> None:
self._dist = dist
# This is populated lazily, to avoid loading metadata for all possible
# distributions eagerly.
self.__extra_mapping: Mapping[NormalizedName, str] | None = None
@propert... | Distribution |
python | pytorch__pytorch | torch/_dynamo/debug_utils.py | {
"start": 18253,
"end": 18852
} | class ____:
def __init__(self) -> None:
self.total = 0
def storage(
self,
storage_hash: Optional[str],
nbytes: int,
*,
device: Optional[torch._prims_common.DeviceLikeType] = None,
dtype_hint: Optional[torch.dtype] = None,
) -> None:
self.total... | NopInputReader |
python | readthedocs__readthedocs.org | readthedocs/api/v3/tests/test_remoteorganizations.py | {
"start": 313,
"end": 2133
} | class ____(APIEndpointMixin):
def setUp(self):
super().setUp()
self.remote_organization = fixture.get(
RemoteOrganization,
created=self.created,
modified=self.modified,
avatar_url="https://avatars.githubusercontent.com/u/366329?v=4",
name=... | RemoteOrganizationEndpointTests |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_workflow_details.py | {
"start": 1373,
"end": 4973
} | class ____(OrganizationWorkflowEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"PUT": ApiPublishStatus.EXPERIMENTAL,
"DELETE": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ALERTS_NOTIFICATIONS
@extend_schema(
operation_id="Fetch a Workflow",
... | OrganizationWorkflowDetailsEndpoint |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 6163,
"end": 6343
} | class ____(Message):
"""
Two or more starred expressions in an assignment (a, *b, *c = d).
"""
message = 'two starred expressions in assignment'
| TwoStarredExpressions |
python | neetcode-gh__leetcode | python/0235-lowest-common-ancestor-of-a-binary-search-tree.py | {
"start": 164,
"end": 535
} | class ____:
def lowestCommonAncestor(
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
) -> "TreeNode":
while True:
if root.val < p.val and root.val < q.val:
root = root.right
elif root.val > p.val and root.val > q.val:
root = root.left... | Solution |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/organization_code_mapping_codeowners.py | {
"start": 1389,
"end": 2679
} | class ____(OrganizationEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (OrganizationIntegrationsPermission,)
def convert_args(self, request: Request, organization_id_or_slug, config_id, *args, **kwargs):
args, kwargs = su... | OrganizationCodeMappingCodeOwnersEndpoint |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/update/tutorial002_py310.py | {
"start": 478,
"end": 2810
} | class ____(SQLModel):
name: str | None = None
secret_name: str | None = None
age: int | None = None
password: str | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, conne... | HeroUpdate |
python | lazyprogrammer__machine_learning_examples | rl3/a2c/subproc_vec_env.py | {
"start": 952,
"end": 1322
} | class ____():
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
"""
def __init__(self, x):
self.x = x
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x)
def __setstate__(self, ob):
import pickle
... | CloudpickleWrapper |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py | {
"start": 1054,
"end": 1201
} | class ____(graphene.ObjectType):
text = graphene.String()
class Meta:
name = "TextRuleEvaluationData"
| GrapheneTextRuleEvaluationData |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amplitude/components.py | {
"start": 1542,
"end": 2198
} | class ____(RecordExtractor):
"""
Create records from complex response structure
Issue: https://github.com/airbytehq/airbyte/issues/23145
"""
def extract_records(self, response: requests.Response) -> List[Record]:
response_data = response.json().get("data", [])
if response_data:
... | ActiveUsersRecordExtractor |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1145091,
"end": 1145604
} | class ____(ScaleInvalidDataShowAsstrokeDash):
"""
ScaleInvalidDataShowAsValuestrokeDash schema wrapper.
Parameters
----------
value : Sequence[float]
An array of alternating stroke, space lengths for creating dashed or dotted lines.
"""
_schema = {"$ref": '#/definitions/ScaleInvali... | ScaleInvalidDataShowAsValuestrokeDash |
python | getsentry__sentry | src/sentry/spans/buffer.py | {
"start": 6008,
"end": 23108
} | class ____:
def __init__(self, assigned_shards: list[int], slice_id: int | None = None):
self.assigned_shards = list(assigned_shards)
self.slice_id = slice_id
self.add_buffer_sha: str | None = None
self.any_shard_at_limit = False
self._current_compression_level = None
... | SpansBuffer |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flow_run_states.py | {
"start": 961,
"end": 1476
} | class ____:
async def test_read_flow_run_state(
self,
flow_run,
flow_run_states,
client,
session,
):
response = await client.get(
"/flow_run_states/", params=dict(flow_run_id=str(flow_run.id))
)
assert response.status_code == status.HTT... | TestReadFlowRunStateByFlowRunId |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/serialization/compute.py | {
"start": 1076,
"end": 4887
} | class ____:
asset_specs: Iterable[AssetSpec]
@cached_property
def mapped_task_asset_specs(self) -> list[AssetSpec]:
return [spec for spec in self.asset_specs if is_task_mapped_asset_spec(spec)]
@cached_property
def mapped_dag_asset_specs(self) -> list[AssetSpec]:
return [spec for s... | AirliftMetadataMappingInfo |
python | optuna__optuna | optuna/storages/journal/_file.py | {
"start": 5035,
"end": 8336
} | class ____(BaseJournalFileLock):
"""Lock class for synchronizing processes for NFSv2 or later.
On acquiring the lock, link system call is called to create an exclusive file. The file is
deleted when the lock is released. In NFS environments prior to NFSv3, use this instead of
:class:`~optuna.storages.j... | JournalFileSymlinkLock |
python | TheAlgorithms__Python | data_structures/queues/linked_queue.py | {
"start": 334,
"end": 3708
} | class ____:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> queue.put(5)
>>> queue.put(9)
>>> queue.put('python')
>>> queue.is_empty()
False
>>> queue.get()
5
>>> queue.put('algorithms')
>>> queue.get()
9
>>> queue.get()
'python'
>>> queue.... | LinkedQueue |
python | huggingface__transformers | src/transformers/models/deformable_detr/modeling_deformable_detr.py | {
"start": 44589,
"end": 51139
} | class ____(DeformableDetrPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
[`DeformableDetrEncoderLayer`].
The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
Args:
... | DeformableDetrEncoder |
python | getsentry__sentry | src/sentry/integrations/vsts/integration.py | {
"start": 29857,
"end": 30256
} | class ____(forms.Form):
def __init__(self, accounts: Sequence[Mapping[str, str]], *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.fields["account"] = forms.ChoiceField(
choices=[(acct["accountId"], acct["accountName"]) for acct in accounts],
label="... | AccountForm |
python | mwaskom__seaborn | seaborn/_base.py | {
"start": 2821,
"end": 10211
} | class ____(SemanticMapping):
"""Mapping that sets artist colors according to data values."""
# A specification of the colors that should appear in the plot
palette = None
# An object that normalizes data values to [0, 1] range for color mapping
norm = None
# A continuous colormap object for in... | HueMapping |
python | spyder-ide__spyder | spyder/utils/svg_colorizer.py | {
"start": 399,
"end": 11717
} | class ____:
"""
A class for modifying SVG files by changing the fill colors of elements
with specific class attributes.
This implementation uses lxml for XML parsing and XPath for element
selection, providing a reliable and maintainable way to manipulate SVG
files.
The main purpose of this... | SVGColorize |
python | anthropics__anthropic-sdk-python | src/anthropic/types/message_delta_usage.py | {
"start": 230,
"end": 816
} | class ____(BaseModel):
cache_creation_input_tokens: Optional[int] = None
"""The cumulative number of input tokens used to create the cache entry."""
cache_read_input_tokens: Optional[int] = None
"""The cumulative number of input tokens read from the cache."""
input_tokens: Optional[int] = None
... | MessageDeltaUsage |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 63295,
"end": 66868
} | class ____:
def test_send_new_organization_moreinformationneeded_email(
self, pyramid_request, pyramid_config, monkeypatch
):
initiator_user = pretend.stub(
id="id",
username="username",
name="",
email="email@example.com",
primary_email... | TestSendNewOrganizationRequestMoreInfoEmail |
python | streamlit__streamlit | lib/streamlit/config.py | {
"start": 2811,
"end": 3558
} | class ____(str, Enum):
"""Valid options for the "client.showErrorDetails" config."""
FULL = "full"
STACKTRACE = "stacktrace"
TYPE = "type"
NONE = "none"
@staticmethod
def is_true_variation(val: str | bool) -> bool:
return val in ["true", "True", True]
@staticmethod
def is_... | ShowErrorDetailsConfigOptions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gcs/source_gcs/config.py | {
"start": 1626,
"end": 2831
} | class ____(AbstractFileBasedSpec, BaseModel):
"""
NOTE: When this Spec is changed, legacy_config_transformer.py must also be
modified to uptake the changes because it is responsible for converting
legacy GCS configs into file based configs using the File-Based CDK.
"""
credentials: Union[OAuthC... | Config |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride4.py | {
"start": 349,
"end": 561
} | class ____(Generic[_TSource]):
@abstractmethod
def method1(
self, mapper: Callable[[_TSource, _T1], _TResult], other: "BaseA[_T1]"
) -> "BaseA[_TResult]":
raise NotImplementedError
| BaseA |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/models/steps.py | {
"start": 923,
"end": 1645
} | class ____:
path: Union[Path, str]
optional: bool = False
def _cast_fields(self) -> None:
self.path = Path(self.path)
self.optional = bool(self.optional)
def _check_exists(self) -> None:
if not self.get_path().exists():
message = f"{self.path} does not exist."
... | MountPath |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 127146,
"end": 128363
} | class ____(Request):
"""
Get single value metrics for the passed tasks
:param tasks: List of task Task IDs
:type tasks: Sequence[str]
"""
_service = "events"
_action = "get_task_single_value_metrics"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
... | GetTaskSingleValueMetricsRequest |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 69055,
"end": 69717
} | class ____(FieldValues):
"""
Valid and invalid values for a `Choice` field that uses a single paired or
grouped.
"""
valid_inputs = {
'poor': 'poor',
'medium': 'medium',
'good': 'good',
}
invalid_inputs = {
'awful': ['"awful" is not a valid choice.']
}
... | TestChoiceFieldWithMixedChoices |
python | scikit-learn__scikit-learn | sklearn/tests/test_common.py | {
"start": 2141,
"end": 13101
} | class ____(BaseEstimator):
"""Dummy development stub for an estimator.
This is to make sure a callable estimator passes common tests.
"""
def __call__(self):
pass # pragma: nocover
@pytest.mark.parametrize(
"val, expected",
[
(partial(_sample_func, y=1), "_sample_func(y=1)")... | CallableEstimator |
python | bottlepy__bottle | test/test_multipart.py | {
"start": 37595,
"end": 38333
} | class ____(BaseMultipartTest):
def test_werkzeug_examples(self):
"""Tests multipart parsing against data collected from webbrowsers"""
for name in browser_test_cases:
self.reset()
self.data = BytesIO(browser_test_cases[name]['data'])
boundary = browser_test_cases[... | TestWerkzeugExamples |
python | rapidsai__cudf | python/cudf/cudf/core/udf/masked_typing.py | {
"start": 11079,
"end": 12159
} | class ____(AbstractTemplate):
def generic(self, args, kws):
"""
Typing for `Masked` <op> a scalar (and vice-versa).
handles situations like `x + 1`
"""
# In the case of op(Masked, scalar), we resolve the type between
# the Masked value_type and the scalar's type direc... | MaskedScalarScalarOp |
python | celery__celery | t/unit/fixups/test_django.py | {
"start": 643,
"end": 5671
} | class ____(FixupCase):
Fixup = DjangoFixup
def test_setting_default_app(self):
from celery import _state
prev, _state.default_app = _state.default_app, None
try:
app = Mock(name='app')
DjangoFixup(app)
app.set_default.assert_called_with()
fina... | test_DjangoFixup |
python | gevent__gevent | src/gevent/select.py | {
"start": 7332,
"end": 7973
} | class ____(object):
__slots__ = ('events', 'event')
def __init__(self):
self.events = set()
self.event = Event()
def add_event(self, events, fd):
if events < 0:
result_flags = POLLNVAL
else:
result_flags = 0
if events & _EV_READ:
... | PollResult |
python | pytorch__pytorch | torch/testing/_internal/common_dtype.py | {
"start": 412,
"end": 5106
} | class ____(tuple):
__slots__ = ()
def __add__(self, other):
assert isinstance(other, tuple)
return _dispatch_dtypes(tuple.__add__(self, other))
_empty_types = _dispatch_dtypes(())
def empty_types():
return _empty_types
_floating_types = _dispatch_dtypes((torch.float32, torch.float64))... | _dispatch_dtypes |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-intercom/components.py | {
"start": 10334,
"end": 14355
} | class ____(SimpleRetriever):
"""
Custom retriever for Intercom's companies stream with reset handling. Only compatible with streams that sync using
a single date time window instead of multiple windows when the step is defined. This is okay for the companies stream
since it only allows for single-thread... | IntercomScrollRetriever |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_compiler.py | {
"start": 65279,
"end": 69586
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "oracle"
def setup_test(self):
self.table = table(
"mytable", column("myid", String), column("name", String)
)
def test_regexp_match(self):
self.assert_compile(
self.table.c.myid.regexp... | RegexpTest |
python | pypa__warehouse | warehouse/cli/db/dbml.py | {
"start": 1696,
"end": 1873
} | class ____(TypedDict):
type: NotRequired[Literal["1-1", "1-n", "n-n"]]
table_from: str
table_from_field: str
table_to: str
table_to_field: str
| RelationshipInfo |
python | sympy__sympy | sympy/physics/mechanics/joint.py | {
"start": 53058,
"end": 67550
} | class ____(Joint):
"""Planar Joint.
.. raw:: html
:file: ../../../doc/src/modules/physics/mechanics/api/PlanarJoint.svg
Explanation
===========
A planar joint is defined such that the child body translates over a fixed
plane of the parent body as well as rotate about the rotation axis... | PlanarJoint |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0018_fix-translation-model.py | {
"start": 133,
"end": 674
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0017_add_domain_https"),
]
operations = [
migrations.AlterField(
model_name="project",
name="main_language_project",
field=models.ForeignKey(
r... | Migration |
python | kamyu104__LeetCode-Solutions | Python/plus-one.py | {
"start": 29,
"end": 453
} | class ____(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in reversed(xrange(len(digits))):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
return digits... | Solution |
python | dask__dask | dask/dataframe/dask_expr/io/io.py | {
"start": 959,
"end": 1059
} | class ____(Expr):
def __str__(self):
return f"{type(self).__name__}({self._name[-7:]})"
| IO |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 2861,
"end": 3290
} | class ____(Benchmark):
param_names = ['alternative']
params = [
['two-sided', 'less', 'greater']
]
def setup(self, alternative):
rng = np.random.default_rng(0xb6acd7192d6e5da0f68b5d8ab8ce7af2)
self.u1 = rng.uniform(-1, 1, 200)
self.u2 = rng.uniform(-0.5, 1.5, 300)
d... | RankSums |
python | ray-project__ray | rllib/env/tests/test_multi_agent_env.py | {
"start": 7919,
"end": 11106
} | class ____(MultiAgentEnv):
"""Multi-agent env in which sometimes, no agent acts.
At each timestep, we determine, which agents emit observations (and thereby request
actions). This set of observing (and action-requesting) agents could be anything
from the empty set to the full set of all agents.
Fo... | SometimesZeroAgentsMultiAgent |
python | viewflow__viewflow | viewflow/fsm/admin.py | {
"start": 873,
"end": 7886
} | class ____(object):
"""
A Mixin for providing Finite State Machine (FSM) management support in
Django admin.
"""
flow_state: State
change_list_template = "admin/fsm_change_list.html"
change_form_template = "admin/fsm_change_form.html"
transition_form_template = None
def get_flow... | FlowAdminMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.