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 | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 0,
"end": 91
} | class ____(Exception):
"""
Base class for all exceptions
"""
pass
| PyJWTError |
python | huggingface__transformers | tests/models/speech_to_text/test_processing_speech_to_text.py | {
"start": 1209,
"end": 6221
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmpdirname = tempfile.mkdtemp()
vocab = ["<s>", "<pad>", "</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est"]
vocab_tokens = dict(zip(vocab, range(len(vocab))))
save_dir = Path(cls.tmpdirname)
save_json(... | Speech2TextProcessorTest |
python | mlflow__mlflow | mlflow/server/job_api.py | {
"start": 377,
"end": 1497
} | class ____(BaseModel):
"""
Pydantic model for job query response.
"""
job_id: str
creation_time: int
function_fullname: str
params: dict[str, Any]
timeout: float | None
status: JobStatus
result: Any
retry_count: int
last_update_time: int
@classmethod
def from_jo... | Job |
python | django__django | tests/or_lookups/models.py | {
"start": 308,
"end": 525
} | class ____(models.Model):
headline = models.CharField(max_length=50)
pub_date = models.DateTimeField()
class Meta:
ordering = ("pub_date",)
def __str__(self):
return self.headline
| Article |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_glue.py | {
"start": 23485,
"end": 30286
} | class ____:
RUN_ID = "1234"
RULE_SET_NAME = "test_rule"
RULE_SET_CONFIG = {
"Name": "test_rule",
"Ruleset": 'Rules=[ColumnLength "review_id" = 15]',
"TargetTable": {"DatabaseName": "test_db", "TableName": "test_table"},
"Description": "test rule",
}
def setup_method(... | TestGlueDataQualityHook |
python | huggingface__transformers | src/transformers/models/rwkv/modeling_rwkv.py | {
"start": 28090,
"end": 33191
} | class ____(RwkvPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"head.weight": "rwkv.embeddings.weight"}
def __init__(self, config):
super().__init__(config)
self.rwkv = RwkvModel(config)
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initial... | RwkvForCausalLM |
python | falconry__falcon | tests/asgi/test_scope.py | {
"start": 193,
"end": 7126
} | class ____:
def items(self):
return [('foo', 'bar')]
def test_missing_asgi_version():
scope = testing.create_scope()
del scope['asgi']
resource = _call_with_scope(scope)
# NOTE(kgriffs): According to the ASGI spec, the version should
# default to "2.0".
assert resource.captured... | CustomCookies |
python | huggingface__transformers | tests/models/fsmt/test_modeling_fsmt.py | {
"start": 1580,
"end": 5094
} | class ____:
def __init__(
self,
parent,
src_vocab_size=99,
tgt_vocab_size=99,
langs=["ru", "en"],
batch_size=13,
seq_length=7,
is_training=False,
use_labels=False,
hidden_size=16,
num_hidden_layers=2,
num_attention_heads... | FSMTModelTester |
python | PrefectHQ__prefect | src/integrations/prefect-snowflake/prefect_snowflake/experimental/workers/spcs.py | {
"start": 11798,
"end": 16412
} | class ____(BaseVariables):
"""Defines variables which can be overridden by deployments.
Must include all variables in SPCSWorkerConfiguration. All validation should happen in SPCSWorkerConfiguration.
"""
image: str = Field(
default_factory=get_prefect_image_name,
description="The image... | SPCSServiceTemplateVariables |
python | django__django | tests/gis_tests/gis_migrations/test_commands.py | {
"start": 127,
"end": 2491
} | class ____(TransactionTestCase):
"""
Tests running the migrate command in GeoDjango.
"""
available_apps = ["gis_tests.gis_migrations"]
def get_table_description(self, table):
with connection.cursor() as cursor:
return connection.introspection.get_table_description(cursor, table... | MigrateTests |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-mdx-builder/sphinxcontrib/mdxbuilder/writers/mdx.py | {
"start": 4333,
"end": 43057
} | class ____(SphinxTranslator):
def __init__(self, document: nodes.document, builder: "MdxBuilder") -> None:
super().__init__(document, builder)
self.sectionlevel = 0
self.nl = "\n"
self.messages: list[str] = []
self._warned: set[str] = set()
self.states: list[list[tupl... | MdxTranslator |
python | gevent__gevent | src/greentest/3.11/test_httplib.py | {
"start": 56978,
"end": 60763
} | class ____(TestCase):
"""
Test peek(), read1(), readline()
"""
lines = (
'HTTP/1.1 200 OK\r\n'
'\r\n'
'hello world!\n'
'and now \n'
'for something completely different\n'
'foo'
)
lines_expected = lines[lines.find('hello'):].encode("ascii")
... | ExtendedReadTest |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/fields.py | {
"start": 11817,
"end": 12706
} | class ____(StringField):
"""Time field."""
types = (datetime.time,)
def __init__(self, str_format: str = None, *args: Any, **kwargs: Any) -> None:
"""Init.
:param str str_format: Format to cast time to (if `None` - casting to
ISO 8601 format).
"""
self.str_for... | TimeField |
python | ray-project__ray | release/nightly_tests/placement_group_tests/pg_run.py | {
"start": 463,
"end": 1600
} | class ____(object):
def __init__(self, i):
self.i = i
def train(self):
time.sleep(0.2)
print("train ", self.i)
def main():
ray.init(address="auto")
bundles = [{"CPU": 1, "GPU": 1}]
bundles += [{"CPU": 1} for _ in range(NUM_CPU_BUNDLES)]
pg = placement_group(bundles, ... | Trainer |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-gaudi/llama_index/embeddings/gaudi/base.py | {
"start": 922,
"end": 1762
} | class ____(SentenceTransformer):
"""Child class that overrides the tokenize method from SentenceTransformer."""
def __init__(self, model_name_or_path, embedding_input_size=-1, **kwargs) -> None:
super().__init__(model_name_or_path, **kwargs)
self.embedding_input_size = embedding_input_size
... | GaudiSentenceTransformer |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy.py | {
"start": 5260,
"end": 5524
} | class ____:
def __init__(self, messages=None):
self.messages = messages or []
async def __call__(self):
while True:
if self.messages:
return self.messages.pop()
await asyncio.sleep(0.1)
| FakeHttpReceive |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/base.py | {
"start": 4085,
"end": 11161
} | class ____(
BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
):
"""Base class to parse the output of an LLM call.
Output parsers help structure language model responses.
Example:
```python
# Implement a simple boolean output parser
class BooleanOutputParser(B... | BaseOutputParser |
python | PrefectHQ__prefect | src/prefect/server/task_queue.py | {
"start": 2922,
"end": 3527
} | class ____:
"""A queue that can pull tasks from from any of a number of task queues"""
_queues: List[TaskQueue]
def __init__(self, task_keys: List[str]):
self._queues = [TaskQueue.for_key(task_key) for task_key in task_keys]
async def get(self) -> schemas.core.TaskRun:
"""Gets the nex... | MultiQueue |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 17056,
"end": 17414
} | class ____(BaseField):
"""Boolean field type."""
def to_python(self, value):
try:
value = bool(value)
except (ValueError, TypeError):
pass
return value
def validate(self, value):
if not isinstance(value, bool):
self.error("BooleanField on... | BooleanField |
python | Textualize__rich | tests/test_pretty.py | {
"start": 6029,
"end": 20281
} | class ____(NamedTuple):
name: str
description: str
price: float
category: str
reviews: List[str]
def test_pretty_namedtuple() -> None:
console = Console(color_system=None)
console.begin_capture()
example_namedtuple = StockKeepingUnit(
"Sparkling British Spring Water",
... | StockKeepingUnit |
python | astropy__astropy | astropy/units/function/logarithmic.py | {
"start": 4805,
"end": 5788
} | class ____(LogUnit):
"""Logarithmic physical units expressed in magnitudes.
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the magnitude function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `... | DexUnit |
python | python-poetry__poetry | tests/repositories/fixtures/pypi.org/generate.py | {
"start": 3613,
"end": 3930
} | class ____:
path: Path
md5: str = dataclasses.field(init=False)
sha256: str = dataclasses.field(init=False)
def __post_init__(self) -> None:
data = self.path.read_bytes()
self.sha256 = hashlib.sha256(data).hexdigest()
self.md5 = hashlib.md5(data).hexdigest()
| ReleaseFileMetadata |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 5739,
"end": 12223
} | class ____:
# pos (string, int, int) Source file position
# is_name boolean Is a NameNode
# is_literal boolean Is a ConstNode
is_name = 0
is_none = 0
is_nonecheck = 0
is_literal = 0
is_terminator = 0
is_wrapper = False # is a DefNode wrap... | Node |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchValue1.py | {
"start": 2211,
"end": 2275
} | class ____(Enum):
gold = 1
silver = 2
bronze = 3
| Medal |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/interface.py | {
"start": 165,
"end": 636
} | class ____(DefaultAudioInterface, BaseVoiceAgentInterface):
def __init__(self, *args, **kwargs):
super().__init__()
# Some methods from BaseVoiceAgentInterface are not implemented in DefaultAudioInterface, so we implement toy methods here
def _speaker_callback(self, *args, **kwargs):
pass
... | ElevenLabsVoiceAgentInterface |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType29.py | {
"start": 279,
"end": 386
} | class ____(Generic[T1]): ...
def func1(x: A[T2]) -> A[T2 | None]: ...
x1: A[int | None] = func1(A[int]())
| A |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_root_cause_analysis.py | {
"start": 399,
"end": 13741
} | class ____(MetricsAPIBaseTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.url = reverse(
"sentry-api-0-organization-even... | OrganizationRootCauseAnalysisTest |
python | astropy__astropy | astropy/nddata/bitmask.py | {
"start": 5646,
"end": 27392
} | class ____(metaclass=BitFlagNameMeta):
"""
A base class for bit flag name maps used to describe data quality (DQ)
flags of images by provinding a mapping from a mnemonic flag name to a flag
value.
Mapping for a specific instrument should subclass this class.
Subclasses should define flags as cl... | BitFlagNameMap |
python | astropy__astropy | astropy/units/structured.py | {
"start": 2027,
"end": 18577
} | class ____:
"""Container for units for a structured Quantity.
Parameters
----------
units : unit-like, tuple of unit-like, or `~astropy.units.StructuredUnit`
Tuples can be nested. If a `~astropy.units.StructuredUnit` is passed
in, it will be returned unchanged unless different names ar... | StructuredUnit |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 30916,
"end": 39214
} | class ____(EfficientLoFTRPreTrainedModel):
def __init__(self, config: EfficientLoFTRConfig):
super().__init__(config)
self.config = config
self.backbone = EfficientLoFTRepVGG(config)
self.local_feature_transformer = EfficientLoFTRLocalFeatureTransformer(config)
self.rotary_e... | EfficientLoFTRModel |
python | django__django | tests/model_options/test_default_pk.py | {
"start": 273,
"end": 4676
} | class ____(SimpleTestCase):
def test_default_value_of_default_auto_field_setting(self):
"""django.conf.global_settings defaults to BigAutoField."""
class MyModel(models.Model):
pass
self.assertIsInstance(MyModel._meta.pk, models.BigAutoField)
@override_settings(DEFAULT_AUT... | TestDefaultPK |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ssm/resources.py | {
"start": 769,
"end": 4445
} | class ____(ResourceWithBoto3Configuration):
"""Resource that gives access to AWS Systems Manager Parameter Store.
The underlying Parameter Store session is created by calling
:py:func:`boto3.session.Session(profile_name) <boto3:boto3.session>`.
The returned resource object is a Systems Manager client, ... | SSMResource |
python | Netflix__metaflow | test/test_config/card_config.py | {
"start": 64,
"end": 400
} | class ____(FlowSpec):
config = Config("config", default_value="")
@card(type=config.type)
@step
def start(self):
print("card type", self.config.type)
self.next(self.end)
@step
def end(self):
print("full config", self.config)
if __name__ == "__main__":
CardConfigF... | CardConfigFlow |
python | great-expectations__great_expectations | tests/datasource/fluent/data_asset/test_sql_asset.py | {
"start": 2991,
"end": 3285
} | class ____:
def __init__(self, queried_row: Any):
self._queried_row = queried_row
def execute(self, *args, **kwargs):
return FakeResult(self._queried_row)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb): ...
| FakeConnection |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_transfer.py | {
"start": 7757,
"end": 9656
} | class ____(TestCase):
def test_missing_transfer(self) -> None:
res = process_relocation_transfer_region(transfer_id=999)
assert res is None
def test_transfer_request_state(self) -> None:
transfer = create_region_relocation_transfer(
organization=self.organization,
... | ProcessRelocationTransferRegionTest |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 101138,
"end": 101722
} | class ____(APITestCase):
provider = "dummy"
def setUp(self):
super().setUp()
with assume_test_silo_mode(SiloMode.CONTROL):
self.auth_provider_inst = AuthProviderModel(
organization_id=self.organization.id, provider=self.provider
)
self.auth_pr... | SCIMTestCase |
python | patrick-kidger__equinox | equinox/_ad.py | {
"start": 19849,
"end": 25834
} | class ____(Module):
# Important that `jaxpr` be a leaf (and not static), so that it is a tuple element
# when passing through `filter_primitive_bind` and thus visible to
# `jax.core.subjaxprs`
jaxpr: jax.extend.core.Jaxpr
consts: PyTree[ArrayLike] # Captured in the PyTree structure of _ClosureConve... | _ClosureConvert |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/event/base.py | {
"start": 1744,
"end": 2303
} | class ____:
"""Serializable callable that re-generates an instance of
:class:`_Dispatch` given a particular :class:`.Events` subclass.
"""
def __call__(self, _instance_cls: Type[_ET]) -> _Dispatch[_ET]:
for cls in _instance_cls.__mro__:
if "dispatch" in cls.__dict__:
... | _UnpickleDispatch |
python | dagster-io__dagster | python_modules/libraries/dagster-msteams/dagster_msteams/adaptive_card.py | {
"start": 25,
"end": 1344
} | class ____:
"""Class to contruct a MS Teams adaptive card for posting Dagster messages."""
def __init__(self, adaptive_card_version: str = "1.5"):
"""Constructs an adaptive card with the given version.
Args:
adaptive_card_version (str): The version of the adaptive card to use. Defa... | AdaptiveCard |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 32158,
"end": 34457
} | class ____(logging.Formatter):
"""Logging formatter that strips ANSI escape codes."""
def format(self, record):
msg = super().format(record)
return ANSI_ESCAPE_PATTERN.sub("", msg)
def add_file_handler() -> contextlib.ExitStack:
log_path = os.path.join(get_debug_dir(), "torchdynamo")
... | StripAnsiFormatter |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 95841,
"end": 96493
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
code: Optional[TerminationCode] = Field(
None, description="Status code indicating why a cluster was terminated."
)
parameters: Optional[ParameterPair] ... | TerminationReason |
python | apache__airflow | providers/smtp/tests/unit/smtp/notifications/test_smtp.py | {
"start": 8571,
"end": 12737
} | class ____:
@pytest.fixture
def mock_smtp_client(self):
"""Create a mock SMTP object with async capabilities."""
mock_smtp = AsyncMock()
mock_smtp.asend_email_smtp = AsyncMock()
return mock_smtp
@pytest.fixture
def mock_smtp_hook(self, mock_smtp_client):
"""Set u... | TestSmtpNotifierAsync |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_cross_trace.py | {
"start": 113,
"end": 10696
} | class ____(OrganizationEventsEndpointTestBase):
def test_cross_trace_query_with_logs(self) -> None:
trace_id = uuid.uuid4().hex
excluded_trace_id = uuid.uuid4().hex
logs = [
self.create_ourlog(
{"body": "foo", "trace_id": trace_id},
timestamp=self.... | OrganizationEventsSpansEndpointTest |
python | conda__conda | conda/activate.py | {
"start": 39581,
"end": 40517
} | class ____(_Activator):
pathsep_join = ";".join if on_win else ":".join
sep = "\\" if on_win else "/"
path_conversion = staticmethod(_path_identity)
script_extension = ".ps1"
tempfile_extension = None # output to stdout
command_join = "\n"
needs_line_ending_fix = False
unset_var_tmpl =... | PowerShellActivator |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 22647,
"end": 23190
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, api_key: str):
"""Airbyte Source for Greenhouse.
Documentation can be found at https://docs.airbyte.com/integrations/sources/greenhouse
Args:
name (str): The name of the destination.
api_k... | GreenhouseSource |
python | scikit-learn__scikit-learn | sklearn/svm/_classes.py | {
"start": 1327,
"end": 14429
} | class ____(LinearClassifierMixin, SparseCoefMixin, BaseEstimator):
"""Linear Support Vector Classification.
Similar to SVC with parameter kernel='linear', but implemented in terms of
liblinear rather than libsvm, so it has more flexibility in the choice of
penalties and loss functions and should scale ... | LinearSVC |
python | pytorch__pytorch | torch/_dynamo/guards.py | {
"start": 7290,
"end": 33276
} | class ____:
"""
A helper class that contains the root guard manager. An instance of this
class is stored in the Dynamo cache entry, so that the cache entry can
access the RootGuardManager stored in the "root" attribute and directly call
the check_nopybind from C++.
"""
def __init__(self, ro... | GuardManagerWrapper |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 60535,
"end": 70738
} | class ____(IR):
"""Perform a groupby."""
__slots__ = (
"agg_requests",
"keys",
"maintain_order",
"zlice",
)
_non_child = (
"schema",
"keys",
"agg_requests",
"maintain_order",
"zlice",
)
keys: tuple[expr.NamedExpr, ...]
... | GroupBy |
python | pypa__warehouse | tests/common/db/sponsors.py | {
"start": 139,
"end": 701
} | class ____(WarehouseFactory):
class Meta:
model = Sponsor
name = factory.Faker("word")
service = factory.Faker("sentence")
activity_markdown = factory.Faker("sentence")
link_url = factory.Faker("uri")
color_logo_url = factory.Faker("image_url")
white_logo_url = factory.Faker("image... | SponsorFactory |
python | tornadoweb__tornado | demos/s3server/s3server.py | {
"start": 5322,
"end": 8252
} | class ____(BaseRequestHandler):
def get(self, bucket_name):
prefix = self.get_argument("prefix", "")
marker = self.get_argument("marker", "")
max_keys = int(self.get_argument("max-keys", 50000))
path = os.path.abspath(os.path.join(self.application.directory, bucket_name))
ter... | BucketHandler |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 4887,
"end": 5191
} | class ____(XsdString):
@classmethod
def validate(cls, value: str) -> None:
cls.validate_string(value)
valid_values = ("none", "left", "right", "all")
if value not in valid_values:
raise ValueError("must be one of %s, got '%s'" % (valid_values, value))
| ST_BrClear |
python | numba__numba | numba/cuda/tests/cudapy/test_extending.py | {
"start": 137,
"end": 2712
} | class ____:
"""
A half-open interval on the real number line.
"""
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
def __repr__(self):
return 'Interval(%f, %f)' % (self.lo, self.hi)
@property
def width(self):
return self.hi - self.lo
@njit
def interva... | Interval |
python | google__jax | jax/_src/shard_map.py | {
"start": 29047,
"end": 50974
} | class ____(core.Primitive):
multiple_results = True
def bind(self, *args, **params):
return self._true_bind(*args, **params)
def bind_with_trace(self, trace, fun_and_args, params):
fun: lu.WrappedFun
fun, *args = fun_and_args
return trace.process_shard_map(shard_map_p, fun, args, **params)
de... | ShardMapPrimitive |
python | Textualize__textual | src/textual/dom.py | {
"start": 3418,
"end": 3503
} | class ____(DOMError):
"""Raised when the node has no associated screen."""
| NoScreen |
python | dagster-io__dagster | examples/project_fully_featured/project_fully_featured/resources/parquet_io_manager.py | {
"start": 361,
"end": 2608
} | class ____(ConfigurableIOManager):
"""This IOManager will take in a pandas or pyspark dataframe and store it in parquet at the
specified path.
It stores outputs for different partitions in different filepaths.
Downstream ops can either load this dataframe into a spark session or simply retrieve a path... | PartitionedParquetIOManager |
python | google__jax | tests/key_reuse_test.py | {
"start": 2476,
"end": 11124
} | class ____(jtu.JaxTestCase):
def check_key_reuse(self, *args):
return _core.check_key_reuse(*args)
def test_assertions(self):
key = jax.random.key(0)
self.check_key_reuse(assert_unconsumed, key)
with self.assertRaises(AssertionError):
self.check_key_reuse(assert_consumed, key)
def test_unk... | KeyReuseUnitTestWithForwarding |
python | django__django | django/core/exceptions.py | {
"start": 1536,
"end": 1718
} | class ____(SuspiciousOperation):
"""
The size of the request (excluding any file uploads) exceeded
settings.DATA_UPLOAD_MAX_MEMORY_SIZE.
"""
pass
| RequestDataTooBig |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 34041,
"end": 35169
} | class ____(ASTExpression):
def __init__(self, identifier: ASTIdentifier) -> None:
self.identifier = identifier
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTSizeofParamPack):
return NotImplemented
return self.identifier == other.identifier
def __h... | ASTSizeofParamPack |
python | django__django | tests/apps/query_performing_app/apps.py | {
"start": 904,
"end": 1203
} | class ____(BaseAppConfig):
def _perform_query(self):
connection = connections[self.database]
with connection.cursor() as cursor:
cursor.execute("SELECT 42" + connection.features.bare_select_suffix)
self.query_results = cursor.fetchall()
| CursorQueryAppConfig |
python | kamyu104__LeetCode-Solutions | Python/number-of-possible-sets-of-closing-branches.py | {
"start": 101,
"end": 1408
} | class ____(object):
def numberOfSets(self, n, maxDistance, roads):
"""
:type n: int
:type maxDistance: int
:type roads: List[List[int]]
:rtype: int
"""
def check(mask, dist):
return all(dist[i][j] <= maxDistance for i in xrange(n) if mask&(1<<i) fo... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/array_ops_shape_test.py | {
"start": 907,
"end": 2069
} | class ____(test.TestCase):
def testShapeInt64Flag(self):
# The tf_shape_default_int64 flag should be set when this test runs
self.assertTrue(flags.config().tf_shape_default_int64.value())
s1 = array_ops.shape_v2(array_ops.zeros([1, 2]))
self.assertEqual(s1.dtype, dtypes.int64)
def testShapeInt64Fl... | ArrayOpShapeSizeTest |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 3528,
"end": 3617
} | class ____(RequestHandler):
def get(self):
self.write("ok")
| NonWebSocketHandler |
python | Netflix__metaflow | metaflow/user_configs/config_options.py | {
"start": 2190,
"end": 3278
} | class ____(click.ParamType):
name = "ConvertDictOrStr"
def convert(self, value, param, ctx):
is_default = False
if isinstance(value, str):
if value.startswith(_CONVERT_PREFIX):
return value
if value.startswith(_DEFAULT_PREFIX):
is_default ... | ConvertDictOrStr |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_method.py | {
"start": 365,
"end": 647
} | class ____(Abstract):
"""Abstract class.
this class is checking that it does not output an error msg for
unimplemeted methods in abstract classes
"""
def cccc(self):
"""should be overridden in concrete class"""
raise NotImplementedError()
| AbstractB |
python | plotly__plotly.py | plotly/graph_objs/isosurface/colorbar/_tickfont.py | {
"start": 233,
"end": 9933
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.colorbar"
_path_str = "isosurface.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Tickfont |
python | doocs__leetcode | solution/3500-3599/3512.Minimum Operations to Make Array Sum Divisible by K/Solution.py | {
"start": 0,
"end": 106
} | class ____:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(nums) % k
| Solution |
python | kamyu104__LeetCode-Solutions | Python/find-array-given-subset-sums.py | {
"start": 7009,
"end": 8125
} | class ____(object):
def recoverArray(self, n, sums):
"""
:type n: int
:type sums: List[int]
:rtype: List[int]
"""
dp = OrderedDict(sorted(collections.Counter(sums).iteritems())) # Time: O(2^n * log(2^n)) = O(n * 2^n)
shift = 0
result = []
for ... | Solution5 |
python | pypa__pipenv | pipenv/vendor/click/testing.py | {
"start": 4241,
"end": 16084
} | class ____:
"""The CLI runner provides functionality to invoke a Click command line
script for unittesting purposes in a isolated environment. This only
works in single-threaded systems without any concurrency as it changes the
global interpreter state.
:param charset: the character set for the in... | CliRunner |
python | wandb__wandb | wandb/automations/_filters/expressions.py | {
"start": 612,
"end": 4164
} | class ____:
"""A descriptor that can be used to define a "filterable" field on a class.
Internal helper to support syntactic sugar for defining event filters.
"""
_python_name: str #: The name of the field this descriptor was assigned to in the Python class.
_server_name: str | None #: If set, t... | FilterableField |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 3166,
"end": 4720
} | class ____:
vector: bool
uuid: bool = True
creation_time_unix: bool = False
last_update_time_unix: bool = False
distance: bool = False
certainty: bool = False
score: bool = False
explain_score: bool = False
is_consistent: bool = False
vectors: Optional[List[str]] = None
@cla... | _MetadataQuery |
python | spack__spack | lib/spack/spack/error.py | {
"start": 4287,
"end": 4375
} | class ____(SpackError):
"""Raised when a patch file doesn't exist."""
| NoSuchPatchError |
python | dagster-io__dagster | python_modules/dagster/dagster/components/utils/translation.py | {
"start": 6527,
"end": 8324
} | class ____(Generic[T_Component]):
"""To support python versions < 3.10, we need to use a Protocol to tell the type system that
these generated classes have a component property.
"""
def __init__(self, component: T_Component, *args, **kwargs):
self._component = component
super().__init__... | ComponentTranslator |
python | pypa__packaging | tests/test_tags.py | {
"start": 14294,
"end": 17476
} | class ____:
@pytest.mark.usefixtures("mock_ios")
def test_version_detection(self) -> None:
platforms = list(tags.ios_platforms(multiarch="arm64-iphoneos"))
assert platforms == [
"ios_13_2_arm64_iphoneos",
"ios_13_1_arm64_iphoneos",
"ios_13_0_arm64_iphoneos",
... | TestIOSPlatforms |
python | walkccc__LeetCode | solutions/1552. Magnetic Force Between Two Balls/1552.py | {
"start": 0,
"end": 499
} | class ____:
def maxDistance(self, position: list[int], m: int) -> int:
position.sort()
l = 1
r = position[-1] - position[0]
def numBalls(force: int) -> int:
balls = 0
prevPosition = -force
for pos in position:
if pos - prevPosition >= force:
balls += 1
p... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 201061,
"end": 224346
} | class ____(Request):
"""
Edit task's details.
:param task: ID of the task
:type task: str
:param force: If not true, call fails if the task status is not 'created'
:type force: bool
:param name: Task name Unique within the company.
:type name: str
:param tags: User-defined tags list... | EditRequest |
python | huggingface__transformers | src/transformers/models/sam_hq/modular_sam_hq.py | {
"start": 8375,
"end": 8434
} | class ____(SamPreTrainedModel):
pass
| SamHQPreTrainedModel |
python | doocs__leetcode | lcci/17.12.BiNode/Solution.py | {
"start": 164,
"end": 587
} | class ____:
def convertBiNode(self, root: TreeNode) -> TreeNode:
def dfs(root):
if root is None:
return
nonlocal prev
dfs(root.left)
prev.right = root
root.left = None
prev = root
dfs(root.right)
dum... | Solution |
python | wandb__wandb | wandb/sdk/mailbox/mailbox_handle.py | {
"start": 3231,
"end": 4072
} | class ____(Generic[_S], MailboxHandle[_S]):
"""A mailbox handle whose result is derived from another handle."""
def __init__(
self,
handle: MailboxHandle[_T],
fn: Callable[[_T], _S],
) -> None:
super().__init__(handle.asyncer)
self._handle = handle
self._fn =... | _MailboxMappedHandle |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/foundry.py | {
"start": 1084,
"end": 1329
} | class ____(AnthropicError):
def __init__(self) -> None:
super().__init__(
"The `api_key` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time"
)
| MutuallyExclusiveAuthError |
python | readthedocs__readthedocs.org | readthedocs/search/migrations/0005_alter_searchquery_id.py | {
"start": 149,
"end": 573
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("search", "0004_make_total_results_not_null"),
]
operations = [
migrations.AlterField(
model_name="searchquery",
name="id",
field=models.BigAutoField(
auto_... | Migration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 4409,
"end": 4664
} | class ____(Parent4[int]):
@overload
def function(self: Parent4[int], a: None) -> float: ...
@overload
def function(self: Parent4[int], a: int) -> float: ...
def function(self, a: int | None = None) -> float:
return 0.0
| Child4_1 |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_constructor.py | {
"start": 77,
"end": 1504
} | class ____(TestCase):
def test_kwarg(self):
m = go.scatter.Marker(color="green")
self.assertEqual(m.to_plotly_json(), {"color": "green"})
def test_valid_arg_dict(self):
m = go.scatter.Marker(dict(color="green"))
self.assertEqual(m.to_plotly_json(), {"color": "green"})
def t... | TestGraphObjConstructor |
python | getsentry__sentry | src/sentry/identity/oauth2.py | {
"start": 2066,
"end": 7456
} | class ____(Provider):
"""
The OAuth2Provider is a generic way to implement an identity provider that
uses the OAuth 2.0 protocol as a means for authenticating a user.
OAuth scopes are configured through the oauth_scopes class property,
however may be overridden using the ``config['oauth_scopes']`` ... | OAuth2Provider |
python | hynek__structlog | src/structlog/_base.py | {
"start": 620,
"end": 7364
} | class ____:
"""
Immutable context carrier.
Doesn't do any actual logging; examples for useful subclasses are:
- the generic `BoundLogger` that can wrap anything,
- `structlog.stdlib.BoundLogger`.
- `structlog.twisted.BoundLogger`,
See also `custom-wrappers`.
"""
_logger: WrappedL... | BoundLoggerBase |
python | celery__celery | t/unit/backends/test_mongodb.py | {
"start": 2012,
"end": 25876
} | class ____:
default_url = 'mongodb://uuuu:pwpw@hostname.dom/database'
replica_set_url = (
'mongodb://uuuu:pwpw@hostname.dom,'
'hostname.dom/database?replicaSet=rs'
)
sanitized_default_url = 'mongodb://uuuu:**@hostname.dom/database'
sanitized_replica_set_url = (
'mongodb://uuu... | test_MongoBackend |
python | scipy__scipy | scipy/stats/_covariance.py | {
"start": 22373,
"end": 22913
} | class ____(Covariance):
"""
Representation of a covariance provided via an instance of _PSD
"""
__class_getitem__ = None
def __init__(self, psd):
self._LP = psd.U
self._log_pdet = psd.log_pdet
self._rank = psd.rank
self._covariance = psd._M
self._shape = psd... | CovViaPSD |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 214427,
"end": 218966
} | class ____(multi_rv_generic):
r"""A vector-valued uniform direction.
Return a random direction (unit vector). The `dim` keyword specifies
the dimensionality of the space.
Methods
-------
rvs(dim=None, size=1, random_state=None)
Draw random directions.
Parameters
----------
... | uniform_direction_gen |
python | django-import-export__django-import-export | import_export/results.py | {
"start": 5806,
"end": 6081
} | class ____:
"""A row that resulted in one or more errors being raised during import."""
def __init__(self, number, errors):
#: The row number
self.number = number
#: A list of errors associated with the row
self.errors = errors
| ErrorRow |
python | pypa__installer | src/installer/records.py | {
"start": 462,
"end": 745
} | class ____(Exception):
"""Raised when a RecordEntry is not valid, due to improper element values or count."""
elements: Iterable[str]
issues: Iterable[str]
def __post_init__(self) -> None:
super().__init__(", ".join(self.issues))
@dataclass
| InvalidRecordEntry |
python | django__django | django/contrib/staticfiles/handlers.py | {
"start": 459,
"end": 2114
} | class ____:
"""
Common methods used by WSGI and ASGI handlers.
"""
# May be used to differentiate between handler types (e.g. in a
# request_finished signal)
handles_files = True
def load_middleware(self):
# Middleware are already loaded for self.application; no need to reload
... | StaticFilesHandlerMixin |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-deeplake/llama_index/vector_stores/deeplake/base.py | {
"start": 12756,
"end": 24114
} | class ____(BasePydanticVectorStore):
"""
The DeepLake Vector Store.
In this vector store we store the text, its embedding and
a few pieces of its metadata in a deeplake dataset. This implementation
allows the use of an already existing deeplake dataset if it is one that was created
this vector ... | DeepLakeVectorStore |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 459841,
"end": 460303
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AbortQueuedMigrations"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "success")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the ... | AbortQueuedMigrationsPayload |
python | apache__airflow | airflow-core/tests/unit/models/test_taskinstance.py | {
"start": 117716,
"end": 128676
} | class ____:
@pytest.mark.parametrize(
("literal", "expected_outputs"),
[
pytest.param([1, 2, 3], [1, 2, 3], id="list"),
pytest.param({"a": 1, "b": 2}, [("a", 1), ("b", 2)], id="dict"),
],
)
def test_map_literal(self, literal, expected_outputs, dag_maker, sessi... | TestMappedTaskInstanceReceiveValue |
python | getsentry__sentry | tests/sentry/middleware/test_access_log_middleware.py | {
"start": 5711,
"end": 6461
} | class ____(APITestCase):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog: pytest.LogCaptureFixture):
self._caplog = caplog
def assert_access_log_recorded(self):
sentinel = object()
for record in self.captured_logs:
for field in required_access_log_fields:
... | LogCaptureAPITestCase |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 1631,
"end": 1825
} | class ____(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
| SongForm |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 16996,
"end": 17627
} | class ____(PatternExpr):
"""
Capture a kwarg which will become an input to the handler.
"""
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
def __repr__(self) -> str:
return f"KeywordArg({self.name!r})"
def _match(self, node: NodeOrConstant, ... | KeywordArg |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 36945,
"end": 37870
} | class ____(ASTExpression):
def __init__(self, typ: ASTType) -> None:
self.typ = typ
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTAlignofExpr):
return NotImplemented
return self.typ == other.typ
def __hash__(self) -> int:
return hash(self.... | ASTAlignofExpr |
python | ray-project__ray | doc/source/serve/doc_code/autoscale_model_comp_example.py | {
"start": 495,
"end": 1036
} | class ____:
def __init__(self, a_handle, b_handle):
self.a_handle: DeploymentHandle = a_handle
self.b_handle: DeploymentHandle = b_handle
async def __call__(self) -> str:
a_future = self.a_handle.remote()
b_future = self.b_handle.remote()
return (await a_future), (await... | Driver |
python | mlflow__mlflow | tests/resources/db/initial_models.py | {
"start": 978,
"end": 2271
} | class ____(Base):
"""
DB model for :py:class:`mlflow.entities.Experiment`. These are recorded in ``experiment`` table.
"""
__tablename__ = "experiments"
experiment_id = Column(Integer, autoincrement=True)
"""
Experiment ID: `Integer`. *Primary Key* for ``experiment`` table.
"""
nam... | SqlExperiment |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 17585,
"end": 18264
} | class ____(unittest.TestCase):
"""Tests person in the en_IN locale"""
def setUp(self):
self.fake = Faker("en_IN")
Faker.seed(0)
def test_first_name(self):
"""Verify that gender specific names are set correctly"""
name = self.fake.first_name_female()
assert name in ... | TestEnIN |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.