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 | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 110304,
"end": 110732
} | class ____(FunctorchHigherOrderVariable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def call_function(
self, tx, args: list[VariableTracker], kwargs: dict[str, VariableTracker]
) -> VariableTracker:
ctx_manager_vt = super().call_function(tx, args, kwargs... | ReparametrizeModuleCallVariable |
python | celery__celery | t/unit/worker/test_request.py | {
"start": 45923,
"end": 52401
} | class ____(RequestCase):
def setup_method(self):
self.task = Mock(name='task')
self.pool = Mock(name='pool')
self.eventer = Mock(name='eventer')
super().setup_method()
def create_request_cls(self, **kwargs):
return create_request_cls(
Request, self.task, sel... | test_create_request_class |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 8767,
"end": 10833
} | class ____(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
... | BaseModelOutputWithCrossAttentions |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 465,
"end": 2802
} | class ____(Exception):
"""This class defines the response generated when a pandas DF fails validation -- it can be used to generate either a
failed typecheck or an exception.
Args:
constraint_name (str): the name of the violated constraint
constraint_description (Optional[str]): the descri... | ConstraintWithMetadataException |
python | huggingface__transformers | src/transformers/quantizers/quantizer_awq.py | {
"start": 1040,
"end": 7401
} | class ____(HfQuantizer):
"""
4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://huggingface.co/papers/2306.00978)
"""
# AWQ requires data calibration - we support only inference
requires_calibration = True
required_packages = ["awq", "accelerate"]
def __init__(self,... | AwqQuantizer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self9.py | {
"start": 207,
"end": 618
} | class ____(ParentA):
b: int
@classmethod
def method1(cls) -> None:
reveal_type(cls.a, expected_text="list[Self@ChildA]")
reveal_type(cls.a[0], expected_text="Self@ChildA")
print(cls.a[0].b)
def method2(self) -> None:
reveal_type(self.a, expected_text="list[Self@ChildA]"... | ChildA |
python | pytorch__pytorch | torchgen/dest/lazy_ir.py | {
"start": 12516,
"end": 14749
} | class ____(GenLazyIR):
def lowering_function(self, schema: LazyIrSchema) -> str:
signature = """
torch::lazy::TSOpVector Lower(
std::shared_ptr<torch::jit::GraphFunction> function,
torch::lazy::TSLoweringContext* loctx) const override"""
if schema.properties.LowerDeclOnly:
... | GenTSLazyIR |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 28530,
"end": 28626
} | class ____(_base.CheckMixin, watcher):
_watcher_callback_name = '_gevent_check_callback0'
| check |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_subprojects.py | {
"start": 253,
"end": 10346
} | class ____(TestCase):
def setUp(self):
self.user = fixture.get(User)
self.project = fixture.get(Project, users=[self.user])
self.subproject = fixture.get(Project, users=[self.user])
self.project.add_subproject(self.subproject, "subproject")
self.relation = self.subproject.sup... | SubprojectFormTests |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 16335,
"end": 17195
} | class ____(Node):
__slots__ = ('loc', 'name', 'value',)
_fields = ('name', 'value',)
def __init__(self, name, value, loc=None):
self.loc = loc
self.name = name
self.value = value
def __eq__(self, other):
return (
self is other or (
isinstance... | ObjectField |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/atrous_convolution_test.py | {
"start": 2171,
"end": 11413
} | class ____(test.TestCase):
@contextlib.contextmanager
def _delay_checks(self):
"""Context manager for combining checks depending on tensor evaluations.
Each call to Session.run has some overhead, and this overhead can easily
account for the majority of the time spent in tests that call Session.run
... | AtrousConvolutionTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 26665,
"end": 27667
} | class ____(AbstractTemplate):
def _unify_minmax(self, tys):
for ty in tys:
if not isinstance(ty, (types.Number, types.NPDatetime, types.NPTimedelta)):
return
return self.context.unify_types(*tys)
def generic(self, args, kws):
"""
Resolve a min() or m... | MinMaxBase |
python | walkccc__LeetCode | solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py | {
"start": 94,
"end": 854
} | class ____:
def __init__(self, maxBit: int):
self.maxBit = maxBit
self.root = TrieNode()
def insert(self, num: int) -> None:
node = self.root
for i in range(self.maxBit, -1, -1):
bit = num >> i & 1
if not node.children[bit]:
node.children[bit] = TrieNode()
node = node.chil... | BitTrie |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 8189,
"end": 10133
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.static_encodings'
# XXX webtest actually runs response.decode_content() and so we can't
# use it to test gzip- or deflate-encoded responses to see if they
# were transferred correctly
def _getResponse(self, *args, **kwargs):
... | TestStaticAppWithEncodings |
python | walkccc__LeetCode | solutions/2302. Count Subarrays With Score Less Than K/2302.py | {
"start": 0,
"end": 280
} | class ____:
def countSubarrays(self, nums: list[int], k: int) -> int:
ans = 0
summ = 0
l = 0
for r, num in enumerate(nums):
summ += num
while summ * (r - l + 1) >= k:
summ -= nums[l]
l += 1
ans += r - l + 1
return ans
| Solution |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_select_column_values_to_be_unique_within_record.py | {
"start": 2256,
"end": 14806
} | class ____(MulticolumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectSelectColumnValuesToBeUniqueWithinRecord is a \
Multicolumn Map Expectation.
Multicolumn Map Expectations are evaluated for a set of columns and ask a yes/no question about the row-wise relationship between thos... | ExpectSelectColumnValuesToBeUniqueWithinRecord |
python | huggingface__transformers | src/transformers/models/sam3_video/processing_sam3_video.py | {
"start": 1057,
"end": 18809
} | class ____(ProcessorMixin):
r"""
Constructs a SAM3 processor which wraps a SAM3 image processor and an 2D points & Bounding boxes processor into a
single processor.
[`Sam3Processor`] offers all the functionalities of [`Sam3ImageProcessor`] and [`Sam3VideoProcessor`]. See the docstring of
[`~Sam3Ima... | Sam3VideoProcessor |
python | openai__openai-python | src/openai/types/graders/text_similarity_grader_param.py | {
"start": 225,
"end": 1045
} | class ____(TypedDict, total=False):
evaluation_metric: Required[
Literal[
"cosine",
"fuzzy_match",
"bleu",
"gleu",
"meteor",
"rouge_1",
"rouge_2",
"rouge_3",
"rouge_4",
"rouge_5",
... | TextSimilarityGraderParam |
python | pyca__cryptography | tests/utils.py | {
"start": 30796,
"end": 32183
} | class ____:
def __init__(self, testfiledata, testgroup, testcase):
self.testfiledata = testfiledata
self.testgroup = testgroup
self.testcase = testcase
def __repr__(self):
return "<WycheproofTest({!r}, {!r}, {!r}, tcId={})>".format(
self.testfiledata,
sel... | WycheproofTest |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 82786,
"end": 83706
} | class ____:
# Base halide target to use for CPU devices
cpu_target = "host"
# Base halide target to use for CUDA devices
gpu_target = "host-cuda"
# Halide autoscheduler to use, choices are:
# "Anderson2021" (gpu-only), "Li2018", "Adams2019" (cpu-only), or "Mullapudi2016" (cpu-only)
schedul... | halide |
python | scrapy__scrapy | scrapy/core/http2/agent.py | {
"start": 4087,
"end": 5570
} | class ____:
def __init__(
self,
reactor: ReactorBase,
pool: H2ConnectionPool,
context_factory: BrowserLikePolicyForHTTPS = BrowserLikePolicyForHTTPS(),
connect_timeout: float | None = None,
bind_address: bytes | None = None,
) -> None:
self._reactor = reac... | H2Agent |
python | walkccc__LeetCode | solutions/2284. Sender With Largest Word Count/2284.py | {
"start": 0,
"end": 563
} | class ____:
def largestWordCount(self, messages: list[str], senders: list[str]) -> str:
n = len(messages)
ans = ''
maxWordsSent = 0
count = collections.Counter() # [sender, # Words sent]
for message, sender in zip(messages, senders):
wordsCount = message.count(' ') + 1
count[sender] ... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-tableau/dagster_tableau/resources.py | {
"start": 18464,
"end": 19329
} | class ____(BaseTableauClient):
"""Represents a client for Tableau Cloud and provides utilities
to interact with the Tableau API.
"""
def __init__(
self,
connected_app_client_id: str,
connected_app_secret_id: str,
connected_app_secret_value: str,
username: str,
... | TableauCloudClient |
python | pytorch__pytorch | torch/_inductor/cache.py | {
"start": 14046,
"end": 14823
} | class ____(OnDiskCache[Key, Value]):
"""
Inductor-specific on-disk cache implementation.
Uses a custom base directory for Inductor cache files.
"""
def __init__(self: Self) -> None:
"""
Initialize an inductor on-disk cache instance.
Sets the cache directory name to "inductor... | InductorOnDiskCache |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 4803,
"end": 4912
} | class ____(UrlError):
code = 'url.scheme'
msg_template = 'invalid or missing URL scheme'
| UrlSchemeError |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 144563,
"end": 145369
} | class ____(OutputSpec):
# This is janky, I figured out what fields to populate by just running
# the model I was interested in and adding properties/methods as needed.
# This doesn't inherit from Layout because Layout assumes you have stuff
# like sizes, but I don't really have anything here.
#
... | NoneLayout |
python | FactoryBoy__factory_boy | tests/test_helpers.py | {
"start": 108,
"end": 1980
} | class ____(unittest.TestCase):
"""Tests for the 'factory.debug()' helper."""
def test_default_logger(self):
stream1 = io.StringIO()
stream2 = io.StringIO()
logger = logging.getLogger('factory.test')
h = logging.StreamHandler(stream1)
h.setLevel(logging.INFO)
log... | DebugTest |
python | Textualize__textual | src/textual/css/tokenizer.py | {
"start": 2994,
"end": 3114
} | class ____(TokenError):
"""Indicates that the text being tokenized ended prematurely."""
@rich.repr.auto
| UnexpectedEnd |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 12096,
"end": 12538
} | class ____(SerializedAttributes.with_attributes(
'ModelAttributes',
copy_from=[LayerAttributes])):
"""Model checkpointable objects + functions that are saved to the SavedModel.
List of all attributes:
All attributes from LayerAttributes (including CommonEndpoints)
"""
# TODO(kathywu): Add attribute... | ModelAttributes |
python | python-visualization__folium | folium/map.py | {
"start": 15681,
"end": 18804
} | class ____(MacroElement):
"""Create a Popup instance that can be linked to a Layer.
Parameters
----------
html: string or Element
Content of the Popup.
parse_html: bool, default False
True if the popup is a template that needs to the rendered first.
max_width: int for pixels or ... | Popup |
python | scrapy__scrapy | scrapy/extensions/corestats.py | {
"start": 430,
"end": 2248
} | class ____:
def __init__(self, stats: StatsCollector):
self.stats: StatsCollector = stats
self.start_time: datetime | None = None
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
assert crawler.stats
o = cls(crawler.stats)
crawler.signals.connect(o.spide... | CoreStats |
python | astropy__astropy | astropy/io/ascii/__init__.py | {
"start": 1341,
"end": 1930
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.ascii`.
"""
guess_limit_lines = _config.ConfigItem(
10000,
"When guessing the format of a table, this is the number of lines that "
"will be used for initial guessing. If the reading succeeds based... | Conf |
python | agronholm__apscheduler | src/apscheduler/abc.py | {
"start": 1621,
"end": 2565
} | class ____(metaclass=ABCMeta):
"""Interface for classes that implement (de)serialization."""
__slots__ = ()
@abstractmethod
def serialize(self, obj: object) -> bytes:
"""
Turn the given object into a bytestring.
Must handle the serialization of at least any JSON type, plus the... | Serializer |
python | pyca__cryptography | src/cryptography/hazmat/decrepit/ciphers/algorithms.py | {
"start": 1097,
"end": 1387
} | class ____(BlockCipherAlgorithm):
name = "Blowfish"
block_size = 64
key_sizes = frozenset(range(32, 449, 8))
def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
@property
def key_size(self) -> int:
return len(self.key) * 8
| Blowfish |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py | {
"start": 2837,
"end": 4490
} | class ____(wx.App):
def OnInit(self):
xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc',
asfileobj=False)
print('loading', xrcfile)
self.res = xrc.XmlResource(xrcfile)
# main frame and panel ---------
self.frame = self.res.LoadF... | MyApp |
python | pallets__click | tests/test_options.py | {
"start": 57046,
"end": 57141
} | class ____(enum.Flag):
RED = enum.auto()
GREEN = enum.auto()
BLUE = enum.auto()
| Color |
python | milvus-io__pymilvus | pymilvus/client/abstract.py | {
"start": 7480,
"end": 11160
} | class ____:
def __init__(self, raw: Any):
self._raw = raw
self.collection_name = None
self.description = None
self.params = {}
self.fields = []
self.struct_array_fields = []
self.functions = []
self.statistics = {}
self.auto_id = False # auto... | CollectionSchema |
python | PrefectHQ__prefect | tests/test_serializers.py | {
"start": 1493,
"end": 3558
} | class ____:
@pytest.fixture(autouse=True)
def restore_dispatch_registry(self):
# Clears serializers defined in tests below to prevent warnings on collision
before = get_registry_for_type(Serializer).copy()
yield
registry = get_registry_for_type(Serializer)
registry.clea... | TestBaseSerializer |
python | dask__distributed | distributed/shuffle/_scheduler_plugin.py | {
"start": 1058,
"end": 23114
} | class ____(SchedulerPlugin):
"""
Shuffle plugin for the scheduler
This coordinates the individual worker plugins to ensure correctness
and collects heartbeat messages for the dashboard.
See Also
--------
ShuffleWorkerPlugin
"""
scheduler: Scheduler
active_shuffles: dict[ShuffleI... | ShuffleSchedulerPlugin |
python | urllib3__urllib3 | test/with_dummyserver/test_proxy_poolmanager.py | {
"start": 1571,
"end": 27215
} | class ____(HypercornDummyProxyTestCase):
@classmethod
def setup_class(cls) -> None:
super().setup_class()
cls.http_url = f"http://{cls.http_host}:{int(cls.http_port)}"
cls.http_url_alt = f"http://{cls.http_host_alt}:{int(cls.http_port)}"
cls.https_url = f"https://{cls.https_host}... | TestHTTPProxyManager |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 89569,
"end": 90866
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(
self,
name: str,
keyspace: str,
username: str,
password: str,
address: str,
port: int,
replication: Optional[int] = None,
):
"""Airbyte Destination for Scylla.
Docu... | ScyllaDestination |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/sources.py | {
"start": 2139,
"end": 28364
} | class ____:
"""
Contains methods to interact with data sources from the gx context
This contains a collection of dynamically generated datasource factory methods in the format
`.add_<TYPE_NAME>()`.
It also contains general data source manipulation methods such as `all()`, `get()` and
`delete()... | DataSourceManager |
python | spyder-ide__spyder | spyder/api/widgets/comboboxes.py | {
"start": 7868,
"end": 11220
} | class ____(_SpyderComboBoxMixin, QComboBox):
"""Default combobox widget for Spyder."""
def __init__(self, parent=None, items_elide_mode=None):
"""
Default combobox widget for Spyder.
Parameters
----------
parent: QWidget, optional
The combobox parent.
... | SpyderComboBox |
python | walkccc__LeetCode | solutions/1258. Synonymous Sentences/1258.py | {
"start": 41,
"end": 686
} | class ____:
def generateSentences(
self,
synonyms: list[list[str]],
text: str,
) -> list[str]:
ans = SortedSet()
graph = collections.defaultdict(list)
q = collections.deque([text])
for s, t in synonyms:
graph[s].append(t)
graph[t].append(s)
while q:
u = q.po... | Solution |
python | pytorch__pytorch | test/inductor/test_max_autotune.py | {
"start": 109219,
"end": 110956
} | class ____(TestCase):
def check_healthy(self, p: TuningProcess, device: Optional[int] = None):
result = random.random()
bmreq = _TestBenchmarkRequest(result, device=device)
p.put(bmreq.benchmark)
self.assertEqual(p.get(), result)
def test_tuning_subproc_timeout(self):
p ... | TestTuningProcess |
python | pytorch__pytorch | test/dynamo/test_global.py | {
"start": 242,
"end": 700
} | class ____: # noqa: B903
def __init__(self, x, y):
self.x = x
self.y = y
def Foo():
return Pair(1, 1)
g_counter = 1
g_list = [0, 1, 2]
g_dict = {"a": 0, "b": 1}
g_object = Foo()
g_tensor = torch.zeros(10)
_name: int = 0
def fresh_name() -> str:
"""create a new unique name for a vari... | Pair |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 48117,
"end": 53504
} | class ____:
def exists(self) -> bool:
"Does this table or view exist yet?"
return False
def __init__(self, db, name):
self.db = db
self.name = name
def count_where(
self,
where: Optional[str] = None,
where_args: Optional[Union[Iterable, dict]] = None... | Queryable |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/fingerprint_op_test.py | {
"start": 965,
"end": 1590
} | class ____(test.TestCase):
def test_default_values(self):
data = np.arange(10)
data = np.expand_dims(data, axis=0)
fingerprint0 = self.evaluate(array_ops.fingerprint(data))
fingerprint1 = self.evaluate(array_ops.fingerprint(data[:, 1:]))
self.assertEqual(fingerprint0.ndim, 2)
self.assertTuple... | FingerprintTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property1.py | {
"start": 1794,
"end": 1914
} | class ____(ClassC):
def method1(self) -> None:
reveal_type(self.prop1, expected_text="type[Self@ClassD]")
| ClassD |
python | explosion__spaCy | spacy/schemas.py | {
"start": 8362,
"end": 9577
} | class ____(BaseModel):
REGEX: Optional[StrictStr] = Field(None, alias="regex")
IN: Optional[List[StrictInt]] = Field(None, alias="in")
NOT_IN: Optional[List[StrictInt]] = Field(None, alias="not_in")
IS_SUBSET: Optional[List[StrictInt]] = Field(None, alias="is_subset")
IS_SUPERSET: Optional[List[Stri... | TokenPatternNumber |
python | ansible__ansible | lib/ansible/_internal/_templating/_lazy_containers.py | {
"start": 2645,
"end": 2844
} | class ____:
"""Intermediate value source for lazy-eligible collection copy operations."""
source: t.Iterable
templar: TemplateEngine
lazy_options: LazyOptions
@t.final
| _LazyValueSource |
python | getsentry__sentry | src/sentry/identity/google/provider.py | {
"start": 571,
"end": 2384
} | class ____(OAuth2Provider):
key = "google"
name = "Google"
oauth_access_token_url = "https://www.googleapis.com/oauth2/v4/token"
oauth_authorize_url = "https://accounts.google.com/o/oauth2/auth"
oauth_scopes = ("email",)
def get_oauth_client_id(self):
return options.get("auth-google.c... | GoogleIdentityProvider |
python | optuna__optuna | optuna/_imports.py | {
"start": 335,
"end": 3349
} | class ____:
"""Context manager to defer exceptions from imports.
Catches :exc:`ImportError` and :exc:`SyntaxError`.
If any exception is caught, this class raises an :exc:`ImportError` when being checked.
"""
def __init__(self) -> None:
self._deferred: tuple[Exception, str] | None = None
... | _DeferredImportExceptionContextManager |
python | apache__airflow | providers/opensearch/tests/unit/opensearch/operators/test_opensearch.py | {
"start": 3203,
"end": 4530
} | class ____:
def setup_method(self, dag_setup):
self.dag = dag_setup
self.open_search = OpenSearchAddDocumentOperator(
task_id="test_opensearch_doc_operator",
index_name="test_index",
document={"title": "Monty Python"},
doc_id=1,
)
sel... | TestOpenSearchAddDocumentOperator |
python | google__pytype | pytype/pytd/pytd_utils.py | {
"start": 9959,
"end": 12788
} | class ____(dict):
"""A simple ordered set."""
def __init__(self, iterable=None):
super().__init__((item, None) for item in (iterable or []))
def add(self, item):
self[item] = None
def ASTeq(ast1: pytd.TypeDeclUnit, ast2: pytd.TypeDeclUnit):
# pytd.TypeDeclUnit does equality by ID, so we need a helpe... | OrderedSet |
python | mlflow__mlflow | mlflow/llama_index/pyfunc_wrapper.py | {
"start": 6098,
"end": 12686
} | class ____(_LlamaIndexModelWrapperBase):
@property
def index(self):
raise NotImplementedError("LlamaIndex Workflow does not have an index")
@property
def engine_type(self):
raise NotImplementedError("LlamaIndex Workflow is not an engine")
def predict(self, data, params: dict[str, A... | WorkflowWrapper |
python | pypa__setuptools | setuptools/_distutils/tests/test_install.py | {
"start": 711,
"end": 8618
} | class ____(
support.TempdirManager,
):
@pytest.mark.xfail(
'platform.system() == "Windows" and sys.version_info > (3, 11)',
reason="pypa/distutils#148",
)
def test_home_installation_scheme(self):
# This ensure two things:
# - that --home generates the desired set of direc... | TestInstall |
python | milvus-io__pymilvus | tests/test_async_milvus_client.py | {
"start": 317,
"end": 12330
} | class ____:
"""Test cases for newly added features in AsyncMilvusClient"""
def test_get_server_type(self):
"""Test get_server_type returns correct value"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connect... | TestAsyncMilvusClientNewFeatures |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/setter.py | {
"start": 0,
"end": 301
} | class ____:
@property
def foo(self) -> str:
"""Docstring for foo."""
return "foo"
@foo.setter
def foo(self, value: str) -> None:
pass
@foo.deleter
def foo(self):
pass
@foo
def foo(self, value: str) -> None:
pass
| PropertyWithSetter |
python | matplotlib__matplotlib | lib/matplotlib/projections/polar.py | {
"start": 17495,
"end": 19003
} | class ____(mtransforms.ScaledTranslation):
"""
Apply a padding shift based on axes theta limits.
This is used to create padding for radial ticks.
Parameters
----------
axes : `~matplotlib.axes.Axes`
The owning Axes; used to determine limits.
pad : float
The padding to apply... | _ThetaShift |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 12702,
"end": 13713
} | class ____(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
Version.objects.get_for_object(obj)[1].revert()
obj.refresh... | RevertTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py | {
"start": 7105,
"end": 8630
} | class ____(EcsBaseTestCase):
@pytest.mark.parametrize(
("return_state", "expected"), [("ACTIVE", True), ("INACTIVE", False), ("DELETE_IN_PROGRESS", False)]
)
def test_default_values_poke(self, return_state, expected):
task = self.create_rendered_task(
EcsTaskDefinitionStateSensor... | TestEcsTaskDefinitionStateSensor |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_discovery_api.py | {
"start": 1004,
"end": 6178
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="google_test",
conn_type="google_cloud_platform",
host="google",
schema="refr... | TestGoogleDiscoveryApiHook |
python | FactoryBoy__factory_boy | tests/test_transformer.py | {
"start": 2449,
"end": 2682
} | class ____(factory.Factory):
class Meta:
model = TestObject
one = factory.Transformer("", transform=str.upper)
two = factory.Transformer(factory.Sequence(int), transform=lambda n: n ** 2)
| TransformDeclarationFactory |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 76374,
"end": 79331
} | class ____(VariableTracker):
"""
Used to represent a wrapper object that contains the actual callable as an
attribute. For example, torch.jit.script/trace have the original function at
their _torchdynamo_inline attribute. Similarly, functions with
__script_if_tracing_wrapper have the original attr a... | WrapperUserFunctionVariable |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 4330,
"end": 4454
} | class ____(ExpressionElementRole[_T]):
__slots__ = ()
_role_name = "Constant True/False/None expression"
| ConstExprRole |
python | django__django | django/db/models/expressions.py | {
"start": 5223,
"end": 16888
} | class ____:
"""Base class for all query expressions."""
empty_result_set_value = NotImplemented
# aggregate specific fields
is_summary = False
# Can the expression be used in a WHERE clause?
filterable = True
# Can the expression be used as a source expression in Window?
window_compatib... | BaseExpression |
python | numba__numba | numba/cuda/dispatcher.py | {
"start": 19839,
"end": 20356
} | class ____(CacheImpl):
def reduce(self, kernel):
return kernel._reduce_states()
def rebuild(self, target_context, payload):
return _Kernel._rebuild(**payload)
def check_cachable(self, cres):
# CUDA Kernels are always cachable - the reasons for an entity not to
# be cachable... | CUDACacheImpl |
python | huggingface__transformers | src/transformers/models/marian/modeling_marian.py | {
"start": 2461,
"end": 5173
} | class ____(nn.Embedding):
"""This module produces sinusoidal positional embeddings of any length."""
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
super().__init__(num_positions, embedding_dim, _freeze=True)
def create_weight(self):
... | MarianSinusoidalPositionalEmbedding |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_member_team_details.py | {
"start": 3414,
"end": 7320
} | class ____(OrganizationMemberTeamTestBase):
method = "post"
def test_manager_can_join_team(self) -> None:
self.login_as(self.manager)
self.get_success_response(
self.org.slug, self.manager.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert Organization... | CreateOrganizationMemberTeamTest |
python | ray-project__ray | python/ray/serve/exceptions.py | {
"start": 917,
"end": 1355
} | class ____(RayServeException, TaskCancelledError):
"""Raise when a Serve request is cancelled."""
def __init__(self, request_id: Optional[str] = None):
self._request_id: Optional[str] = request_id
def __str__(self):
if self._request_id:
return f"Request {self._request_id} was c... | RequestCancelledError |
python | tensorflow__tensorflow | tensorflow/tools/proto_splitter/split_test.py | {
"start": 4858,
"end": 4942
} | class ____(split.ComposableSplitter):
def build_chunks(self):
pass
| NoOpSplitter |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 103017,
"end": 103720
} | class ____:
"""Test pl_PL address provider methods"""
def test_postcode(self, faker, num_samples):
for _ in range(num_samples):
postcode = faker.postcode()
match = re.findall(r"^\d{2}-\d{3}$", postcode)
assert match
def test_zipcode(self, faker, num_samples):
... | TestPlPl |
python | scipy__scipy | scipy/_lib/_sparse.py | {
"start": 59,
"end": 875
} | class ____(ABC):
pass
def issparse(x):
"""Is `x` of a sparse array or sparse matrix type?
Parameters
----------
x
object to check for being a sparse array or sparse matrix
Returns
-------
bool
True if `x` is a sparse array or a sparse matrix, False otherwise
Note... | SparseABC |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-baiduvectordb/llama_index/vector_stores/baiduvectordb/base.py | {
"start": 1688,
"end": 1910
} | class ____:
name: str
data_type: str = "STRING"
def __init__(self, name: str, data_type: str = "STRING"):
self.name = name
self.data_type = "STRING" if data_type is None else data_type
| TableField |
python | mlflow__mlflow | tests/dspy/test_save.py | {
"start": 1046,
"end": 1263
} | class ____(dspy.Module):
def __init__(self):
super().__init__()
self.prog = dspy.ChainOfThought("question -> answer")
def forward(self, question):
return self.prog(question=question)
| CoT |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_twodim_base.py | {
"start": 17260,
"end": 17543
} | class ____(TestCase):
def test_exceptions(self):
assert_raises(ValueError, triu_indices_from, np.ones((2,)))
assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
# assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
| TestTriuIndicesFrom |
python | pytorch__pytorch | test/nn/test_pooling.py | {
"start": 1211,
"end": 6540
} | class ____(TestCase):
def _sum_pool2d(self, x, kernel_size):
windows = torch.nn.functional.unfold(
x, kernel_size=kernel_size, stride=kernel_size
)
return torch.sum(windows, dim=1)
def _sum_pool3d(self, x, kernel_size):
# Because unfold does not support 3D sliding wi... | TestAvgPool |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 1153,
"end": 1213
} | class ____(ParentC):
def __init__(self):
pass
| ChildE |
python | apache__airflow | airflow-core/src/airflow/jobs/triggerer_job_runner.py | {
"start": 28056,
"end": 28230
} | class ____(TypedDict):
"""Type class for the trigger details dictionary."""
task: asyncio.Task
name: str
events: int
@attrs.define(kw_only=True)
| TriggerDetails |
python | ansible__ansible | test/lib/ansible_test/_internal/python_requirements.py | {
"start": 2409,
"end": 2528
} | class ____(PipCommand):
"""Details required to get the pip version."""
@dataclasses.dataclass(frozen=True)
| PipVersion |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_diff_less_than_threshold.py | {
"start": 5506,
"end": 12631
} | class ____(ProfileNumericColumnsDiffExpectation):
"""Expect a statistic's value for a given column of a DataProfiler difference report to be less than the specified threshold.
This expectation takes the difference report between the data it is called on and a DataProfiler profile of the same schema loaded from... | ExpectProfileNumericColumnsDiffLessThanThreshold |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 10035,
"end": 10215
} | class ____(WorkspaceImportApp):
version = version
@default("workspaces_dir")
def _default_workspaces_dir(self):
return get_workspaces_dir()
| LabWorkspaceImportApp |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_aliases.py | {
"start": 1433,
"end": 3264
} | class ____:
def test_valid(self) -> None:
prop = bcpc.CoordinateLike()
assert prop.is_valid(-1.0)
assert prop.is_valid(-1)
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(0.0)
assert prop.is_valid(1.0)
assert prop.is_valid("2020-01... | Test_CoordinateLike |
python | python__mypy | mypy/nodes.py | {
"start": 64186,
"end": 64622
} | class ____(Expression):
"""Integer literal"""
__slots__ = ("value",)
__match_args__ = ("value",)
value: int # 0 by default
def __init__(self, value: int) -> None:
super().__init__()
self.value = value
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visi... | IntExpr |
python | pydata__xarray | xarray/tests/test_datatree_mapping.py | {
"start": 7941,
"end": 9631
} | class ____:
def test_construct_using_type(self):
# from datatree GH issue https://github.com/xarray-contrib/datatree/issues/188
# xarray's .weighted is unusual because it uses type() to create a Dataset/DataArray
a = xr.DataArray(
np.random.rand(3, 4, 10),
dims=["x",... | TestMutableOperations |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_watch_grpc_server.py | {
"start": 503,
"end": 1473
} | class ____(BaseTestSuite):
def test_grpc_server_handle_message_subscription(self, graphql_context):
events = []
test_subscriber = LocationStateSubscriber(events.append)
location = next(
iter(graphql_context.process_context.create_request_context().code_locations)
)
... | TestSubscribeToGrpcServerEvents |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 15950,
"end": 16974
} | class ____(abc.ABC, Generic[_T_partition_id]):
id: ShuffleId
disk: bool
@property
@abc.abstractmethod
def output_partitions(self) -> Generator[_T_partition_id]:
"""Output partitions"""
@abc.abstractmethod
def pick_worker(self, partition: _T_partition_id, workers: Sequence[str]) -> ... | ShuffleSpec |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 11121,
"end": 11336
} | class ____(Where):
"""Contains comparison for document content"""
key: str
content: str
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$contains": self.content}}
@dataclass
| Contains |
python | pytorch__pytorch | torch/utils/_debug_mode.py | {
"start": 10553,
"end": 12871
} | class ____(_DebugCall):
"""Normal operator call"""
def __init__(
self,
op,
args: tuple,
kwargs: dict,
call_depth: int,
stack: bool = False,
) -> None:
super().__init__(call_depth, stack=stack)
self.op = op
self.args = args
self... | _OpCall |
python | wandb__wandb | wandb/automations/events.py | {
"start": 6980,
"end": 7840
} | class ____(GQLBase):
event_type: EventType
scope: AutomationScope
"""The scope of the event."""
filter: JsonEncoded[Any]
def then(self, action: InputAction) -> NewAutomation:
"""Define a new Automation in which this event triggers the given action."""
from .automations import NewA... | _BaseEventInput |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py | {
"start": 2024,
"end": 2307
} | class ____(graphene.ObjectType):
partitionKeysOrError = graphene.Field(GraphenePartitionKeysOrError)
evaluationData = graphene.Field(GrapheneAutoMaterializeRuleEvaluationData)
class Meta:
name = "AutoMaterializeRuleEvaluation"
| GrapheneAutoMaterializeRuleEvaluation |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/common.py | {
"start": 5612,
"end": 6478
} | class ____(ABC):
"""Abstract base class for benchmarks of estimators implementing predict"""
if Benchmark.bench_predict:
def time_predict(self, *args):
self.estimator.predict(self.X)
def peakmem_predict(self, *args):
self.estimator.predict(self.X)
if Benchmark... | Predictor |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchaudio_models.py | {
"start": 4176,
"end": 4844
} | class ____(nn.Module):
def __init__(self, module):
"""
Collapses input of dim T*N*H to (T*N)*H, and applies to a module.
Allows handling of variable sequence lengths and minibatch sizes.
:param module: Module to apply input to.
"""
super().__init__()
self.modu... | SequenceWise |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 148181,
"end": 153158
} | class ____(Request):
"""
Update project information
:param project: Project id
:type project: str
:param name: Project name. Unique within the company.
:type name: str
:param description: Project description
:type description: str
:param tags: User-defined tags list
:type tags: ... | UpdateRequest |
python | Textualize__textual | tests/command_palette/test_declare_sources.py | {
"start": 1715,
"end": 2178
} | class ____(Screen[None]):
def on_mount(self) -> None:
self.app.action_command_palette()
async def test_no_screen_command_sources() -> None:
"""An app with a screen with no sources declared should work fine."""
async with AppWithInitialScreen(ScreenWithNoSources()).run_test() as pilot:
asse... | ScreenWithNoSources |
python | altair-viz__altair | altair/expr/core.py | {
"start": 7948,
"end": 8121
} | class ____(Expression):
def __init__(self, name) -> None:
super().__init__(name=name)
def __repr__(self) -> str:
return str(self.name)
| ConstExpression |
python | huggingface__transformers | src/transformers/models/plbart/modeling_plbart.py | {
"start": 37432,
"end": 43634
} | class ____(PLBartPreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: PLBartConfig):
super().__init__(config)
padding_idx, vocab_size = config.pad_token_id, conf... | PLBartModel |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 31211,
"end": 31764
} | class ____(PreTrainedModel):
config_class = Sam3Config
base_model_prefix = "sam3"
main_input_name = "pixel_values"
input_modalities = ["image", "text"]
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_supports_attention_backend = True
def _init_weights(s... | Sam3PreTrainedModel |
python | django-import-export__django-import-export | import_export/formats/base_formats.py | {
"start": 3488,
"end": 3585
} | class ____(TextFormat):
TABLIB_MODULE = "tablib.formats._csv"
CONTENT_TYPE = "text/csv"
| CSV |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.