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 | ray-project__ray | python/ray/tests/unit/test_runtime_env_validation.py | {
"start": 2037,
"end": 3499
} | class ____:
def test_validate_bad_path(self):
with pytest.raises(ValueError, match="a valid path"):
parse_and_validate_working_dir("/does/not/exist")
def test_validate_bad_uri(self):
with pytest.raises(ValueError, match="a valid URI"):
parse_and_validate_working_dir("unk... | TestValidateWorkingDir |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/5.3_Dueling_DQN/RL_brain.py | {
"start": 272,
"end": 6714
} | class ____:
def __init__(
self,
n_actions,
n_features,
learning_rate=0.001,
reward_decay=0.9,
e_greedy=0.9,
replace_target_iter=200,
memory_size=500,
batch_size=32,
e_greedy_increment=None,
... | DuelingDQN |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_shape_base_.py | {
"start": 18210,
"end": 19576
} | class ____(TestCase):
def test_non_iterable(self):
assert_raises(TypeError, dstack, 1)
def test_0D_array(self):
a = np.array(1)
b = np.array(2)
res = dstack([a, b])
desired = np.array([[[1, 2]]])
assert_array_equal(res, desired)
def test_1D_array(self):
... | TestDstack |
python | chroma-core__chroma | chromadb/api/configuration.py | {
"start": 13081,
"end": 13958
} | class ____(ConfigurationInternal):
"""Internal representation of the collection configuration.
Used for validation, defaults, and serialization / deserialization."""
definitions = {
"hnsw_configuration": ConfigurationDefinition(
name="hnsw_configuration",
validator=lambda va... | CollectionConfigurationInternal |
python | celery__celery | t/integration/test_security.py | {
"start": 349,
"end": 3833
} | class ____:
@pytest.fixture(autouse=True, scope='class')
def class_certs(self, request):
self.tmpdir = tempfile.mkdtemp()
self.key_name = 'worker.key'
self.cert_name = 'worker.pem'
key = self.gen_private_key()
cert = self.gen_certificate(key=key,
... | test_security |
python | kamyu104__LeetCode-Solutions | Python/number-of-ships-in-a-rectangle.py | {
"start": 396,
"end": 471
} | class ____(object):
def __init__(self, x, y):
self.x = x
self.y = y
| Point |
python | getsentry__sentry | src/sentry/integrations/opsgenie/actions/form.py | {
"start": 1035,
"end": 3953
} | class ____(forms.Form):
"""Used for notifying a specific team."""
account = forms.ChoiceField(choices=(), widget=forms.Select())
team = forms.ChoiceField(required=False, choices=(), widget=forms.Select())
def __init__(self, *args, **kwargs):
self.org_id = kwargs.pop("org_id")
self._int... | OpsgenieNotifyTeamForm |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_cache_test.py | {
"start": 3616,
"end": 8153
} | class ____(test.TestCase):
def testConcreteFunctionDictRetainsInsertedKeys(self):
cache = function_cache.FunctionCache()
f_type_1 = make_type(1)
self.assertIsNone(cache.lookup(f_type_1))
f_type_2 = make_type(2)
f_type_3 = make_type(3)
cache.add(MockFunction(f_type_1, "test_1"))
cache.a... | FunctionCacheTest |
python | jina-ai__jina | tests/docker_compose/test-executor-torch/debug_executor.py | {
"start": 78,
"end": 3251
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from jina.logging.logger import JinaLogger
self.logger = JinaLogger(self.__class__.__name__)
self._name = self.runtime_args.name
@requests(on='/debug')
def debug(self, docs: Documen... | TestExecutor |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 223576,
"end": 223853
} | class ____(VegaLiteSchema):
"""ConditionalMarkPropFieldOrDatumDef schema wrapper."""
_schema = {"$ref": "#/definitions/ConditionalMarkPropFieldOrDatumDef"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ConditionalMarkPropFieldOrDatumDef |
python | joke2k__faker | faker/providers/phone_number/th_TH/__init__.py | {
"start": 49,
"end": 1826
} | class ____(PhoneNumberProvider):
# as per https://en.wikipedia.org/wiki/Telephone_numbers_in_Thailand
formats = (
# landline (9 digits, starts with 02, 03, 04, 05, or 07)
"+66 2### ####",
"+662 ### ####",
"+66 (0) 2### ####",
"02#######",
"0 2### ####",
"0... | Provider |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 17930,
"end": 18835
} | class ____(nn.Module):
def __init__(self, config: Glm4vMoeTextConfig):
super().__init__()
self.config = config
self.top_k = config.num_experts_per_tok
self.n_routed_experts = config.n_routed_experts
self.routed_scaling_factor = config.routed_scaling_factor
self.n_grou... | Glm4vMoeTextTopkRouter |
python | keras-team__keras | keras/src/ops/operation_utils_test.py | {
"start": 176,
"end": 7659
} | class ____(testing.TestCase):
def test_get_source_inputs(self):
x1 = backend.KerasTensor(shape=(2,))
x2 = backend.KerasTensor(shape=(2,))
x = x1 + x2
x += 2
x = ops.square(x)
self.assertEqual(operation_utils.get_source_inputs(x), [x1, x2])
def test_get_source_inp... | OperationUtilsTest |
python | MongoEngine__mongoengine | tests/fields/test_float_field.py | {
"start": 83,
"end": 1781
} | class ____(MongoDBTestCase):
def test_float_ne_operator(self):
class TestDocument(Document):
float_fld = FloatField()
TestDocument.drop_collection()
TestDocument(float_fld=None).save()
TestDocument(float_fld=1).save()
assert 1 == TestDocument.objects(float_fld_... | TestFloatField |
python | paramiko__paramiko | paramiko/buffered_pipe.py | {
"start": 1248,
"end": 7225
} | class ____:
"""
A buffer that obeys normal read (with timeout) & close semantics for a
file or socket, but is fed data from another thread. This is used by
`.Channel`.
"""
def __init__(self):
self._lock = threading.Lock()
self._cv = threading.Condition(self._lock)
self.... | BufferedPipe |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_load_centrality.py | {
"start": 39,
"end": 11343
} | class ____:
@classmethod
def setup_class(cls):
G = nx.Graph()
G.add_edge(0, 1, weight=3)
G.add_edge(0, 2, weight=2)
G.add_edge(0, 3, weight=6)
G.add_edge(0, 4, weight=4)
G.add_edge(1, 3, weight=5)
G.add_edge(1, 5, weight=5)
G.add_edge(2, 4, weight=... | TestLoadCentrality |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_average_to_be_within_range_of_given_point.py | {
"start": 2632,
"end": 7284
} | class ____(ColumnAggregateExpectation):
"""Expect the average of a column of degree-decimal, lat/lon coordinates to be in range of a given point."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
... | ExpectColumnAverageToBeWithinRangeOfGivenPoint |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 6421,
"end": 6878
} | class ____(BaseOp):
val: bool = Field(alias="$exists")
@override
def __invert__(self) -> Exists:
"""Implements `~Exists(True) -> Exists(False)` and vice versa."""
return Exists(val=not self.val)
# Evaluation operator(s)
# https://www.mongodb.com/docs/manual/reference/operator/query/regex/... | Exists |
python | pytorch__pytorch | torch/fx/_graph_pickler.py | {
"start": 5170,
"end": 5559
} | class ____:
def __init__(self, fake_mode: FakeTensorMode) -> None:
self.fake_mode = fake_mode
self.meta_converter: MetaConverter[FakeTensor] = MetaConverter()
# This token is passed when pickling to indicate that we want to use the
# unpickler's _UnpickleState as a parameter in that position.
_Unp... | _UnpickleState |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py | {
"start": 5459,
"end": 9976
} | class ____(object):
"""
Thread-safe kevent descriptor collection.
"""
def __init__(self):
# Set of KeventDescriptor
self._descriptors = set()
# Descriptor for a given path.
self._descriptor_for_path = dict()
# Descriptor for a given fd.
self._descripto... | KeventDescriptorSet |
python | geekcomputers__Python | PingPong/Ball.py | {
"start": 31,
"end": 1462
} | class ____:
def __init__(self, pos, vel, win, rad, minCoord, maxCoord):
self.pos = pos
self.vel = vel
self.win = win
self.rad = rad
self.minCoord = minCoord
self.maxCoord = maxCoord
def drawBall(self):
pygame.draw.circle(self.win, (255,) * 3, self.pos, se... | Ball |
python | zostera__django-bootstrap4 | tests/test_forms.py | {
"start": 12193,
"end": 13199
} | class ____(TestCase):
def test_show_label_false(self):
form = CharFieldTestForm()
res = render_template_with_form("{% bootstrap_form form show_label=False %}", {"form": form})
self.assertIn("sr-only", res)
def test_show_label_sr_only(self):
form = CharFieldTestForm()
res... | ShowLabelTest |
python | tox-dev__tox | src/tox/pytest.py | {
"start": 14764,
"end": 19625
} | class ____(Protocol):
def __call__(
self,
files: dict[str, Any],
base: Path | None = None,
prj_path: Path | None = None,
) -> ToxProject: ...
@pytest.fixture(name="tox_project")
def init_fixture(
tmp_path: Path,
capfd: CaptureFixture,
monkeypatch: pytest.MonkeyPatch... | ToxProjectCreator |
python | plotly__plotly.py | plotly/graph_objs/layout/_hoverlabel.py | {
"start": 235,
"end": 9064
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.hoverlabel"
_valid_props = {
"align",
"bgcolor",
"bordercolor",
"font",
"grouptitlefont",
"namelength",
"showarrow",
}
@property
def align(self):
... | Hoverlabel |
python | celery__celery | celery/utils/threads.py | {
"start": 4297,
"end": 7142
} | class ____:
"""Local stack.
This class works similar to a :class:`Local` but keeps a stack
of objects instead. This is best explained with an example::
>>> ls = LocalStack()
>>> ls.push(42)
>>> ls.top
42
>>> ls.push(23)
>>> ls.top
23
>>> ls.... | _LocalStack |
python | bottlepy__bottle | bottle.py | {
"start": 140829,
"end": 141949
} | class ____(ServerAdapter):
""" Untested. Options:
* `backlog` adjust the eventlet backlog parameter which is the maximum
number of queued connections. Should be at least 1; the maximum
value is system-dependent.
* `family`: (default is 2) socket family, optional. See socket
... | EventletServer |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 31516,
"end": 32636
} | class ____(MeanMetricWrapper):
"""Computes how often targets are in the top `K` predictions.
Args:
k: (Optional) Number of top elements to look at for computing accuracy.
Defaults to 5.
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.
Stand... | TopKCategoricalAccuracy |
python | streamlit__streamlit | lib/streamlit/runtime/scriptrunner/script_cache.py | {
"start": 840,
"end": 2864
} | class ____:
"""Thread-safe cache of Python script bytecode."""
def __init__(self) -> None:
# Mapping of script_path: bytecode
self._cache: dict[str, Any] = {}
self._lock = threading.Lock()
def clear(self) -> None:
"""Remove all entries from the cache.
Notes
... | ScriptCache |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess23.py | {
"start": 650,
"end": 1271
} | class ____(metaclass=MyMeta):
@property
def attr2(self) -> int:
return 2
@property
def attr3(self) -> int:
return 3
@property
def attr4(self) -> int:
return 4
attr5 = "5"
reveal_type(A.attr1, expected_text="int")
reveal_type(A().attr2, expected_text="int")
reveal... | A |
python | google__pytype | pytype/rewrite/load_abstract_test.py | {
"start": 400,
"end": 1265
} | class ____(test_utils.ContextfulTestBase):
def test_class(self):
int_cls = self.ctx.abstract_loader.load_builtin('int')
self.assertIsInstance(int_cls, abstract.SimpleClass)
self.assertEqual(int_cls.name, 'int')
def test_function(self):
abs_func = self.ctx.abstract_loader.load_builtin('abs')
se... | LoadBuiltinTest |
python | gevent__gevent | src/gevent/tests/lock_tests.py | {
"start": 15645,
"end": 16003
} | class ____(BaseSemaphoreTests):
"""
Tests for bounded semaphores.
"""
def test_release_unacquired(self):
# Cannot go past the initial value
sem = self.semtype()
self.assertRaises(ValueError, sem.release)
sem.acquire()
sem.release()
self.assertRaises(Value... | BoundedSemaphoreTests |
python | getsentry__sentry | src/sentry/notifications/notification_action/issue_alert_registry/handlers/msteams_issue_alert_handler.py | {
"start": 283,
"end": 347
} | class ____(BaseIssueAlertHandler):
pass
| MSTeamsIssueAlertHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass15.py | {
"start": 247,
"end": 410
} | class ____:
children: "C"
def test(self):
for child in self.children:
reveal_type(child, expected_text="ClassB")
C = List[ClassB]
| ClassB |
python | mlflow__mlflow | mlflow/genai/judges/tools/base.py | {
"start": 422,
"end": 1499
} | class ____(ABC):
"""
Abstract base class for tools that can be used by MLflow judges.
Tools provide additional capabilities to judges for analyzing traces,
performing calculations, or accessing external data sources during evaluation.
"""
@property
@abstractmethod
def name(self) -> str... | JudgeTool |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 288,
"end": 1097
} | class ____(dg.ConfigurableIOManager):
def handle_output(self, context: dg.OutputContext, obj):
pass
def load_input(self, context: dg.InputContext):
pass
@dg.op
def produce_pandas_output():
return 1
def read_dataframe_from_table(*_args, **_kwargs):
pass
def write_dataframe_to_table... | TableIOManager |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 28781,
"end": 28891
} | class ____(BaseModel, extra="forbid"):
delete: "PointsSelector" = Field(..., description="")
| DeleteOperation |
python | huggingface__transformers | src/transformers/models/modernbert/modular_modernbert.py | {
"start": 70940,
"end": 77166
} | class ____(ModernBertPreTrainedModel):
def __init__(self, config: ModernBertConfig):
super().__init__(config)
self.config = config
self.model = ModernBertModel(config)
self.head = ModernBertPredictionHead(config)
self.drop = torch.nn.Dropout(config.classifier_dropout)
... | ModernBertForMultipleChoice |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol15.py | {
"start": 171,
"end": 307
} | class ____(Protocol):
@property
def f(self: T) -> T: ...
def m(self, item: T, callback: Callable[[T], str]) -> str: ...
| Proto |
python | pytorch__pytorch | test/dynamo/test_trace_rules.py | {
"start": 3454,
"end": 11171
} | class ____:
"""
Track the objects, object id - name pairs, and name - dynamo wrapping rule pairs
from the heuristic defined in `gen_allowed_objs_and_ids`.
"""
object_ids: dict[int, str]
c_binding_in_graph_functions: set[Any]
non_c_binding_in_graph_functions: set[Any]
name_rule_map: dict... | AllowedObjects |
python | doocs__leetcode | lcci/17.15.Longest Word/Solution.py | {
"start": 0,
"end": 482
} | class ____:
def longestWord(self, words: List[str]) -> str:
def dfs(w: str) -> bool:
if not w:
return True
for k in range(1, len(w) + 1):
if w[:k] in s and dfs(w[k:]):
return True
return False
s = set(words)
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/adapter.py | {
"start": 704,
"end": 14592
} | class ____(BaseAdapter):
"""The adapter class allows you to override various functionality of the
``allauth.socialaccount`` app. To do so, point ``settings.SOCIALACCOUNT_ADAPTER`` to
your own class that derives from ``DefaultSocialAccountAdapter`` and override the
behavior by altering the implementatio... | DefaultSocialAccountAdapter |
python | pytorch__pytorch | test/cpp/aoti_inference/compile_model.py | {
"start": 671,
"end": 2378
} | class ____(torch.nn.Module):
"""
a wrapper nn.Module that instantiates its forward method
on MyAOTIClass
"""
def __init__(self, lib_path, device):
super().__init__()
self.aoti_custom_op = torch.classes.aoti.MyAOTIClass(
lib_path,
device,
)
def fo... | MyAOTIModule |
python | getsentry__sentry | tests/relay_integration/lang/java/test_plugin.py | {
"start": 2559,
"end": 27652
} | class ____ : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
InnerClass().whoops()
val list = findViewById<RecyclerView>(R.id.list)
list.layoutManager = LinearLayoutManager(t... | MainActivity |
python | has2k1__plotnine | plotnine/geoms/geom_rect.py | {
"start": 416,
"end": 3717
} | class ____(geom):
"""
Rectangles
{usage}
Parameters
----------
{common_parameters}
"""
DEFAULT_AES = {
"color": None,
"fill": "#595959",
"linetype": "solid",
"size": 0.5,
"alpha": 1,
}
REQUIRED_AES = {"xmax", "xmin", "ymax", "ymin"}
... | geom_rect |
python | huggingface__transformers | utils/modular_integrations.py | {
"start": 6187,
"end": 6697
} | class ____(cst.CSTTransformer):
def __init__(self, relative_path: str, source_library: str):
super().__init__()
self.relative_path = relative_path
self.source_library = source_library
def leave_ImportFrom(self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom) -> cst.ImportFr... | AbsoluteImportTransformer |
python | PyCQA__pylint | doc/data/messages/t/too-many-ancestors/good.py | {
"start": 404,
"end": 562
} | class ____(Mammal):
beaver_tailed = True
can_swim = True
has_beak = True
lays_egg = True
protected_specie = True
venomous = True
| Playtypus |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/log.py | {
"start": 2928,
"end": 11780
} | class ____(logging.Handler):
def __init__(self, callback: StructuredLoggerCallback):
super().__init__()
self.callback = check.is_callable(callback, "callback")
def emit(self, record: logging.LogRecord) -> None:
try:
self.callback(
StructuredLoggerMessage(
... | StructuredLoggerHandler |
python | dagster-io__dagster | python_modules/libraries/dagstermill/dagstermill/manager.py | {
"start": 2789,
"end": 16235
} | class ____:
def __init__(self):
self.job = None
self.op_def: Optional[NodeDefinition] = None
self.in_job: bool = False
self.marshal_dir: Optional[str] = None
self.context = None
self.resource_manager = None
def _setup_resources(
self,
resource_def... | Manager |
python | catalyst-team__catalyst | catalyst/callbacks/scheduler.py | {
"start": 9202,
"end": 12331
} | class ____(ILRUpdater):
"""
Helps you find an optimal learning rate for a model, as per suggestion of
`Cyclical Learning Rates for Training Neural Networks`_ paper.
Learning rate is increased in linear or log scale, depending on user input.
See `How Do You Find A Good Learning Rate`_ article for de... | LRFinder |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/dynamic_ragged_shape.py | {
"start": 6905,
"end": 75115
} | class ____(extension_type.BatchableExtensionType):
"""The shape of a ragged or dense tensor.
Ragged shapes are encoded using two fields:
* `inner_shape`: An integer vector giving the shape of a dense tensor.
* `row_partitions`: A list of `RowPartition` objects, describing how
that flat shape should be par... | DynamicRaggedShape |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_null.py | {
"start": 874,
"end": 1436
} | class ____(ColumnMapMetricProvider):
condition_metric_name = "column_values.null"
filter_column_isnull = False
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.isnull()
@column_condition_partial(engine=SqlAlchemyExecutionEngine)
... | ColumnValuesNull |
python | facebook__pyre-check | tools/upgrade/filesystem.py | {
"start": 812,
"end": 908
} | class ____(NamedTuple):
name: str
strict: bool
pyre: bool
check_types: bool
| Target |
python | doocs__leetcode | solution/2600-2699/2653.Sliding Subarray Beauty/Solution2.py | {
"start": 0,
"end": 1685
} | class ____:
def __init__(self, x: int):
self.x = x
self.small = []
self.large = []
self.delayed = defaultdict(int)
self.small_size = 0
self.large_size = 0
def add_num(self, num: int):
if self.small_size < self.x or num <= -self.small[0]:
heapp... | MedianFinder |
python | mlflow__mlflow | tests/haystack/test_haystack_tracing.py | {
"start": 443,
"end": 532
} | class ____:
def run(self, a: int, b: int):
return {"sum": a + b}
@component
| Add |
python | falconry__falcon | falcon/inspect.py | {
"start": 13573,
"end": 14150
} | class ____(_Traversable):
"""Describes a middleware class.
Args:
name (str): The name of the middleware class.
source_info (str): The source path where the middleware was defined.
methods (list[MiddlewareMethodInfo]): List of method defined by the
middleware class.
"""
... | MiddlewareClassInfo |
python | dagster-io__dagster | scripts/run-pyright.py | {
"start": 3602,
"end": 3726
} | class ____(TypedDict):
file: str
message: str
severity: str
range: Range
rule: NotRequired[str]
| Diagnostic |
python | getsentry__sentry | src/sentry/models/releasefile.py | {
"start": 6880,
"end": 7739
} | class ____:
"""Holds data of artifact index and keeps track of changes"""
def __init__(self, data: dict, fresh=False):
self._data = data
self.changed = fresh
@property
def data(self):
"""Meant to be read-only"""
return self._data
@property
def num_files(self):
... | _ArtifactIndexData |
python | python__mypy | mypy/inspections.py | {
"start": 5284,
"end": 6147
} | class ____(ExtendedTraverserVisitor):
"""Visitor looking for all expressions whose spans enclose given position."""
def __init__(self, line: int, column: int) -> None:
self.line = line
self.column = column
self.result: list[Expression] = []
def visit(self, o: Node) -> bool:
... | SearchAllVisitor |
python | doocs__leetcode | solution/3300-3399/3375.Minimum Operations to Make Array Values Equal to K/Solution.py | {
"start": 0,
"end": 269
} | class ____:
def minOperations(self, nums: List[int], k: int) -> int:
s = set()
mi = inf
for x in nums:
if x < k:
return -1
mi = min(mi, x)
s.add(x)
return len(s) - int(k == mi)
| Solution |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 42505,
"end": 42863
} | class ____(TestNonLatin1HeaderFromApplication):
# Flip-flop of the superclass: Python 3 native string, Python 2 unicode object
header = u"\u1f4a3" # bomb in unicode
# Error both on py3 and py2. On py2, non-native string. On py3, native string
# that cannot be encoded to latin-1
should_error = True
... | TestNonLatin1UnicodeHeaderFromApplication |
python | Netflix__metaflow | metaflow/client/filecache.py | {
"start": 1059,
"end": 13947
} | class ____(object):
def __init__(self, cache_dir=None, max_size=None):
self._cache_dir = cache_dir
self._max_size = max_size
if self._cache_dir is None:
self._cache_dir = CLIENT_CACHE_PATH
if self._max_size is None:
self._max_size = int(CLIENT_CACHE_MAX_SIZE)
... | FileCache |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 21260,
"end": 22987
} | class ____(graphene.Interface):
id = graphene.NonNull(graphene.ID)
runId = graphene.NonNull(graphene.String)
# Nullable because of historical runs
pipelineSnapshotId = graphene.String()
repositoryOrigin = graphene.Field(GrapheneRepositoryOrigin)
status = graphene.NonNull(GrapheneRunStatus)
p... | GraphenePipelineRun |
python | kamyu104__LeetCode-Solutions | Python/split-message-based-on-limit.py | {
"start": 124,
"end": 843
} | class ____(object):
def splitMessage(self, message, limit):
"""
:type message: str
:type limit: int
:rtype: List[str]
"""
cnt, l, total, base = 1, 1, len(message)+1, 1
while 3+l*2 < limit:
if total+(3+l)*cnt <= limit*cnt:
break
... | Solution |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 7075,
"end": 7628
} | class ____(LocalizableStreamlitException):
"""Exception raised when no weights are specified, or a negative weight is specified."""
def __init__(self) -> None:
super().__init__(
"The `spec` argument to `st.columns` must be either a "
"positive integer (number of columns) or a li... | StreamlitInvalidColumnSpecError |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 43232,
"end": 45363
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter for deployments. Only deployments matching all criteria will be returned."""
id: Optional[DeploymentFilterId] = Field(
default=None, description="Filter criteria for `Deployment.id`"
)
name: Optional[DeploymentFilterName] = Field(
de... | DeploymentFilter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/plan.py | {
"start": 228,
"end": 655
} | class ____(CatalogModel):
add_ons: List[AddOn]
billing_day_of_month: Optional[Decimal]
billing_frequency: Decimal
created_at: datetime
currency_iso_code: str
description: str
discounts: List[Discount]
id: str
name: str
number_of_billing_cycles: Optional[Decimal]
price: Decima... | Plan |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 14300,
"end": 15026
} | class ____:
def __init__(
self,
target_collection: Optional[str],
uuids: UUIDS,
):
"""You should not initialise this class directly. Use the `.to_multi()` class methods instead."""
self.__target_collection = target_collection if target_collection else ""
self.__uu... | _Reference |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/barrier_ops_test.py | {
"start": 1086,
"end": 28110
} | class ____(test.TestCase):
def testConstructorWithShapes(self):
with ops.Graph().as_default():
b = data_flow_ops.Barrier(
(dtypes.float32, dtypes.float32),
shapes=((1, 2, 3), (8,)),
shared_name="B",
name="B")
self.assertTrue(isinstance(b.barrier_ref, tensor.Tenso... | BarrierTest |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 32432,
"end": 34054
} | class ____(Field):
"""
Layout object for rendering fields as uneditable in bootstrap.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
attrs : dict
Attributes to be applied to the field. These are converted into ht... | UneditableField |
python | realpython__materials | python-property/point_v3.py | {
"start": 50,
"end": 449
} | class ____:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@x.setter
def x(self, value):
raise WriteCoordinateError("x coordinate is read-only")
@property
def y(self):
return self._y
@y.setter
def y(... | Point |
python | pennersr__django-allauth | allauth/headless/account/views.py | {
"start": 2284,
"end": 3351
} | class ____(APIView):
input_class = ConfirmLoginCodeInput
def dispatch(self, request, *args, **kwargs):
auth_status = authkit.AuthenticationStatus(request)
self.stage = auth_status.get_pending_stage()
if not self.stage:
return ConflictResponse(request)
self.process = ... | ConfirmLoginCodeView |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 16579,
"end": 16689
} | class ____(nodes.reference):
"""Node for download references, similar to pending_xref."""
| download_reference |
python | eth-brownie__brownie | brownie/_cli/console.py | {
"start": 13217,
"end": 14155
} | class ____(Completer):
def __init__(self, console, local_dict: Dict[str, Any]) -> None:
self.console = console
self.locals = local_dict
super().__init__()
def get_completions(self, document, complete_event):
try:
text = "\n".join(self.console.buffer + [document.text]... | ConsoleCompleter |
python | pandas-dev__pandas | pandas/tests/series/methods/test_dropna.py | {
"start": 174,
"end": 3577
} | class ____:
def test_dropna_empty(self):
ser = Series([], dtype=object)
assert len(ser.dropna()) == 0
return_value = ser.dropna(inplace=True)
assert return_value is None
assert len(ser) == 0
# invalid axis
msg = "No axis named 1 for object type Series"
... | TestDropna |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 4741,
"end": 5502
} | class ____(FunctionPass):
_name = "rewrite_semantic_constants"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
This prunes dead branches, a dead branch is one which is derivable as
not taken at compile time purely based on const/literal evalua... | RewriteSemanticConstants |
python | neetcode-gh__leetcode | python/0057-insert-interval.py | {
"start": 0,
"end": 640
} | class ____:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
res = []
for i in range(len(intervals)):
if newInterval[1] < intervals[i][0]:
res.append(newInterval)
return res + intervals[i:]
... | Solution |
python | apache__avro | lang/py/avro/errors.py | {
"start": 1607,
"end": 1676
} | class ____(UserWarning):
"""Base class for warnings."""
| AvroWarning |
python | coleifer__peewee | tests/schema.py | {
"start": 516,
"end": 593
} | class ____(TestModel):
value = IntegerField(sequence='test_seq')
| TMSequence |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 113369,
"end": 117203
} | class ____(Request):
"""
Get user and system tags used for the specified projects and their children
:param include_system: If set to 'true' then the list of the system tags is also returned.
The default value is 'false'
:type include_system: bool
:param projects: The list of projects under... | GetProjectTagsRequest |
python | tensorflow__tensorflow | tensorflow/python/distribute/values.py | {
"start": 70637,
"end": 72095
} | class ____():
"""A per-worker CapturableResource class for non-ParameterServer strategy.
Resources that populate `host_to_resources` should be instances of classes
subclassing CapturableResource, although currently it's only used and tested
for StaticHashTable with TPUStrategy.
"""
def __init__(self, stra... | PerWorkerResource |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/relationships/tutorial001_py310.py | {
"start": 1034,
"end": 1185
} | class ____(SQLModel):
name: str | None = None
secret_name: str | None = None
age: int | None = None
team_id: int | None = None
| HeroUpdate |
python | kamyu104__LeetCode-Solutions | Python/check-if-a-string-can-break-another-string.py | {
"start": 692,
"end": 1001
} | class ____(object):
def checkIfCanBreak(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
return not {1, -1}.issubset(set(cmp(a, b) for a, b in itertools.izip(sorted(s1), sorted(s2))))
# Time: O(nlogn)
# Space: O(1)
import itertools
| Solution2 |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 73769,
"end": 76832
} | class ____(BaseValidator):
def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs):
super(CompoundValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
# Save element class string
self.data_class_str = data_clas... | CompoundValidator |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_sigma_utils.py | {
"start": 1787,
"end": 2706
} | class ____(SigmaComponent):
@cached_property
def organization_resource(self) -> MockSigmaOrganization:
return MockSigmaOrganization(**self.organization.model_dump())
def test_mock_sigma_organization() -> None:
"""Test that the mock Sigma organization returns the expected data."""
import asynci... | MockSigmaComponent |
python | pytorch__pytorch | torch/jit/_recursive.py | {
"start": 4426,
"end": 15545
} | class ____(torch._C._jit_tree_views.SourceRangeFactory):
pass
def get_annotations(obj):
# In Python-3.10+ it is recommended to use inspect.get_annotations
# See https://docs.python.org/3.10/howto/annotations.html
# But also, in 3.10 annotations from base class are not inherited
# by unannotated de... | SourceContext |
python | chroma-core__chroma | chromadb/db/base.py | {
"start": 397,
"end": 909
} | class ____(Protocol):
"""Reifies methods we use from a DBAPI2 Cursor since DBAPI2 is not typed."""
def execute(self, sql: str, params: Optional[Tuple[Any, ...]] = None) -> Self:
...
def executescript(self, script: str) -> Self:
...
def executemany(
self, sql: str, params: Opti... | Cursor |
python | lepture__authlib | authlib/oauth2/rfc7591/claims.py | {
"start": 206,
"end": 12169
} | class ____(BaseClaims):
# https://tools.ietf.org/html/rfc7591#section-2
REGISTERED_CLAIMS = [
"redirect_uris",
"token_endpoint_auth_method",
"grant_types",
"response_types",
"client_name",
"client_uri",
"logo_uri",
"scope",
"contacts",
... | ClientMetadataClaims |
python | django-haystack__django-haystack | test_haystack/elasticsearch7_tests/test_backend.py | {
"start": 1673,
"end": 1898
} | class ____(Elasticsearch7MockSearchIndex):
def prepare_text(self, obj):
if obj.author == "daniel3":
raise SkipDocument
return "Indexed!\n%s" % obj.id
| Elasticsearch7MockSearchIndexWithSkipDocument |
python | django__django | tests/gis_tests/geoapp/feeds.py | {
"start": 929,
"end": 1149
} | class ____(TestGeoRSS2):
feed_type = feeds.GeoAtom1Feed
def geometry(self, obj):
# This time we'll use a 2-tuple of coordinates for the box.
return ((-123.30, -41.32), (174.78, 48.46))
| TestGeoAtom2 |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/transform_reward.py | {
"start": 476,
"end": 1817
} | class ____(
gym.RewardWrapper[ObsType, ActType], gym.utils.RecordConstructorArgs
):
"""Applies a function to the ``reward`` received from the environment's ``step``.
A vector version of the wrapper exists :class:`gymnasium.wrappers.vector.TransformReward`.
Example:
>>> import gymnasium as gym
... | TransformReward |
python | getsentry__responses | responses/_recorder.py | {
"start": 3007,
"end": 5637
} | class ____(RequestsMock):
def __init__(
self,
*,
target: str = "requests.adapters.HTTPAdapter.send",
registry: "Type[FirstMatchRegistry]" = OrderedRegistry,
) -> None:
super().__init__(target=target, registry=registry)
def reset(self) -> None:
self._registry ... | Recorder |
python | huggingface__transformers | tests/models/qwen2_5_vl/test_modeling_qwen2_5_vl.py | {
"start": 1627,
"end": 6402
} | class ____:
def __init__(
self,
parent,
batch_size=3,
seq_length=7,
num_channels=3,
ignore_index=-100,
image_size=14,
bos_token_id=0,
eos_token_id=1,
pad_token_id=2,
hidden_act="silu",
hidden_size=32,
vocab_size=... | Qwen2_5_VLVisionText2TextModelTester |
python | sqlalchemy__sqlalchemy | test/sql/test_query.py | {
"start": 1241,
"end": 26291
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("u... | QueryTest |
python | streamlit__streamlit | lib/streamlit/web/server/oauth_authlib_routes.py | {
"start": 4629,
"end": 4794
} | class ____(AuthHandlerMixin, tornado.web.RequestHandler):
def get(self) -> None:
self.clear_auth_cookie()
self.redirect_to_base()
| AuthLogoutHandler |
python | django__django | tests/admin_changelist/models.py | {
"start": 1355,
"end": 1545
} | class ____(models.Model):
name = models.CharField(max_length=30)
members = models.ManyToManyField(Musician, through="Membership")
def __str__(self):
return self.name
| Group |
python | django__django | django/db/models/fields/json.py | {
"start": 19996,
"end": 21092
} | class ____(lookups.In):
def resolve_expression_parameter(self, compiler, connection, sql, param):
sql, params = super().resolve_expression_parameter(
compiler,
connection,
sql,
param,
)
if (
not hasattr(param, "as_sql")
... | KeyTransformIn |
python | doocs__leetcode | solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/Solution.py | {
"start": 0,
"end": 420
} | class ____:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
left = [0] * (n + 1)
right = [0] * (n + 1)
for i, x in enumerate(nums, 1):
if x:
left[i] = left[i - 1] + 1
for i in range(n - 1, -1, -1):
if nums[i]:
... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image56.py | {
"start": 315,
"end": 841
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image56.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | python__mypy | mypy/types.py | {
"start": 146686,
"end": 147295
} | class ____(BoolTypeQuery):
"""Visitor for querying whether a type has a type variable component."""
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
self.skip_alias_target = True
def visit_type_var(self, t: TypeVarType) -> bool:
return True
def visit_type_var_tuple(s... | HasTypeVars |
python | ipython__ipython | tests/test_interactiveshell.py | {
"start": 34563,
"end": 35774
} | class ____(unittest.TestCase):
def test_warning_suppression(self):
ip.run_cell("import warnings")
try:
with self.assertWarnsRegex(UserWarning, "asdf"):
ip.run_cell("warnings.warn('asdf')")
# Here's the real test -- if we run that again, we should get the
... | TestWarningSuppression |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.