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/nn/modules/upsampling.py | {
"start": 9878,
"end": 11675
} | class ____(Upsample):
r"""Applies a 2D bilinear upsampling to an input signal composed of several input channels.
To specify the scale, it takes either the :attr:`size` or the :attr:`scale_factor`
as it's constructor argument.
When :attr:`size` is given, it is the output size of the image `(h, w)`.
... | UpsamplingBilinear2d |
python | getsentry__sentry | src/sentry/unmerge.py | {
"start": 7669,
"end": 8297
} | class ____(UnmergeArgsBase):
last_event: Any | None
locked_primary_hashes: Collection[str]
# unmerge may only start mutating data on a successive page, once it
# actually has found an event that needs to be migrated.
# (unmerge_key) -> (group_id, eventstream_state)
destinations: Destinations
... | SuccessiveUnmergeArgs |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-valid-strings-to-form-target-i.py | {
"start": 5174,
"end": 6715
} | class ____(object):
def minValidStrings(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
class Trie(object):
def __init__(self):
self.__nodes = []
self.__new_node()
... | Solution4 |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/distlib/util.py | {
"start": 16613,
"end": 24131
} | class ____(object):
def __init__(self, dry_run=False):
self.dry_run = dry_run
self.ensured = set()
self._init_record()
def _init_record(self):
self.record = False
self.files_written = set()
self.dirs_created = set()
def record_as_written(self, path):
... | FileOperator |
python | numba__numba | numba/cuda/cudadrv/nvrtc.py | {
"start": 970,
"end": 1485
} | class ____:
"""
A class for managing the lifetime of nvrtcProgram instances. Instances of
the class own an nvrtcProgram; when an instance is deleted, the underlying
nvrtcProgram is destroyed using the appropriate NVRTC API.
"""
def __init__(self, nvrtc, handle):
self._nvrtc = nvrtc
... | NvrtcProgram |
python | django__django | tests/postgres_tests/models.py | {
"start": 863,
"end": 984
} | class ____(models.Model):
class Meta:
abstract = True
required_db_vendor = "postgresql"
| PostgreSQLModel |
python | PrefectHQ__prefect | tests/utilities/test_collections.py | {
"start": 2225,
"end": 2291
} | class ____(pydantic.BaseModel):
x: int
y: int
| SimplePydantic |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 64651,
"end": 65040
} | class ____(_PrintableStructure):
_fields_ = [
('timeStamp', c_ulonglong),
('vgpuInstance', _nvmlVgpuInstance_t),
('smUtil', c_nvmlValue_t),
('memUtil', c_nvmlValue_t),
('encUtil', c_nvmlValue_t),
('decUtil', c_nvmlValue_t),
('jpgUtil', c_nvmlValue_t),
... | c_nvmlVgpuInstanceUtilizationInfo_v1_t |
python | getsentry__sentry | src/sentry/incidents/endpoints/organization_incident_details.py | {
"start": 1301,
"end": 2807
} | class ____(IncidentEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
permission_classes = (IncidentPermission,)
@track_alert_endpoint_execution("GET", "sentry-api-0-organization-incident-details")
def get(se... | OrganizationIncidentDetailsEndpoint |
python | PrefectHQ__prefect | src/prefect/utilities/asyncutils.py | {
"start": 15939,
"end": 19024
} | class ____(anyio.abc.TaskGroup):
"""
A task group that gathers results.
AnyIO does not include `gather` support. This class extends the `TaskGroup`
interface to allow simple gathering.
See https://github.com/agronholm/anyio/issues/100
This class should be instantiated with `create_gather_task... | GatherTaskGroup |
python | bokeh__bokeh | tests/unit/bokeh/models/test_plots.py | {
"start": 2091,
"end": 2713
} | class ____:
def test_basic(self) -> None:
plot = figure(tools='')
x = plot.legend
assert isinstance(x, bmp._list_attr_splat)
assert len(x) == 0
plot.scatter([1,2], [3,4], legend_label="foo")
x = plot.legend
assert isinstance(x, bmp._list_attr_splat)
as... | TestPlotLegendProperty |
python | html5lib__html5lib-python | html5lib/tests/sanitizer.py | {
"start": 439,
"end": 1869
} | class ____(pytest.Item):
def __init__(self, name, parent, test):
super(SanitizerTest, self).__init__(name, parent)
self.obj = lambda: 1 # this is to hack around skipif needing a function!
self.test = test
def runtest(self):
input = self.test["input"]
expected = self.tes... | SanitizerTest |
python | huggingface__transformers | src/transformers/models/hubert/modular_hubert.py | {
"start": 4387,
"end": 4482
} | class ____(Wav2Vec2EncoderStableLayerNorm):
pass
@auto_docstring
| HubertEncoderStableLayerNorm |
python | django__django | tests/defer_regress/models.py | {
"start": 591,
"end": 697
} | class ____(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
| Child |
python | readthedocs__readthedocs.org | readthedocs/oauth/admin.py | {
"start": 2437,
"end": 3092
} | class ____(admin.ModelAdmin):
"""Admin configuration for the RemoteOrganizationRelation model."""
raw_id_fields = (
"account",
"remote_organization",
"user",
)
list_select_related = (
"remote_organization",
"user",
"account",
)
list_display = (
... | RemoteOrganizationRelationAdmin |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 33727,
"end": 33843
} | class ____(Structure):
_fields_ = (("data_owner", p_str16), ("offset", p_uint64), ("size", p_uint64))
| note_command |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constructors.py | {
"start": 257,
"end": 762
} | class ____:
HOST = "api.some.com/1.1"
AUTHENTICATE_URL = f"https://{HOST}/some.json"
def __init__(self, oauth_token: str, oauth_token_secret: str) -> None:
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
@classmethod
def from_default_keys(cls, oauth_toke... | SomeAPI |
python | scipy__scipy | scipy/optimize/tests/test_minpack.py | {
"start": 8929,
"end": 9829
} | class ____:
def setup_method(self):
self.nfev = threading.local()
def zero_f(self, y):
if not hasattr(self.nfev, 'c'):
self.nfev.c = 0
self.nfev.c += 1
return y**2-3
@pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1',
... | TestNfev |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-operations-to-make-array-continuous.py | {
"start": 749,
"end": 1171
} | class ____(object):
def minOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
nums = sorted(set(nums))
result = right = 0
for left in xrange(len(nums)):
while right < len(nums) and nums[right] <= nums[left]+n-1:... | Solution2 |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 184589,
"end": 185584
} | class ____(PyObjectType, PythonTypeConstructorMixin):
"""
For things like ClassVar, Optional, etc, which are not types and disappear during type analysis.
"""
def __init__(self, name):
super().__init__()
self.set_python_type_constructor_name(name)
self.modifier_name = name
... | SpecialPythonTypeConstructor |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ColorMapButton.py | {
"start": 3070,
"end": 3878
} | class ____(ColorMapDisplayMixin, QtWidgets.QWidget):
sigColorMapChanged = QtCore.Signal(object)
def __init__(self):
QtWidgets.QWidget.__init__(self)
ColorMapDisplayMixin.__init__(self, orientation='horizontal')
def colorMapChanged(self):
cmap = self.colorMap()
self.sigColor... | ColorMapButton |
python | falconry__falcon | falcon/errors.py | {
"start": 103370,
"end": 105818
} | class ____(HTTPBadRequest):
"""400 Bad Request.
Request media is invalid. This exception is raised by a media validator
(such as
:func:`jsonschema.validate <falcon.media.validators.jsonschema.validate>`)
when ``req.media`` is successfully deserialized, but fails to validate
against the configur... | MediaValidationError |
python | gevent__gevent | src/gevent/testing/util.py | {
"start": 17572,
"end": 18963
} | class ____(ExampleMixin,
unittest.TestCase):
popen = None
def running_server(self):
from contextlib import contextmanager
@contextmanager
def running_server():
with self.start_example() as popen:
self.popen = popen
self.befor... | TestServer |
python | getsentry__sentry | src/sentry/quotas/redis.py | {
"start": 640,
"end": 10647
} | class ____(Quota):
#: The ``grace`` period allows accommodating for clock drift in TTL
#: calculation since the clock on the Redis instance used to store quota
#: metrics may not be in sync with the computer running this code.
grace = 60
def __init__(self, **options: object):
self.is_redis_... | RedisQuota |
python | huggingface__transformers | tests/models/blip/test_image_processing_blip.py | {
"start": 4083,
"end": 5193
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = BlipImageProcessor if is_vision_available() else None
fast_image_processing_class = BlipImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester =... | BlipImageProcessingTestFourChannels |
python | pydantic__pydantic | pydantic/errors.py | {
"start": 4816,
"end": 5142
} | class ____(PydanticUserError):
"""An error raised during failures to generate a JSON schema for some `CoreSchema`.
Attributes:
message: Description of the error.
"""
def __init__(self, message: str) -> None:
super().__init__(message, code='invalid-for-json-schema')
| PydanticInvalidForJsonSchema |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/search_ads.py | {
"start": 5122,
"end": 6257
} | class ____(_GoogleSearchAdsBaseOperator):
"""
Retrieve metadata for a resource or a field.
.. seealso:
For API documentation check:
https://developers.google.com/search-ads/reporting/api/reference/rest/v0/searchAds360Fields/get
.. seealso::
For more information on how to use th... | GoogleSearchAdsGetFieldOperator |
python | PyCQA__pylint | tests/functional/g/generic_class_syntax_py312.py | {
"start": 59,
"end": 189
} | class ____[_T: float]:
last_update: int | None = None
def __init__(self, data: _T) -> None:
self.data = data
| Entity |
python | django__django | tests/filtered_relation/models.py | {
"start": 2601,
"end": 2679
} | class ____(models.Model):
currency = models.CharField(max_length=3)
| Currency |
python | pypa__hatch | tests/config/test_model.py | {
"start": 20384,
"end": 22066
} | class ____:
def test_default(self):
config = RootConfig({})
assert config.publish == config.publish == {"index": {"repo": "main"}}
assert config.raw_data == {"publish": {"index": {"repo": "main"}}}
def test_defined(self):
config = RootConfig({"publish": {"foo": {"username": "",... | TestPublish |
python | jazzband__django-model-utils | tests/models.py | {
"start": 3386,
"end": 3484
} | class ____(TimeStampedModel):
test_field = models.PositiveSmallIntegerField(default=0)
| TimeStamp |
python | tensorflow__tensorflow | tensorflow/python/distribute/values_v2_test.py | {
"start": 12954,
"end": 13759
} | class ____(_VariableInterfaceTestBase):
def create_variable(self, initial_value=1., **kwargs):
variables = []
for device in self.devices:
with ops.device(device):
variables.append(
variables_lib.Variable(initial_value, **kwargs))
return values_v2.DistributedVariable(variables)
... | DistributedVariableInterfaceTest |
python | huggingface__transformers | tests/models/musicgen_melody/test_modeling_musicgen_melody.py | {
"start": 5953,
"end": 18970
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (MusicgenMelodyModel, MusicgenMelodyForCausalLM) if is_torch_available() else ()
# Doesn't run generation tests. See `greedy_sample_model_classes` below
all_generative_model_classes = ()
greedy_sample_model_class... | MusicgenMelodyDecoderTest |
python | google__jax | docs/autodidax.py | {
"start": 32121,
"end": 32311
} | class ____:
val: Any
aval: ShapedArray
def __init__(self, val):
self.aval = aval = raise_to_shaped(get_aval(val))
self.val = np.array(val, aval.dtype)
Atom = Union[Var, Lit]
| Lit |
python | huggingface__transformers | src/transformers/models/gemma3n/modular_gemma3n.py | {
"start": 92288,
"end": 92989
} | class ____(Gemma2PreTrainedModel):
config: Gemma3nConfig
input_modalities = ("image", "text", "audio")
_no_split_modules = ["Gemma3nTextDecoderLayer"]
@torch.no_grad()
def _init_weights(self, module):
PreTrainedModel._init_weights(self, module)
if isinstance(module, Gemma3nAudioCumu... | Gemma3nPreTrainedModel |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_data_versions.py | {
"start": 1590,
"end": 17003
} | class ____(ExecutingGraphQLContextTestMatrix):
# Storage dir is shared between tests in the same class, so we need to clean it out.
@pytest.fixture(autouse=True)
def clean_storage_directory(self, graphql_context):
"""Clean IO manager storage directory before each test to prevent pollution."""
... | TestDataVersions |
python | facelessuser__pymdown-extensions | pymdownx/tabbed.py | {
"start": 1403,
"end": 11414
} | class ____(BlockProcessor):
"""Tabbed block processor."""
START = re.compile(
r'(?:^|\n)={3}(\+|\+!|!\+|!)? +"(.*?)" *(?:\n|$)'
)
COMPRESS_SPACES = re.compile(r' {2,}')
def __init__(self, parser, config):
"""Initialize."""
super().__init__(parser)
self.tab_group_co... | TabbedProcessor |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib.py | {
"start": 42008,
"end": 54358
} | class ____(_IterableInput,
composite_tensor.CompositeTensor):
"""Inputs created from dataset function."""
def __init__(
self,
input_workers,
strategy,
input_contexts=None,
dataset_fn=None,
options=None,
components=None,
element_s... | DistributedDatasetsFromFunction |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/sparse_batch_test.py | {
"start": 4314,
"end": 5050
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self, components):
return dataset_ops.Dataset.from_tensor_slices(components).map(
lambda x: array_ops.fill([x], x)).sparse_batch(4, [12])
@combinations.generate(
... | DenseToSparseBatchCheckpointTest |
python | astropy__astropy | astropy/utils/decorators.py | {
"start": 32311,
"end": 35117
} | class ____(property):
"""
Works similarly to property(), but computes the value only once.
This essentially memorizes the value of the property by storing the result
of its computation in the ``__dict__`` of the object instance. This is
useful for computing the value of some property that should o... | lazyproperty |
python | spack__spack | lib/spack/spack/modules/tcl.py | {
"start": 1829,
"end": 2100
} | class ____(BaseFileLayout):
"""File layout for tcl module files."""
@property
def modulerc(self):
"""Returns the modulerc file associated with current module file"""
return os.path.join(os.path.dirname(self.filename), ".modulerc")
| TclFileLayout |
python | explosion__spaCy | spacy/schemas.py | {
"start": 19978,
"end": 20055
} | class ____(BaseModel):
name: str
size_factor: int
| RecommendationTrfItem |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_comment07.py | {
"start": 315,
"end": 1115
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("comment07.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workboo... | TestCompareXLSXFiles |
python | coleifer__peewee | tests/model_sql.py | {
"start": 40210,
"end": 40270
} | class ____(CompoundTestModel):
alpha = IntegerField()
| Alpha |
python | google__jax | jax/_src/stages.py | {
"start": 11683,
"end": 11934
} | class ____:
_aval: core.AbstractValue
donated: bool
@property
def shape(self):
return self._aval.shape # pytype: disable=attribute-error
@property
def dtype(self):
return self._aval.dtype # pytype: disable=attribute-error
| ArgInfo |
python | nedbat__coveragepy | tests/test_arcs.py | {
"start": 63300,
"end": 63733
} | class ____(CoverageTest):
"""Tests using type annotations."""
def test_annotations(self) -> None:
self.check_coverage(
"""\
def f(x:str, y:int) -> str:
a:int = 2
return f"{x}, {y}, {a}, 3"
print(f("x", 4))
""",
... | AnnotationTest |
python | getsentry__sentry | src/sentry/migrations/0966_groupopenperiod_data_pending_inc_detector_id_index.py | {
"start": 155,
"end": 1534
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | fastai__fastai | fastai/callback/core.py | {
"start": 2378,
"end": 4083
} | class ____(Stateful,GetAttr):
"Basic class handling tweaks of the training loop by changing a `Learner` in various events"
order,_default,learn,run,run_train,run_valid = 0,'learn',None,True,True,True
_methods = _events
def __init__(self, **kwargs): assert not kwargs, f'Passed unknown events: {kwargs}'
... | Callback |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 71013,
"end": 80108
} | class ____(Qwen2VLProcessor):
r"""
Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor.
[`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information.
Args:
image_processor ([`Glm4vProcessor`], *optional*):
... | Glm4vProcessor |
python | pytorch__pytorch | torch/fx/experimental/migrate_gradual_types/constraint.py | {
"start": 4150,
"end": 4979
} | class ____(Constraint):
"""
Greatest Upper bound for dimensions
"""
def __init__(self, res, rhs1, rhs2):
"""
:param res: Dimension variable to store the result
:param rhs1: dimension variable 1
:param rhs2: dimension variable 2
"""
assert is_dim(res)
... | DGreatestUpperBound |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_file_details.py | {
"start": 4346,
"end": 5580
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user)
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
releasefile = ReleaseFile.obj... | ReleaseFileUpdateTest |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 4567,
"end": 4652
} | class ____(PydanticTypeError):
msg_template = 'value is not a valid dict'
| DictError |
python | pytorch__pytorch | test/distributed/_composable/test_composability/test_2d_composability.py | {
"start": 3067,
"end": 16111
} | class ____(FSDPTest):
global c10d_ops
global funcol
c10d_ops = torch.ops.c10d
funcol = torch.ops.c10d_functional
@property
def world_size(self) -> int:
return min(4, torch.accelerator.device_count())
def init_global_mesh(self) -> DeviceMesh:
# Prefer to test with >=4 GPUs, ... | TestFullyShard2DTraining |
python | joke2k__faker | tests/providers/test_isbn.py | {
"start": 1259,
"end": 2488
} | class ____:
prov = ISBNProvider(None)
def test_reg_pub_separation(self):
r1 = ("0000000", "0000001", 1)
r2 = ("0000002", "0000003", 2)
assert self.prov._registrant_publication("00000000", [r1, r2]) == (
"0",
"0000000",
)
assert self.prov._registra... | TestProvider |
python | django-extensions__django-extensions | tests/management/commands/test_sync_s3.py | {
"start": 333,
"end": 759
} | class ____:
def setUp(self):
self.m_boto = Mock()
self.boto_patch = patch(
"django_extensions.management.commands.sync_s3.boto",
create=True,
boto=self.m_boto,
)
self.boto_patch.start()
def tearDown(self):
super().tearDown()
se... | SyncS3TestsMixin |
python | celery__celery | celery/app/control.py | {
"start": 15646,
"end": 29699
} | class ____:
"""Worker remote control client."""
Mailbox = Mailbox
def __init__(self, app=None):
self.app = app
if (app.conf.control_queue_durable and
app.conf.control_queue_exclusive):
raise ImproperlyConfigured(
"control_queue_durable and contro... | Control |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 89110,
"end": 89241
} | class ____(CIntType):
to_py_function = "__Pyx_PyLong_FromSize_t"
def sign_and_name(self):
return "size_t"
| CSizeTType |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 79058,
"end": 79398
} | class ____(NamedTuple):
# A pair of a canonicalized constant and its original form.
# It is important that we keep the original value alive because we use id(c)
# as a key in various dictionaries. If the original value were deleted we
# may confuse constants if the same object ID is reused.
canonical: Any
o... | Constants |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/cache_key.py | {
"start": 14710,
"end": 14936
} | class ____(HasCacheKey, HasMemoized):
__slots__ = ()
@HasMemoized.memoized_instancemethod
def _generate_cache_key(self) -> Optional[CacheKey]:
return HasCacheKey._generate_cache_key(self)
| MemoizedHasCacheKey |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 62616,
"end": 63413
} | class ____(BiffRecord):
"""
This record contains information about the layout of outline symbols.
Record GUTS, BIFF3-BIFF8:
Offset Size Contents
0 2 Width of the area to display row outlines (left of the sheet), in pixel
2 2 Height of the area to display column outl... | GutsRecord |
python | openai__openai-python | src/openai/types/shared_params/custom_tool_input_format.py | {
"start": 402,
"end": 769
} | class ____(TypedDict, total=False):
definition: Required[str]
"""The grammar definition."""
syntax: Required[Literal["lark", "regex"]]
"""The syntax of the grammar definition. One of `lark` or `regex`."""
type: Required[Literal["grammar"]]
"""Grammar format. Always `grammar`."""
CustomToolIn... | Grammar |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modular_falcon_mamba.py | {
"start": 1686,
"end": 8727
} | class ____(MambaConfig):
"""
This is the configuration class to store the configuration of a [`FalconMambaModel`]. It is used to instantiate a FALCON_MAMBA
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar co... | FalconMambaConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_13/workers.py | {
"start": 23847,
"end": 25100
} | class ____(NonStrictDataModel):
"""
:param id: ID
:type id: str
:param name: Name
:type name: str
"""
_schema = {
"properties": {
"id": {"description": "ID", "type": ["string", "null"]},
"name": {"description": "Name", "type": ["string", "null"]},
},
... | IdNameEntry |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 3684,
"end": 3889
} | class ____(InvalidTransition):
def to_event(self) -> tuple[str, dict[str, Any]]:
topic, msg = super().to_event()
return "transition-counter-max-exceeded", msg
| TransitionCounterMaxExceeded |
python | cython__cython | Cython/Compiler/UtilNodes.py | {
"start": 3354,
"end": 6767
} | class ____(AtomicExprNode):
# A reference to the result of an expression. The result_code
# must be set externally (usually a temp name).
subexprs = []
lhs_of_first_assignment = False
def __init__(self, expression=None, pos=None, type=None, may_hold_none=True, is_temp=False):
self.express... | ResultRefNode |
python | django__django | tests/forms_tests/tests/test_i18n.py | {
"start": 289,
"end": 4738
} | class ____(SimpleTestCase):
def test_lazy_labels(self):
class SomeForm(Form):
username = CharField(max_length=10, label=gettext_lazy("username"))
f = SomeForm()
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">username:</label>'
'<... | FormsI18nTests |
python | pytorch__pytorch | test/test_numba_integration.py | {
"start": 360,
"end": 15769
} | class ____(common.TestCase):
@unittest.skipIf(not TEST_NUMPY, "No numpy")
@unittest.skipIf(not TEST_CUDA, "No cuda")
def test_cuda_array_interface(self):
"""torch.Tensor exposes __cuda_array_interface__ for cuda tensors.
An object t is considered a cuda-tensor if:
hasattr(t, '__... | TestNumbaIntegration |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 5821,
"end": 30236
} | class ____(threading.local):
value: bool = False
_disable_update_tensor_tracker_tls = _DisableUpdateTensorTracker()
_FAKE_TENSOR_ID_TO_PROXY_MAP_FOR_EXPORT: dict[int, torch.fx.Node] = {}
def _is_proxy_tensor_update_tensor_tracker_disabled() -> bool:
"""
Returns current state of disabling update tensor... | _DisableUpdateTensorTracker |
python | facebookresearch__faiss | tests/test_residual_quantizer.py | {
"start": 38886,
"end": 40015
} | class ____(unittest.TestCase):
def test_codec(self):
"""check that the error is in the same ballpark as PQ."""
ds = datasets.SyntheticDataset(64, 3000, 3000, 0)
xt = ds.get_train()
xb = ds.get_database()
nsplits = 2
Msub = 2
nbits = 4
prq = faiss.P... | TestProductResidualQuantizer |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/evernote/tests.py | {
"start": 243,
"end": 989
} | class ____(OAuthTestsMixin, TestCase):
provider_id = EvernoteProvider.id
def get_mocked_response(self):
return []
def get_expected_to_str(self):
return "Evernote"
def get_access_token_response(self):
return MockedResponse(
HTTPStatus.OK,
"oauth_token=S%... | EvernoteTests |
python | django__django | tests/admin_widgets/models.py | {
"start": 5350,
"end": 5630
} | class ____(models.Model):
name = models.CharField(max_length=255)
students = models.ManyToManyField(Student, related_name="current_schools")
alumni = models.ManyToManyField(Student, related_name="previous_schools")
def __str__(self):
return self.name
| School |
python | numba__numba | numba/tests/test_unsafe_intrinsics.py | {
"start": 2088,
"end": 4123
} | class ____(TestCase):
"""Tests for numba.unsafe.ndarray
"""
def test_to_fixed_tuple(self):
const = 3
@njit
def foo(array):
a = to_fixed_tuple(array, length=1)
b = to_fixed_tuple(array, 2)
c = to_fixed_tuple(array, const)
d = to_fixed_t... | TestNdarrayIntrinsic |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1068829,
"end": 1069586
} | class ____(sgqlc.types.Type, GitObject, Node):
"""Represents a Git blob."""
__schema__ = github_schema
__field_names__ = ("byte_size", "is_binary", "is_truncated", "text")
byte_size = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="byteSize")
"""Byte size of Blob object"""
is_binary... | Blob |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_filter_rewriting.py | {
"start": 11426,
"end": 24765
} | class ____:
def __call__(self, bar):
return True
lambda_without_source = eval("lambda x: x > 2", {}, {})
assert get_pretty_function_description(lambda_without_source) == "lambda x: <unknown>"
@pytest.mark.parametrize(
"start, end, predicate",
[
(1, 4, lambda x: 0 < x < 5 and x % 7),
... | NotAFunction |
python | wandb__wandb | tests/system_tests/test_core/test_torch_full.py | {
"start": 773,
"end": 1108
} | class ____(nn.Module):
def __init__(self, x=16, y=32):
super().__init__()
self.emb1 = nn.Embedding(x, y)
self.emb2 = nn.Embedding(x, y)
def forward(self, x):
return {
"key": {
"emb1": self.emb1(x),
"emb2": self.emb2(x),
}
... | EmbModel |
python | falconry__falcon | examples/ws_tutorial/ws_tutorial/app.py | {
"start": 2159,
"end": 2537
} | class ____:
async def on_websocket(self, req: Request, ws: WebSocket):
while True:
try:
message = await ws.receive_text()
await ws.send_media(
{'message': message, 'date': datetime.now().isoformat()}
)
except WebSock... | EchoWebSocketResource |
python | python-excel__xlwt | tests/test_by_name_functions.py | {
"start": 31,
"end": 868
} | class ____(unittest.TestCase):
def setUp(self):
self.wb = xlwt.Workbook()
self.wb.add_sheet('Plan1')
self.wb.add_sheet('Plan2')
self.wb.add_sheet('Plan3')
self.wb.add_sheet('Plan4')
def test_sheet_index(self):
'Return sheet index by sheet name'
idx = self... | TestByName |
python | sphinx-doc__sphinx | utils/bump_version.py | {
"start": 5106,
"end": 6574
} | class ____(Exception):
pass
@contextmanager
def processing(message: str) -> Iterator[None]:
try:
print(message + ' ... ', end='')
yield
except Skip as exc:
print(f'skip: {exc}')
except Exception:
print('error')
raise
else:
print('done')
def parse_o... | Skip |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 735255,
"end": 737665
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"commit",
"commit_oid",
"created_at",
"creator",
"database_id",
"description",
"environment",
"latest_environmen... | Deployment |
python | google__pytype | pytype/tests/test_flow1.py | {
"start": 111,
"end": 9320
} | class ____(test_base.BaseTest):
"""Tests for control flow.
These tests primarily test instruction ordering and CFG traversal of the
bytecode interpreter, i.e., their primary focus isn't the inferred types.
Even though they check the validity of the latter, they're mostly smoke tests.
"""
def test_if(self)... | FlowTest |
python | django-haystack__django-haystack | test_haystack/test_query.py | {
"start": 35627,
"end": 36829
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.esqs = EmptySearchQuerySet()
def test_get_count(self):
self.assertEqual(self.esqs.count(), 0)
self.assertEqual(len(self.esqs.all()), 0)
def test_filter(self):
sqs = self.esqs.filter(content="foo")
s... | EmptySearchQuerySetTestCase |
python | h5py__h5py | h5py/tests/test_attrs_data.py | {
"start": 736,
"end": 3693
} | class ____(BaseAttrs):
"""
Feature: Scalar types map correctly to array scalars
"""
def test_int(self):
""" Integers are read as correct NumPy type """
name = make_name()
self.f.attrs[name] = np.array(1, dtype=np.int8)
out = self.f.attrs[name]
self.assertIsI... | TestScalar |
python | catalyst-team__catalyst | tests/catalyst/callbacks/test_profiler.py | {
"start": 1475,
"end": 4871
} | class ____(dl.IRunner):
def __init__(self, logdir, device, tb_logs=None, chrome_logs=None, stack_logs=None):
super().__init__()
self._logdir = logdir
self._device = device
self.profiler_tb_logs = tb_logs
self.chrome_trace_logs = chrome_logs
self.stacks_logs = stack_lo... | CustomRunner |
python | ipython__ipython | IPython/core/builtin_trap.py | {
"start": 442,
"end": 3006
} | class ____(Configurable):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
allow_none=True)
def __init__(self, shell=None):
super(BuiltinTrap, self).__init__(shell=shell, config=None)
self._orig_builtins = {}
# We define this to track if a sing... | BuiltinTrap |
python | google__pytype | pytype/tests/test_special_builtins2.py | {
"start": 93,
"end": 1392
} | class ____(test_base.BaseTest):
"""Tests for special_builtins.py."""
def test_property_with_type_parameter(self):
ty = self.Infer("""
from typing import Union
class Foo:
@property
def foo(self) -> Union[str, int]:
return __any_object__
""")
self.assertTypesMatchPyt... | SpecialBuiltinsTest |
python | google__flatbuffers | python/flatbuffers/flexbuffers.py | {
"start": 11867,
"end": 12596
} | class ____(Sized):
"""Data accessor for the encoded vector bytes."""
__slots__ = ()
def __getitem__(self, index):
if index < 0 or index >= len(self):
raise IndexError(
'vector index %s is out of [0, %d) range' % (index, len(self))
)
packed_type = self._buf[len(self) * self._byte_w... | Vector |
python | getsentry__sentry | src/sentry/utils/marketo_client.py | {
"start": 220,
"end": 540
} | class ____(Exception):
def __init__(self, data: MarketoErrorResponse):
# just use the first error
error = data["errors"][0]
self.code = error["code"]
self.message = error["message"]
def __str__(self) -> str:
return f"MarketoError: {self.code} - {self.message}"
| MarketoError |
python | kamyu104__LeetCode-Solutions | Python/divide-an-array-into-subarrays-with-minimum-cost-ii.py | {
"start": 3851,
"end": 4813
} | class ____(object):
def minimumCost(self, nums, k, dist):
"""
:type nums: List[int]
:type k: int
:type dist: int
:rtype: int
"""
sl1, sl2 = SortedList(), SortedList()
mn, curr = float("inf"), 0
for i in xrange(1, len(nums)):
sl1.add... | Solution3 |
python | agronholm__apscheduler | src/apscheduler/triggers/cron/fields.py | {
"start": 3192,
"end": 3432
} | class ____(
BaseField, extra_compilers=(WeekdayPositionExpression, LastDayOfMonthExpression)
):
__slots__ = ()
def get_max(self, dateval: datetime) -> int:
return monthrange(dateval.year, dateval.month)[1]
| DayOfMonthField |
python | walkccc__LeetCode | solutions/2932. Maximum Strong Pair XOR I/2932.py | {
"start": 141,
"end": 1516
} | 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 | rapidsai__cudf | python/cudf_polars/cudf_polars/containers/dataframe.py | {
"start": 2175,
"end": 2218
} | class ____(Column):
name: str
| NamedColumn |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 18067,
"end": 19450
} | class ____(state.AbstractRef):
refs: Sequence[_GPUMemoryRefTree]
def __init__(
self,
aval,
refs: Sequence[_GPUMemoryRefTree],
memory_space,
):
self.refs = refs
super().__init__(aval, memory_space=memory_space)
def _iter(self, tracer):
return iter(flatten_ref_union(tracer))
... | AbstractRefUnion |
python | explosion__spaCy | spacy/lang/af/__init__.py | {
"start": 84,
"end": 153
} | class ____(BaseDefaults):
stop_words = STOP_WORDS
| AfrikaansDefaults |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 163334,
"end": 164899
} | class ____(TestCase):
"""Tests for ``windowed_complete()``"""
def test_basic(self):
actual = list(mi.windowed_complete([1, 2, 3, 4, 5], 3))
expected = [
((), (1, 2, 3), (4, 5)),
((1,), (2, 3, 4), (5,)),
((1, 2), (3, 4, 5), ()),
]
self.assertEq... | WindowedCompleteTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 7394,
"end": 7494
} | class ____(SQLAlchemyError):
"""Raised when an error occurs during SQL compilation"""
| CompileError |
python | jina-ai__jina | tests/integration/hub_usage/dummyhub/__init__.py | {
"start": 53,
"end": 185
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
foo()
| DummyHubExecutor |
python | fastai__fastai | fastai/torch_core.py | {
"start": 20417,
"end": 20572
} | class ____(TensorBase): pass
TensorBase.register_func(Tensor.__getitem__, TensorImageBase, TensorCategory)
# %% ../nbs/00_torch_core.ipynb 121
| TensorCategory |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 56417,
"end": 62405
} | class ____(nn.Module):
"""
Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
[`OneFormerPixelDecoderEncoderLayer`].
The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
Args:
config: On... | OneFormerPixelDecoderEncoderOnly |
python | scipy__scipy | scipy/optimize/_shgo.py | {
"start": 61586,
"end": 63593
} | class ____:
def __init__(self):
self.cache = {}
# Lists for search queries
self.v_maps = []
self.xl_maps = []
self.xl_maps_set = set()
self.f_maps = []
self.lbound_maps = []
self.size = 0
def __getitem__(self, v):
try:
v = np.... | LMapCache |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 13648,
"end": 17233
} | class ____(MimetypeRenderer):
"""
Renderer to display interactive figures using an IFrame. HTML
representations of Figures are saved to an `iframe_figures/` directory and
iframe HTML elements that reference these files are inserted into the
notebook.
With this approach, neither plotly.js nor t... | IFrameRenderer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.