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 | walkccc__LeetCode | solutions/1452. People Whose List of Favorite Companies Is Not a Subset of Another List/1452.py | {
"start": 0,
"end": 443
} | class ____:
def peopleIndexes(self, favoriteCompanies: list[list[str]]) -> list[int]:
ans = []
n = len(favoriteCompanies)
companies = [set(comp) for comp in favoriteCompanies]
for i in range(n):
find = False
for j in range(n):
if i == j:
continue
if companies[i].... | Solution |
python | python-excel__xlrd | xlrd/biffh.py | {
"start": 301,
"end": 417
} | class ____(Exception):
"""
An exception indicating problems reading data from an Excel file.
"""
| XLRDError |
python | lepture__authlib | authlib/integrations/starlette_client/apps.py | {
"start": 2380,
"end": 4140
} | class ____(
StarletteAppMixin, AsyncOAuth2Mixin, AsyncOpenIDMixin, BaseApp
):
client_cls = AsyncOAuth2Client
async def authorize_access_token(self, request, **kwargs):
if request.scope.get("method", "GET") == "GET":
error = request.query_params.get("error")
if error:
... | StarletteOAuth2App |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 930105,
"end": 930543
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of RemoveUpvote"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "subject")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation.... | RemoveUpvotePayload |
python | neetcode-gh__leetcode | python/0212-word-search-ii.py | {
"start": 0,
"end": 581
} | class ____:
def __init__(self):
self.children = {}
self.isWord = False
self.refs = 0
def addWord(self, word):
cur = self
cur.refs += 1
for c in word:
if c not in cur.children:
cur.children[c] = TrieNode()
cur = cur.children... | TrieNode |
python | pytorch__pytorch | torch/_inductor/runtime/static_cuda_launcher.py | {
"start": 209,
"end": 10928
} | class ____:
"""
Parses the metadata of a CompiledKernel from Triton into a structure that can
launch the cuda kernel directly. Only works for triton kernels compiled to cubin.
Doing this avoids C++ codegen and compilation during compile, since we can use a
statically compiled library to launch the ... | StaticallyLaunchedCudaKernel |
python | Netflix__metaflow | metaflow/_vendor/importlib_metadata/__init__.py | {
"start": 8018,
"end": 9704
} | class ____(DeprecatedList):
"""
An immutable collection of selectable EntryPoint objects.
"""
__slots__ = ()
def __getitem__(self, name): # -> EntryPoint:
"""
Get the EntryPoint in self matching name.
"""
if isinstance(name, int):
warnings.warn(
... | EntryPoints |
python | django__django | tests/template_tests/test_library.py | {
"start": 133,
"end": 1311
} | class ____(SimpleTestCase):
def setUp(self):
self.library = Library()
def test_filter(self):
@self.library.filter
def func():
return ""
self.assertEqual(self.library.filters["func"], func)
def test_filter_parens(self):
@self.library.filter()
def... | FilterRegistrationTests |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 3089,
"end": 3309
} | class ____(TypedDict):
currentCrashFreeRate: float | None
previousCrashFreeRate: float | None
CurrentAndPreviousCrashFreeRates = Mapping[ProjectId, CurrentAndPreviousCrashFreeRate]
| CurrentAndPreviousCrashFreeRate |
python | pytorch__pytorch | benchmarks/instruction_counts/execution/work.py | {
"start": 1416,
"end": 5088
} | class ____:
"""Wraps subprocess.Popen for a given WorkOrder."""
_work_order: WorkOrder
_cpu_list: Optional[str]
_proc: PopenType
# Internal bookkeeping
_communication_file: str
_start_time: float
_end_time: Optional[float] = None
_retcode: Optional[int]
_result: Optional[Union[... | _BenchmarkProcess |
python | coleifer__peewee | tests/models.py | {
"start": 128059,
"end": 128585
} | class ____(BaseTestCase):
def test_set_database(self):
class Register(Model):
value = IntegerField()
db_a = get_in_memory_db()
db_b = get_in_memory_db()
Register._meta.set_database(db_a)
Register.create_table()
Register._meta.set_database(db_b)
se... | TestModelSetDatabase |
python | astropy__astropy | astropy/units/tests/test_quantity_info.py | {
"start": 3768,
"end": 5092
} | class ____:
"""Regression test for gh-14514: _new_view should __array_finalize__.
But info should be propagated only for slicing, etc.
"""
@classmethod
def setup_class(cls):
class MyQuantity(u.Quantity):
def __array_finalize__(self, obj):
super().__array_finaliz... | TestQuantitySubclass |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 30730,
"end": 32944
} | class ____(_TestParametrizer):
"""
Decorator for adjusting the way an existing parametrizer operates. This class runs
the given adapter_fn on each parametrization produced by the given parametrizer,
allowing for on-the-fly parametrization more flexible than the default,
product-based composition tha... | reparametrize |
python | django__django | tests/backends/test_utils.py | {
"start": 3717,
"end": 5559
} | class ____(TransactionTestCase):
available_apps = []
def _test_procedure(self, procedure_sql, params, param_types, kparams=None):
with connection.cursor() as cursor:
cursor.execute(procedure_sql)
# Use a new cursor because in MySQL a procedure can't be used in the
# same cur... | CursorWrapperTests |
python | pytorch__pytorch | torch/ao/pruning/_experimental/pruner/saliency_pruner.py | {
"start": 94,
"end": 1536
} | class ____(BaseStructuredSparsifier):
"""
Prune rows based on the saliency (L1 norm) of each row.
This pruner works on N-Dimensional weight tensors.
For each row, we will calculate the saliency, which is the sum the L1 norm of all weights in that row.
We expect that the resulting saliency vector ha... | SaliencyPruner |
python | jina-ai__jina | tests/unit/serve/runtimes/gateway/http/test_app.py | {
"start": 482,
"end": 12374
} | class ____(Executor):
@requests
def empty(self, docs: DocumentArray, **kwargs):
print(f"# docs {docs}")
@pytest.fixture
def error_log_level():
old_env = os.environ.get('JINA_LOG_LEVEL')
os.environ['JINA_LOG_LEVEL'] = 'ERROR'
yield
os.environ['JINA_LOG_LEVEL'] = old_env
def test_tag_u... | ExecutorTest |
python | weaviate__weaviate-python-client | profiling/test_refs.py | {
"start": 1771,
"end": 2205
} | class ____:
contents: str
author: Reference
hasParagraphs: Optional[Reference]
uuid: uuid_lib.UUID = field(init=False)
class_name: str = field(init=False)
def to_data_object(self) -> DataObject:
return DataObject({"contents": self.contents}, self.class_name, self.uuid)
def __post_i... | Paragraph |
python | getsentry__sentry | src/sentry/integrations/middleware/hybrid_cloud/parser.py | {
"start": 2052,
"end": 2263
} | class ____:
def __init__(
self,
response: HttpResponseBase | None = None,
error: Exception | None = None,
):
self.response = response
self.error = error
| RegionResult |
python | kubernetes-client__python | kubernetes/base/dynamic/exceptions.py | {
"start": 3507,
"end": 3591
} | class ____(DynamicApiError):
""" 429: StatusTooManyRequests """
| TooManyRequestsError |
python | weaviate__weaviate-python-client | weaviate/collections/batch/collection.py | {
"start": 2418,
"end": 6018
} | class ____(Generic[Properties], _BatchBaseNew):
def __init__(
self,
executor: ThreadPoolExecutor,
connection: ConnectionSync,
consistency_level: Optional[ConsistencyLevel],
results: _BatchDataWrapper,
batch_mode: _BatchMode,
name: str,
tenant: Optional... | _BatchCollectionNew |
python | kubernetes-client__python | kubernetes/client/models/v1_endpoints_list.py | {
"start": 383,
"end": 6848
} | 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... | V1EndpointsList |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 242382,
"end": 243616
} | class ____(Response):
"""
Response of tasks.get_configuration_names endpoint.
:param configurations: Names of task configuration items (keyed by task ID)
:type configurations: dict
"""
_service = "tasks"
_action = "get_configuration_names"
_version = "2.9"
_schema = {
"defi... | GetConfigurationNamesResponse |
python | jina-ai__jina | jina/proto/serializer.py | {
"start": 4210,
"end": 4735
} | class ____:
"""Placeholder that delegates the serialization and deserialization to the internal protobuf"""
@staticmethod
def SerializeToString(x):
"""
# noqa: DAR101
# noqa: DAR102
# noqa: DAR201
"""
return x.SerializeToString()
@staticmethod
def Fr... | SnapshotId |
python | huggingface__transformers | src/transformers/models/layoutlmv2/image_processing_layoutlmv2.py | {
"start": 1561,
"end": 4569
} | class ____(ImagesKwargs, total=False):
r"""
apply_ocr (`bool`, *optional*, defaults to `True`):
Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by
the `apply_ocr` parameter in the `preprocess` method.
ocr_lang (`str`, *optional*):
... | LayoutLMv2ImageProcessorKwargs |
python | huggingface__transformers | src/transformers/models/gemma3/modeling_gemma3.py | {
"start": 59069,
"end": 59694
} | class ____(GenericForSequenceClassification, Gemma3PreTrainedModel):
"""
Gemma3TextForSequenceClassification is a text-only sequence classification model that works with Gemma3TextConfig.
It uses the generic sequence classification implementation for efficiency and consistency.
"""
config: Gemma3Te... | Gemma3TextForSequenceClassification |
python | pypa__pipenv | pipenv/vendor/colorama/winterm.py | {
"start": 247,
"end": 416
} | class ____(object):
BLACK = 0
BLUE = 1
GREEN = 2
CYAN = 3
RED = 4
MAGENTA = 5
YELLOW = 6
GREY = 7
# from wincon.h
| WinColor |
python | wandb__wandb | tests/unit_tests/test_file_stream.py | {
"start": 244,
"end": 6495
} | class ____:
data: str = None
def test_split_files():
def choices(pop, k=1):
# Note: random.choices was added in python 3.6
return [random.choice(pop) for _ in range(k)]
def rand_string_list(size):
width = max(1, int(size / 10))
num_lines = int(size / width)
return ... | Chunk |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 483736,
"end": 484454
} | class ____(VegaLiteSchema):
"""
ImputeSequence schema wrapper.
Parameters
----------
stop : float
The ending value(exclusive) of the sequence.
start : float
The starting value of the sequence. **Default value:** ``0``
step : float
The step value between sequence entr... | ImputeSequence |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 5660,
"end": 5802
} | class ____:
updated: list[MonitorSerializerResponse]
errored: list[MonitorSerializerResponse]
@register(Monitor)
| MonitorBulkEditResponse |
python | pytorch__pytorch | torch/_inductor/compile_worker/subproc_pool.py | {
"start": 3463,
"end": 3528
} | class ____(Enum):
FORK = "fork"
SPAWN = "spawn"
| SubprocKind |
python | ZoranPandovski__al-go-rithms | data_structures/Linked_list/Python/Singly_linked_list.py | {
"start": 115,
"end": 2277
} | class ____:
def __init__(self):
self.head = None #creating a header
#inserting a new node at the beginning
def push(self, new_data):
new_node = node(new_data)
new_node.next = self.head
self.head = new_node
#inserting a new node after a node
def pu... | linkedlist |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_bundle.py | {
"start": 9051,
"end": 10048
} | class ____:
def test_without_widgets(self) -> None:
assert beb._use_widgets(beb._all_objs([plot()])) is False
assert beb._use_widgets(beb._all_objs([plot(), glplot()])) is False
d = Document()
d.add_root(plot())
d.add_root(glplot())
assert beb._use_widgets(beb._all_ob... | Test__use_widgets |
python | ray-project__ray | python/ray/tune/tests/execution/test_controller_search_alg_integration.py | {
"start": 728,
"end": 12264
} | class ____(TuneController):
def __init__(self, *args, **kwargs):
kwargs.update(dict(storage=mock_storage_context()))
super().__init__(*args, **kwargs)
@pytest.fixture(autouse=True)
def register_test_trainable():
register_mock_trainable()
yield
@pytest.fixture(scope="function")
def ray_st... | TestTuneController |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/data_factory.py | {
"start": 4218,
"end": 5080
} | class ____(AirflowException):
"""An exception that indicates a pipeline run failed to complete."""
def get_field(extras: dict, field_name: str, strict: bool = False):
"""Get field from extra, first checking short name, then for backcompat we check for prefixed name."""
backcompat_prefix = "extra__azure_da... | AzureDataFactoryPipelineRunException |
python | django__django | django/contrib/gis/gdal/field.py | {
"start": 4129,
"end": 4552
} | class ____(Field):
_bit64 = False
@property
def value(self):
"Return an integer contained in this field."
return self.as_int(self._bit64)
@property
def type(self):
"""
GDAL uses OFTReals to represent OFTIntegers in created
shapefiles -- forcing the type here... | OFTInteger |
python | huggingface__transformers | src/transformers/models/colqwen2/modular_colqwen2.py | {
"start": 1674,
"end": 11845
} | class ____(ColPaliProcessor):
r"""
Constructs a ColQwen2 processor which wraps a Qwen2VLProcessor and special methods to process images and queries, as
well as to compute the late-interaction retrieval score.
[`ColQwen2Processor`] offers all the functionalities of [`Qwen2VLProcessor`]. See the [`~Qwen2... | ColQwen2Processor |
python | django-import-export__django-import-export | tests/core/tests/test_declarative.py | {
"start": 1305,
"end": 3706
} | class ____(TestCase):
def test_meta_inheritance_3_levels(self):
# issue 1363
class GrandparentResource(Resource):
class Meta:
batch_size = 666
class ParentResource(GrandparentResource):
class Meta:
pass
class ChildResource(Par... | TestMultiInheritance |
python | faif__python-patterns | patterns/creational/factory.py | {
"start": 1092,
"end": 1397
} | class ____:
"""A simple localizer a la gettext"""
def __init__(self) -> None:
self.translations = {"dog": "σκύλος", "cat": "γάτα"}
def localize(self, msg: str) -> str:
"""We'll punt if we don't have a translation"""
return self.translations.get(msg, msg)
| GreekLocalizer |
python | ansible__ansible | test/lib/ansible_test/_internal/connections.py | {
"start": 608,
"end": 2201
} | class ____(metaclass=abc.ABCMeta):
"""Base class for connecting to a host."""
@abc.abstractmethod
def run(
self,
command: list[str],
capture: bool,
interactive: bool = False,
data: t.Optional[str] = None,
stdin: t.Optional[t.IO[bytes]] = None,
stdout:... | Connection |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/FeedbackButton.py | {
"start": 66,
"end": 5914
} | class ____(QtWidgets.QPushButton):
"""
QPushButton which flashes success/failure indication for slow or asynchronous procedures.
"""
### For thread-safetyness
sigCallSuccess = QtCore.Signal(object, object, object)
sigCallFailure = QtCore.Signal(object, object, object)
sigCallProces... | FeedbackButton |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/ops.py | {
"start": 127,
"end": 360
} | class ____:
def get(self, _url):
return MockResponse()
requests = MockRequest()
# start_op_marker
@dg.op
def my_op():
return "hello"
# end_op_marker
# start_configured_op_marker
import dagster as dg
| MockRequest |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 56639,
"end": 59428
} | class ____(unittest.TestCase):
def check_interrupt_main_with_signal_handler(self, signum):
def handler(signum, frame):
1/0
old_handler = signal.signal(signum, handler)
self.addCleanup(signal.signal, signum, old_handler)
with self.assertRaises(ZeroDivisionError):
... | InterruptMainTests |
python | walkccc__LeetCode | solutions/3074. Apple Redistribution into Boxes/3074.py | {
"start": 0,
"end": 298
} | class ____:
def minimumBoxes(self, apple: list[int], capacity: list[int]) -> int:
appleSum = sum(apple)
capacitySum = 0
for i, c in enumerate(sorted(capacity, reverse=True)):
capacitySum += c
if capacitySum >= appleSum:
return i + 1
return len(capacity)
| Solution |
python | python-openxml__python-docx | tests/test_settings.py | {
"start": 219,
"end": 1633
} | class ____:
"""Unit-test suite for the `docx.settings.Settings` objects."""
@pytest.mark.parametrize(
("cxml", "expected_value"),
[
("w:settings", False),
("w:settings/w:evenAndOddHeaders", True),
("w:settings/w:evenAndOddHeaders{w:val=0}", False),
... | DescribeSettings |
python | kamyu104__LeetCode-Solutions | Python/design-memory-allocator.py | {
"start": 167,
"end": 1575
} | class ____(object):
def __init__(self, n):
"""
:type n: int
"""
self.__avails = SortedList([[0, n]])
self.__lookup = collections.defaultdict(list)
def allocate(self, size, mID):
"""
:type size: int
:type mID: int
:rtype: int
"""
... | Allocator |
python | google__jax | docs/autodidax.py | {
"start": 35691,
"end": 35906
} | class ____(Tracer):
__slots__ = ['aval']
aval: ShapedArray
def __init__(self, trace, aval):
self._trace = trace
self.aval = aval
# NB: the analogous class in JAX is called 'DynamicJaxprTrace'
| JaxprTracer |
python | numba__llvmlite | llvmlite/binding/targets.py | {
"start": 9712,
"end": 15369
} | class ____(ffi.ObjectRef):
def _dispose(self):
self._capi.LLVMPY_DisposeTargetMachine(self)
def add_analysis_passes(self, pm):
"""
Register analysis passes for this target machine with a pass manager.
"""
ffi.lib.LLVMPY_AddAnalysisPasses(self, pm)
def set_asm_verbo... | TargetMachine |
python | google__pytype | pytype/typegraph/cfg_test.py | {
"start": 101,
"end": 33301
} | class ____(unittest.TestCase):
"""Test control flow graph creation."""
def test_simple_graph(self):
p = cfg.Program()
n1 = p.NewCFGNode("foo")
n2 = n1.ConnectNew("n2")
n3 = n1.ConnectNew("n3")
n4 = n3.ConnectNew("n4")
self.assertEqual(0, n1.id)
self.assertEqual("foo", n1.name)
self.... | CFGTest |
python | pallets__jinja | src/jinja2/compiler.py | {
"start": 7665,
"end": 8217
} | class ____(NodeVisitor):
"""A visitor that collects filter and test calls."""
def __init__(self) -> None:
self.filters: set[str] = set()
self.tests: set[str] = set()
def visit_Filter(self, node: nodes.Filter) -> None:
self.generic_visit(node)
self.filters.add(node.name)
... | DependencyFinderVisitor |
python | sympy__sympy | sympy/plotting/pygletplot/plot_controller.py | {
"start": 168,
"end": 6941
} | class ____:
normal_mouse_sensitivity = 4.0
modified_mouse_sensitivity = 1.0
normal_key_sensitivity = 160.0
modified_key_sensitivity = 40.0
keymap = {
key.LEFT: 'left',
key.A: 'left',
key.NUM_4: 'left',
key.RIGHT: 'right',
key.D: 'right',
key.NUM_6:... | PlotController |
python | altair-viz__altair | altair/vegalite/v6/schema/mixins.py | {
"start": 42104,
"end": 50021
} | class ____(SchemaBase):
"""
BoxPlotDef schema wrapper.
Parameters
----------
box : bool, dict, :class:`BarConfig`, :class:`AreaConfig`, :class:`LineConfig`, :class:`MarkConfig`, :class:`RectConfig`, :class:`TickConfig`, :class:`AnyMarkConfig`
clip : bool
Whether a composite mark be cli... | _BoxPlotDef |
python | streamlit__streamlit | lib/streamlit/runtime/state/common.py | {
"start": 5527,
"end": 7760
} | class ____(Generic[T_co]):
"""Result returned by the `register_widget` family of functions/methods.
Should be usable by widget code to determine what value to return, and
whether to update the UI.
Parameters
----------
value : T_co
The widget's current value, or, in cases where the tru... | RegisterWidgetResult |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-typesense/destination_typesense/destination.py | {
"start": 1023,
"end": 3304
} | class ____(Destination):
def write(
self,
config: Mapping[str, Any],
configured_catalog: ConfiguredAirbyteCatalog,
input_messages: Iterable[AirbyteMessage],
) -> Iterable[AirbyteMessage]:
client = get_client(config=config)
for configured_stream in configured_cata... | DestinationTypesense |
python | modin-project__modin | modin/tests/pandas/extensions/conftest.py | {
"start": 1423,
"end": 2211
} | class ____(BaseFactory):
@classmethod
def prepare(cls):
cls.io_cls = Test1IO
@pytest.fixture
def Backend1():
factories.Test1_Storage_FormatOnTest1_EngineFactory = Test1Factory
if "Backend1" not in Backend.choices:
StorageFormat.add_option("Test1_storage_format")
Engine.add_opt... | Test1Factory |
python | pytorch__pytorch | benchmarks/dynamo/dist_util.py | {
"start": 1170,
"end": 1412
} | class ____(torch.nn.Module):
def __init__(self, a, b):
super().__init__()
self.net = nn.Sequential(
nn.Linear(a, b),
nn.ReLU(),
)
def forward(self, x):
return self.net(x)
| MyModule |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 7410,
"end": 7594
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ENABLED", "NO_POLICY")
| EnterpriseEnabledSettingValue |
python | django__django | tests/utils_tests/test_duration.py | {
"start": 2522,
"end": 3405
} | class ____(unittest.TestCase):
def test_simple(self):
duration = datetime.timedelta(hours=1, minutes=3, seconds=5)
self.assertEqual(parse_duration(duration_iso_string(duration)), duration)
def test_days(self):
duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
... | TestParseISODurationRoundtrip |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py | {
"start": 3998,
"end": 4034
} | class ____(TypedDict):
d1: int
| TD1 |
python | getsentry__sentry | tests/sentry/utils/test_committers.py | {
"start": 816,
"end": 1857
} | class ____(TestCase):
def setUp(self) -> None:
self.repo = Repository.objects.create(
organization_id=self.organization.id, name=self.organization.id
)
def create_commit_author(self, name=None, email=None):
return CommitAuthor.objects.create(
organization_id=self... | CommitTestCase |
python | openai__openai-python | src/openai/types/responses/response_function_web_search_param.py | {
"start": 1000,
"end": 1346
} | class ____(TypedDict, total=False):
pattern: Required[str]
"""The pattern or text to search for within the page."""
type: Required[Literal["find"]]
"""The action type."""
url: Required[str]
"""The URL of the page searched for the pattern."""
Action: TypeAlias = Union[ActionSearch, ActionOpen... | ActionFind |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 376165,
"end": 376778
} | class ____(VegaLiteSchema):
"""
FacetMapping schema wrapper.
Parameters
----------
column : dict, :class:`FacetFieldDef`
A field definition for the horizontal facet of trellis plots.
row : dict, :class:`FacetFieldDef`
A field definition for the vertical facet of trellis plots.
... | FacetMapping |
python | huggingface__transformers | src/transformers/models/x_clip/modeling_x_clip.py | {
"start": 32817,
"end": 36845
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`XCLIPVisionEncoderLayer`].
Args:
config: XCLIPConfig
"""
def __init__(self, config: XCLIPConfig):
super().__init__()
self.config = config
... | XCLIPVisionEncoder |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py | {
"start": 10800,
"end": 12502
} | class ____(test.TestCase):
# Check the gradients.
def _checkGrad(self, x, block_shape, crops, crops_dtype):
block_shape = np.array(block_shape)
crops = constant_op.constant(
np.array(crops).reshape((len(block_shape), 2)), crops_dtype)
with self.cached_session():
tf_x = ops.convert_to_tens... | BatchToSpaceNDGradientTest |
python | openai__openai-python | src/openai/types/evals/runs/output_item_list_response.py | {
"start": 2165,
"end": 2937
} | class ____(BaseModel):
error: EvalAPIError
"""An object representing an error response from the Eval API."""
finish_reason: str
"""The reason why the sample generation was finished."""
input: List[SampleInput]
"""An array of input messages."""
max_completion_tokens: int
"""The maximum... | Sample |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass11.py | {
"start": 326,
"end": 386
} | class ____(A):
pass
# This should generate an error.
B()
| B |
python | doocs__leetcode | solution/0200-0299/0217.Contains Duplicate/Solution.py | {
"start": 0,
"end": 136
} | class ____:
def containsDuplicate(self, nums: List[int]) -> bool:
return any(a == b for a, b in pairwise(sorted(nums)))
| Solution |
python | readthedocs__readthedocs.org | readthedocs/gold/tests/test_views.py | {
"start": 219,
"end": 1110
} | class ____(PaymentMixin, TestCase):
def setUp(self):
super().setUp()
self.user = get(User)
def test_csp_headers(self):
"""
Test CSP headers aren't altered.
This view originally altered the CSP directives based on whether we were
using the new dashboard. We weren... | TestViews |
python | scikit-learn__scikit-learn | sklearn/model_selection/_plot.py | {
"start": 4163,
"end": 19725
} | class ____(_BaseCurveDisplay):
"""Learning Curve visualization.
It is recommended to use
:meth:`~sklearn.model_selection.LearningCurveDisplay.from_estimator` to
create a :class:`~sklearn.model_selection.LearningCurveDisplay` instance.
All parameters are stored as attributes.
Read more in the :... | LearningCurveDisplay |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/ext/association_proxy/association_proxy_two.py | {
"start": 570,
"end": 1022
} | class ____(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64))
kw: Mapped[list[Keyword]] = relationship(
secondary=lambda: user_keyword_table
)
def __init__(self, name: str):
self.name = name
# proxy ... | User |
python | sympy__sympy | sympy/stats/symbolic_multivariate_probability.py | {
"start": 3799,
"end": 6730
} | class ____(Variance, MatrixExpr):
"""
Variance of a random matrix probability expression. Also known as
Covariance matrix, auto-covariance matrix, dispersion matrix,
or variance-covariance matrix.
Examples
========
>>> from sympy.stats import VarianceMatrix
>>> from sympy.stats.rv impo... | VarianceMatrix |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/private.py | {
"start": 6072,
"end": 6445
} | class ____(
PrivateViewMixin,
UpdateChangeReasonPostView,
OrganizationTeamView,
DeleteViewWithMessage,
):
http_method_names = ["post"]
success_message = _("Team deleted")
def get_success_url(self):
return reverse_lazy(
"organization_team_list",
args=[self.get... | DeleteOrganizationTeam |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 51459,
"end": 54501
} | class ____(CheckTestCase):
def test_autocomplete_e036(self):
class Admin(ModelAdmin):
autocomplete_fields = "name"
self.assertIsInvalid(
Admin,
Band,
msg="The value of 'autocomplete_fields' must be a list or tuple.",
id="admin.E036",
... | AutocompleteFieldsTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_symbol_annotations/lifecycle.py | {
"start": 15109,
"end": 28398
} | class ____:
breaking_version: str
hidden: bool
additional_warn_text: Optional[str]
subject: Optional[str]
@overload
def deprecated(
__obj: T_Annotatable,
*,
breaking_version: str,
additional_warn_text: Optional[str] = ...,
subject: Optional[str] = ...,
emit_runtime_warning: boo... | DeprecatedInfo |
python | TheAlgorithms__Python | data_structures/queues/priority_queue_using_list.py | {
"start": 201,
"end": 2636
} | class ____:
"""
Tasks can be added to a Priority Queue at any time and in any order but when Tasks
are removed then the Task with the highest priority is removed in FIFO order. In
code we will use three levels of priority with priority zero Tasks being the most
urgent (high priority) and priority 2... | FixedPriorityQueue |
python | scipy__scipy | scipy/io/matlab/_mio5.py | {
"start": 30468,
"end": 33989
} | class ____:
''' Class for writing mat5 files '''
@docfiller
def __init__(self, file_stream,
do_compression=False,
unicode_strings=False,
global_vars=None,
long_field_names=False,
oned_as='row'):
''' Initialize writ... | MatFile5Writer |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 74833,
"end": 75379
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Conv2d(3, 5, 3).to(dtype=torch.float)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Conv2d(5, 5, 1).to(dtype=torch.float)
def forward(self, x):
x = self.fc1(x)
x = s... | ConvReluAddModel |
python | astropy__astropy | astropy/uncertainty/tests/test_functions.py | {
"start": 1124,
"end": 1913
} | class ____(ArraySetup):
def test_concatenate(self):
# Concatenate needs consistent shapes.
db = self.db[np.newaxis]
concat_a_b = np.concatenate((self.da, db), axis=0)
expected_distr = np.concatenate((self.a, self.b[np.newaxis]), axis=0)
assert_array_equal(concat_a_b.distribut... | TestConcatenation |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 3998,
"end": 4196
} | class ____(BaseModel):
properties: dict[str, ParamProperty]
type: Literal["object"] = "object"
required: list[str] | None = None
additionalProperties: bool | None = None
| FunctionParams |
python | doocs__leetcode | solution/3200-3299/3249.Count the Number of Good Nodes/Solution.py | {
"start": 0,
"end": 656
} | class ____:
def countGoodNodes(self, edges: List[List[int]]) -> int:
def dfs(a: int, fa: int) -> int:
pre = -1
cnt = ok = 1
for b in g[a]:
if b != fa:
cur = dfs(b, a)
cnt += cur
if pre < 0:
... | Solution |
python | pydata__xarray | xarray/computation/apply_ufunc.py | {
"start": 1800,
"end": 47494
} | class ____:
"""Core dimensions signature for a given function.
Based on the signature provided by generalized ufuncs in NumPy.
Attributes
----------
input_core_dims : tuple[tuple, ...]
Core dimension names on each input variable.
output_core_dims : tuple[tuple, ...]
Core dimens... | _UFuncSignature |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 157961,
"end": 163117
} | class ____(Response):
"""
Response of tasks.delete endpoint.
:param deleted: Indicates whether the task was deleted
:type deleted: bool
:param updated_children: Number of child tasks whose parent property was
updated
:type updated_children: int
:param updated_models: Number of model... | DeleteResponse |
python | kamyu104__LeetCode-Solutions | Python/count-integers-with-even-digit-sum.py | {
"start": 396,
"end": 782
} | class ____(object):
def countEven(self, num):
"""
:type num: int
:rtype: int
"""
def parity(x):
result = 0
while x:
result += x%10
x //= 10
return result%2
return sum(parity(x) == 0 for x in xrange(1... | Solution2 |
python | MongoEngine__mongoengine | mongoengine/base/metaclasses.py | {
"start": 466,
"end": 8999
} | class ____(type):
"""Metaclass for all documents."""
# TODO lower complexity of this method
def __new__(mcs, name, bases, attrs):
flattened_bases = mcs._get_bases(bases)
super_new = super().__new__
# If a base class just call super
metaclass = attrs.get("my_metaclass")
... | DocumentMetaclass |
python | keras-team__keras | keras/src/layers/preprocessing/pipeline_test.py | {
"start": 164,
"end": 619
} | class ____(layers.Layer):
def __init__(self):
super().__init__()
self.training = None
self.received_mask = False
def call(self, x, training=False, mask=None):
self.training = training
if mask is not None:
self.received_mask = True
return x
def co... | CanaryLayer |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/configs.py | {
"start": 1072,
"end": 1374
} | class ____(_StageConfigBase):
model_source: Optional[str] = Field(
default=None, description="Model source/identifier for this stage."
)
chat_template: Optional[str] = Field(default=None)
chat_template_kwargs: Optional[Dict[str, Any]] = Field(default=None)
| ChatTemplateStageConfig |
python | cython__cython | runtests.py | {
"start": 68694,
"end": 75658
} | class ____(unittest.TestCase):
def __init__(self, cython_dir):
self.cython_dir = cython_dir
unittest.TestCase.__init__(self)
def runTest(self):
source_dirs = ['Cython', 'Demos', 'docs', 'pyximport', 'tests']
import pycodestyle
@pycodestyle.register_check
def b... | TestCodeFormat |
python | django__django | tests/invalid_models_tests/test_relative_fields.py | {
"start": 45622,
"end": 48639
} | class ____(SimpleTestCase):
def test_fk_to_integer(self):
self._test_reverse_query_name_clash(
target=models.IntegerField(),
relative=models.ForeignKey("Target", models.CASCADE),
)
def test_fk_to_fk(self):
self._test_reverse_query_name_clash(
target=m... | ReverseQueryNameClashTests |
python | TheAlgorithms__Python | data_structures/trie/trie.py | {
"start": 340,
"end": 3614
} | class ____:
def __init__(self) -> None:
self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode
self.is_leaf = False
def insert_many(self, words: list[str]) -> None:
"""
Inserts a list of words into the Trie
:param words: list of string words
:retur... | TrieNode |
python | scikit-learn__scikit-learn | sklearn/feature_selection/_univariate_selection.py | {
"start": 28332,
"end": 31023
} | class ____(_BaseFilter):
"""Filter: Select the pvalues below alpha based on a FPR test.
FPR test stands for False Positive Rate test. It controls the total
amount of false detections.
Read more in the :ref:`User Guide <univariate_feature_selection>`.
Parameters
----------
score_func : cal... | SelectFpr |
python | getsentry__sentry | tests/sentry/sudo/test_utils.py | {
"start": 1918,
"end": 3571
} | class ____(BaseTestCase):
def test_untouched(self) -> None:
self.assertFalse(has_sudo_privileges(self.request))
def test_granted(self) -> None:
self.login()
grant_sudo_privileges(self.request)
self.assertTrue(has_sudo_privileges(self.request))
def test_revoked(self) -> None... | HasSudoPrivilegesTestCase |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-path-with-edge-reversals.py | {
"start": 79,
"end": 977
} | class ____(object):
def minCost(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def dijkstra():
best = [float("inf")]*len(adj)
best[0] = 0
min_heap = [(best[0], 0)]
while min_heap:
... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/athena/resources.py | {
"start": 3669,
"end": 3776
} | class ____(AthenaClient):
"""This class was used by the function-style Athena resource."""
| AthenaResource |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 119779,
"end": 119987
} | class ____(Double[_N]):
"""The SQL DOUBLE type.
.. versionadded:: 2.0
.. seealso::
:class:`_types.Double` - documentation for the base type.
"""
__visit_name__ = "DOUBLE"
| DOUBLE |
python | pytorch__pytorch | torch/nn/modules/padding.py | {
"start": 21808,
"end": 23907
} | class ____(_ReplicationPadNd):
r"""Pads the input tensor using replication of the input boundary.
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
Args:
padding (int, tuple): the size of the padding. If is `int`, uses the same
padding in all boundaries. If a 4-`tuple... | ReplicationPad2d |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_trace.py | {
"start": 5417,
"end": 5526
} | class ____(TypedDict):
orphan_errors: list[TraceError]
transactions: list[FullResponse]
| SerializedTrace |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_resource_pool.py | {
"start": 383,
"end": 7818
} | 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... | V1beta1ResourcePool |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet_first_layers.py | {
"start": 1854,
"end": 1960
} | class ____:
def forward(self, X):
return tf.nn.relu(X)
def get_params(self):
return []
| ReLULayer |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/bigquery_to_mysql.py | {
"start": 1198,
"end": 3662
} | class ____(BigQueryToSqlBaseOperator):
"""
Fetch data from a BigQuery table (alternatively fetch selected columns) and insert it into a MySQL table.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigQueryToMySqlOperator`
:p... | BigQueryToMySqlOperator |
python | google__pytype | pytype_extensions/instrumentation_for_testing_test.py | {
"start": 224,
"end": 357
} | class ____:
def __init__(self):
raise RuntimeError("Meant to be inaccessible")
def Mul100(self, i):
return i * 100
| NoCtor |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofworkv2.py | {
"start": 27527,
"end": 43578
} | class ____(UOWTest):
def teardown_test(self):
engines.testing_reaper.rollback_all()
# mysql can't handle delete from nodes
# since it doesn't deal with the FKs correctly,
# so wipe out the parent_id first
with testing.db.begin() as conn:
conn.execute(self.tables.n... | SingleCycleTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.