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
huggingface__transformers
src/transformers/models/perception_lm/modular_perception_lm.py
{ "start": 3038, "end": 3129 }
class ____(LlavaPreTrainedModel): base_model_prefix = "model"
PerceptionLMPreTrainedModel
python
great-expectations__great_expectations
great_expectations/experimental/metric_repository/metrics.py
{ "start": 1798, "end": 4862 }
class ____(MetricRepositoryBaseModel, Generic[_ValueType]): """Abstract computed metric. Domain, value and parameters are metric dependent. Note: This implementation does not currently take into account other domain modifiers, e.g. row_condition, condition_parser, ignore_row_if """ def __new__(cls...
Metric
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 19062, "end": 19386 }
class ____(GroupType): type_id = 2001 slug = "profile_file_io_main_thread" description = "File I/O on Main Thread" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.MOBILE.value default_priority = PriorityLevel.LOW released = True @dataclass(frozen=True)
ProfileFileIOGroupType
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 88074, "end": 91229 }
class ____(Request): """ Indicates that task is closed :param force: Allows forcing state change even if transition is not supported :type force: bool :param task: Task ID :type task: str :param status_reason: Reason for status change :type status_reason: str :param status_message: ...
CloseRequest
python
huggingface__transformers
src/transformers/models/informer/modular_informer.py
{ "start": 15385, "end": 20847 }
class ____(TimeSeriesTransformerEncoder): def __init__(self, config: InformerConfig): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.encoder_layerdrop self.gradient_checkpointing = False if config.prediction_length is None: raise V...
InformerEncoder
python
django__django
tests/model_formsets/models.py
{ "start": 1067, "end": 1461 }
class ____(models.Model): author = models.ForeignKey(Author, models.CASCADE) # Optional secondary author alt_editor = models.ForeignKey(Editor, models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = (("author", "title", "alt_editor"),)...
BookWithOptionalAltEditor
python
tornadoweb__tornado
tornado/platform/asyncio.py
{ "start": 10207, "end": 10953 }
class ____(BaseAsyncIOLoop): """``AsyncIOMainLoop`` creates an `.IOLoop` that corresponds to the current ``asyncio`` event loop (i.e. the one returned by ``asyncio.get_event_loop()``). .. deprecated:: 5.0 Now used automatically when appropriate; it is no longer necessary to refer to this...
AsyncIOMainLoop
python
huggingface__transformers
src/transformers/models/mpnet/modeling_mpnet.py
{ "start": 3974, "end": 6710 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention...
MPNetSelfAttention
python
facebook__pyre-check
client/configuration/tests/configuration_test.py
{ "start": 1191, "end": 22393 }
class ____(unittest.TestCase): def test_create_from_command_arguments(self) -> None: configuration = PartialConfiguration.from_command_arguments( command_arguments.CommandArguments( local_configuration=None, logger="logger", targets=[], ...
PartialConfigurationTest
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 545, "end": 764 }
class ____: """dummy""" def __init__(self, _): pass def __get__(self, obj, __): if not obj: return self return 5 def __set__(self, _, __): pass
CustomProperty
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 21527, "end": 21664 }
class ____(TypedDict, total=False): release: list[str] releaseId: list[str] globalFilter: list[dict[str, Any]]
DashboardFilters
python
miyuchina__mistletoe
mistletoe/block_token.py
{ "start": 1975, "end": 4221 }
class ____(token.Token): """ Base class for block-level tokens. Recursively parse inner tokens. Naming conventions: * lines denotes a list of (possibly unparsed) input lines, and is commonly used as the argument name for constructors. * BlockToken.children is a list with all the...
BlockToken
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 1528, "end": 1586 }
class ____(DataContextError): pass
ExpectationSuiteError
python
walkccc__LeetCode
solutions/1725. Number Of Rectangles That Can Form The Largest Square/1725.py
{ "start": 0, "end": 176 }
class ____: def countGoodRectangles(self, rectangles: list[list[int]]) -> int: minSides = [min(x, y) for x, y in rectangles] return minSides.count(max(minSides))
Solution
python
tornadoweb__tornado
tornado/gen.py
{ "start": 25823, "end": 31765 }
class ____: """Internal implementation of `tornado.gen.coroutine`. Maintains information about pending callbacks and their results. The results of the generator are stored in ``result_future`` (a `.Future`) """ def __init__( self, ctx_run: Callable, gen: "Generator[_Yi...
Runner
python
astropy__astropy
astropy/table/bst.py
{ "start": 810, "end": 1194 }
class ____: """ The opposite of MaxValue, i.e. a representation of negative infinity. """ def __lt__(self, other): return True def __le__(self, other): return True def __gt__(self, other): return False def __ge__(self, other): return False def __r...
MinValue
python
fluentpython__example-code-2e
21-async/mojifinder/charindex.py
{ "start": 1219, "end": 2443 }
class ____: entries: Index def __init__(self, start: int = 32, stop: int = STOP_CODE): entries: Index = defaultdict(set) for char in (chr(i) for i in range(start, stop)): name = unicodedata.name(char, '') if name: for word in tokenize(name): ...
InvertedIndex
python
pyqtgraph__pyqtgraph
tests/test_signalproxy.py
{ "start": 91, "end": 239 }
class ____(QtCore.QObject): signalSend = QtCore.Signal() def __init__(self, parent=None): super(Sender, self).__init__(parent)
Sender
python
cython__cython
Cython/Compiler/FusedNode.py
{ "start": 351, "end": 41407 }
class ____(StatListNode): """ This node replaces a function with fused arguments. It deep-copies the function for every permutation of fused types, and allocates a new local scope for it. It keeps track of the original function in self.node, and the entry of the original function in the symbol table...
FusedCFuncDefNode
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/gcs/io_manager.py
{ "start": 2907, "end": 6027 }
class ____(ConfigurableIOManager): """Persistent IO manager using GCS for storage. Serializes objects via pickling. Suitable for objects storage for distributed executors, so long as each execution node has network connectivity and credentials for GCS and the backing bucket. Assigns each op output to ...
GCSPickleIOManager
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_annotated.py
{ "start": 911, "end": 1445 }
class ____: a: Annotated[Optional[float], Color.RED] = None b: Annotated[Optional[float], Color.BLUE] = None x: Annotated[Optional[float], Color.RED, "foo"] = None def test2_alarm1(c: Test2_C) -> None: c.a = 1.01 _test_sink(c.a) def test2_alarm2(c: Test2_C) -> None: c.x = 1.01 _test_sink...
Test2_C
python
huggingface__transformers
src/transformers/models/mamba2/modeling_mamba2.py
{ "start": 41910, "end": 47769 }
class ____(Mamba2PreTrainedModel, GenerationMixin): _tied_weights_keys = {} def __init__(self, config): super().__init__(config) self.backbone = Mamba2Model(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final p...
Mamba2ForCausalLM
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_batch_client.py
{ "start": 17914, "end": 21383 }
class ____: @mock.patch.dict("os.environ", AWS_DEFAULT_REGION=AWS_REGION) @mock.patch.dict("os.environ", AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID) @mock.patch.dict("os.environ", AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY) def setup_method(self, method): self.batch_client = BatchClientHook(aws_conn_i...
TestBatchClientDelays
python
PyCQA__pylint
tests/functional/n/non/non_str_assignment_to_dunder_name.py
{ "start": 214, "end": 1457 }
class ____(): pass def example_function(): pass def returns_str(): return "abcd" def returns_int(): return 0 def returns_tuple(): return 0, "abc" # Might not be thorough if same hash seed is used in testing... def returns_random_type(): if random.randint(0, 1) > 0: return 0 ...
ExampleClass
python
pydantic__pydantic
pydantic/types.py
{ "start": 17708, "end": 33703 }
class ____(annotated_types.GroupedMetadata): """!!! abstract "Usage Documentation" [String types](./standard_library_types.md#strings) A field metadata class to apply constraints to `str` types. Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.A...
StringConstraints
python
wandb__wandb
wandb/sdk/launch/environment/gcp_environment.py
{ "start": 1610, "end": 12715 }
class ____(AbstractEnvironment): """GCP Environment. Attributes: region: The GCP region. """ region: str def __init__( self, region: str, ) -> None: """Initialize the GCP environment. Arguments: region: The GCP region. verify: W...
GcpEnvironment
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py
{ "start": 14774, "end": 18094 }
class ____(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes def test_valid(self): with ops.Graph().as_default(), context.eager_mode(): input_value = constant_op.constant([-0.8, -0.5, 0, 0.3, 0.8, -2.0], shape=(6,), ...
QuantizeAndDequantizeV3OpTest
python
huggingface__transformers
tests/models/textnet/test_modeling_textnet.py
{ "start": 1768, "end": 7013 }
class ____: def __init__( self, parent, stem_kernel_size=3, stem_stride=2, stem_in_channels=3, stem_out_channels=32, stem_act_func="relu", dropout_rate=0, ops_order="weight_bn_act", conv_layer_kernel_sizes=[ [[3, 3]], ...
TextNetModelTester
python
Textualize__textual
src/textual/widgets/_input.py
{ "start": 1512, "end": 2162 }
class ____(NamedTuple): """A range of selected text within the Input. Text can be selected by clicking and dragging the mouse, or by pressing shift+arrow keys. Attributes: start: The start index of the selection. end: The end index of the selection. """ start: int end: int...
Selection
python
davidhalter__jedi
jedi/inference/gradual/generics.py
{ "start": 804, "end": 1209 }
class ____: def get_index_and_execute(self, index): try: return self[index].execute_annotation() except IndexError: debug.warning('No param #%s found for annotation %s', index, self) return NO_VALUES def get_type_hint(self): return '[%s]' % ', '.join(...
_AbstractGenericManager
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/set_based_column_map_expectation_template.py
{ "start": 623, "end": 2722 }
class ____(SetBasedColumnMapExpectation): # </snippet> # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/set_based_column_map_expectation_template.py docstring"> """TODO: Add a docstring here""" # </snippet> # These values will be used to configure the metri...
ExpectColumnValuesToBeInSomeSet
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 8867, "end": 9146 }
class ____(models.Model): waters = models.CharField(max_length=200) level = models.IntegerField() date = models.DateTimeField() history = HistoricalRecords(cascade_delete_history=True) @property def _history_date(self): return self.date
WaterLevel
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_gcs.py
{ "start": 44476, "end": 52798 }
class ____: def setup_method(self): with mock.patch(BASE_STRING.format("GoogleBaseHook.__init__")) as mock_init: mock_init.return_value = None self.gcs_hook = gcs.GCSHook(gcp_conn_id="test") @mock.patch(GCS_STRING.format("GCSHook.get_conn")) def test_upload_file(self, mock_s...
TestGCSHookUpload
python
pytorch__pytorch
test/test_modules.py
{ "start": 963, "end": 51810 }
class ____(TestCase): _do_cuda_memory_leak_check = True _do_cuda_non_default_stream = True precision = 1e-5 rel_tol = 1e-5 def _assert_module_parameters_and_buffer_are(self, module, device, dtype): # Check device placement and dtype for created parameters and buffers. # Only verify ...
TestModule
python
jina-ai__jina
tests/docker_compose/reload-executor/reload_executor.py
{ "start": 53, "end": 353 }
class ____(Executor): def __init__(self, argument, *args, **kwargs): super().__init__(*args, **kwargs) self.argument = argument @requests() def exec(self, docs: DocumentArray, **kwargs): for doc in docs: doc.tags['argument'] = self.argument
ReloadExecutor
python
doocs__leetcode
solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.py
{ "start": 0, "end": 584 }
class ____: def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n - 1 while left < right: mid = (left + right) >> 1 if nums[0] <= nums[mid]: if nums[0] <= target <= nums[mid]: right = mid ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 250444, "end": 251077 }
class ____(sgqlc.types.Input): """Autogenerated input type of MarkFileAsViewed""" __schema__ = github_schema __field_names__ = ("pull_request_id", "path", "client_mutation_id") pull_request_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="pullRequestId") """The Node ID of the pull req...
MarkFileAsViewedInput
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property14.py
{ "start": 193, "end": 502 }
class ____: def __init__(self): self._something = [] @property def something(self) -> Sequence[Hashable]: return self._something @something.setter def something(self, thing: list[HashableT]): self._something = thing f = ClassA() f.something = ["a", "b", "c"]
ClassA
python
weaviate__weaviate-python-client
weaviate/config.py
{ "start": 2418, "end": 3668 }
class ____(BaseModel): """Use this class to specify the connection and proxy settings for your client when connecting to Weaviate. When specifying the timeout, you can either provide a tuple with the query and insert timeouts, or a `Timeout` object. The `Timeout` object gives you additional option to confi...
AdditionalConfig
python
walkccc__LeetCode
solutions/2790. Maximum Number of Groups With Increasing Length/2790.py
{ "start": 0, "end": 351 }
class ____: def maxIncreasingGroups(self, usageLimits: list[int]) -> int: ans = 1 # the next target length availableLimits = 0 for usageLimit in sorted(usageLimits): availableLimits += usageLimit # Can create groups 1, 2, ..., ans. if availableLimits >= ans * (ans + 1) // 2: an...
Solution
python
django__django
tests/admin_views/admin.py
{ "start": 6873, "end": 7333 }
class ____(admin.ModelAdmin): def has_change_permission(self, request, obj=None): """Only allow changing objects with even id number""" return request.user.is_staff and (obj is not None) and (obj.id % 2 == 0) def has_view_permission(self, request, obj=None): """Only allow viewing object...
RowLevelChangePermissionModelAdmin
python
kamyu104__LeetCode-Solutions
Python/sorting-the-sentence.py
{ "start": 48, "end": 432 }
class ____(object): def sortSentence(self, s): """ :type s: str :rtype: str """ words = s.split() for i in xrange(len(words)): while int(words[i][-1])-1 != i: words[int(words[i][-1])-1], words[i] = words[i], words[int(words[i][-1])-1] ...
Solution
python
walkccc__LeetCode
solutions/545. Boundary of Binary Tree/545.py
{ "start": 0, "end": 991 }
class ____: def boundaryOfBinaryTree(self, root: TreeNode | None) -> list[int]: if not root: return [] ans = [root.val] def dfs(root: TreeNode | None, lb: bool, rb: bool): """ 1. root.left is left boundary if root is left boundary. root.right if left boundary if root.left is N...
Solution
python
lazyprogrammer__machine_learning_examples
rl/approx_prediction.py
{ "start": 1224, "end": 3388 }
class ____: def __init__(self, grid): # fit the featurizer to data samples = gather_samples(grid) # self.featurizer = Nystroem() self.featurizer = RBFSampler() self.featurizer.fit(samples) dims = self.featurizer.n_components # initialize linear model weights self.w = np.zeros(dims) ...
Model
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-removals-to-make-mountain-array.py
{ "start": 49, "end": 863 }
class ____(object): def minimumMountainRemovals(self, nums): """ :type nums: List[int] :rtype: int """ left_lis_len = [0]*len(nums) lis = [] for i in xrange(len(nums)-1): j = bisect.bisect_left(lis, nums[i]) if j == len(lis): ...
Solution
python
getsentry__sentry
src/sentry/integrations/github/status_check.py
{ "start": 429, "end": 854 }
class ____(enum.Enum): """ GitHub Check Run conclusion values (when status is completed). https://docs.github.com/en/rest/checks/runs?apiVersion=2022-11-28#create-a-check-run """ ACTION_REQUIRED = "action_required" CANCELLED = "cancelled" FAILURE = "failure" NEUTRAL = "neutral" SKIP...
GitHubCheckConclusion
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/control_flow_ops_test.py
{ "start": 73267, "end": 74655 }
class ____(PForTestCase): def test_loop_variant_cond(self): x = [1, 2, 3, 4, 5.] y = 2.5 @def_function.function def loop_fn(i): x_i = array_ops.gather(x, i) # Note that the output has a combination of then and else branches being # loop variant / invariant. return cond_v2.con...
StatelessIfTest
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 19527, "end": 20504 }
class ____(LayoutNode): """Place elements vertically stacked, one under another. Example: layout = Layout( Row( Column('first_name', 'last_name', desktop=8, tablet=6) 'sex_options' ) ) """ def __init__(self, *elements, **kwargs): ...
Column
python
huggingface__transformers
src/transformers/models/bart/modeling_bart.py
{ "start": 2403, "end": 3491 }
class ____(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, num_embeddings: int, embedding_dim: int): # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2 # and adjust num_embeddings appropr...
BartLearnedPositionalEmbedding
python
Textualize__textual
tests/css/test_css_reloading.py
{ "start": 214, "end": 332 }
class ____(Screen[None]): def compose(self) -> ComposeResult: yield Label("I am the base screen")
BaseScreen
python
Textualize__textual
tests/test_await_remove.py
{ "start": 64, "end": 164 }
class ____(Label): async def on_mount(self) -> None: await self.remove()
SelfRemovingLabel
python
python-attrs__attrs
src/attr/_make.py
{ "start": 77170, "end": 84046 }
class ____: """ *Read-only* representation of an attribute. .. warning:: You should never instantiate this class yourself. The class has *all* arguments of `attr.ib` (except for ``factory`` which is only syntactic sugar for ``default=Factory(...)`` plus the following: - ``name`` (`str...
Attribute
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/sql.py
{ "start": 7962, "end": 8049 }
class ____: UniqueText = db.String(512) LongText = LongText
MySQLCompatabilityTypes
python
keras-team__keras
keras/src/layers/normalization/layer_normalization_test.py
{ "start": 186, "end": 4817 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_ln_basics(self): self.run_layer_test( layers.LayerNormalization, init_kwargs={ "gamma_regularizer": regularizers.L2(0.01), "beta_regularizer": regularizers.L2(0.01), ...
LayerNormalizationTest
python
pyca__cryptography
tests/hazmat/primitives/test_rsa.py
{ "start": 59636, "end": 60446 }
class ____: def test_invalid_algorithm(self): mgf = padding.MGF1(hashes.SHA256()) with pytest.raises(TypeError): padding.OAEP( mgf=mgf, algorithm=b"", # type:ignore[arg-type] label=None, ) def test_algorithm_property(self)...
TestOAEP
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 19373, "end": 19937 }
class ____(_Constraint): """Constraint representing boolean likes. Convenience class for [bool, np.bool_] """ def __init__(self): super().__init__() self._constraints = [ _InstancesOf(bool), _InstancesOf(np.bool_), ] def is_satisfied_by(self, va...
_Booleans
python
lazyprogrammer__machine_learning_examples
cnn_class2/tf_resnet_identity_block.py
{ "start": 413, "end": 3736 }
class ____: def __init__(self, mi, fm_sizes, activation=tf.nn.relu): # conv1, conv2, conv3 # note: # feature maps shortcut = # feauture maps conv 3 assert(len(fm_sizes) == 3) # note: kernel size in 2nd conv is always 3 # so we won't bother including it as an arg self.session = None ...
IdentityBlock
python
gevent__gevent
src/gevent/tests/test__selectors.py
{ "start": 1604, "end": 3845 }
class ____(SelectorTestMixin, greentest.TestCase): def test_select_using_socketpair(self): # Basic test. with selectors.GeventSelector() as sel: self._check_selector(sel) def test_select_many_sockets(self): try: AF_UNIX = socket.AF_UNIX ...
GeventSelectorTest
python
python-pillow__Pillow
Tests/test_image_access.py
{ "start": 304, "end": 3199 }
class ____: def test_sanity(self) -> None: im1 = hopper() im2 = Image.new(im1.mode, im1.size, 0) for y in range(im1.size[1]): for x in range(im1.size[0]): pos = x, y value = im1.getpixel(pos) assert value is not None ...
TestImagePutPixel
python
encode__django-rest-framework
tests/utils.py
{ "start": 496, "end": 923 }
class ____: def __init__(self, iterable): self.items = iterable def __getitem__(self, val): return self.items[val] def get(self, **lookup): for item in self.items: if all([ attrgetter(key.replace('__', '.'))(item) == value for key, value ...
MockQueryset
python
walkccc__LeetCode
solutions/2418. Sort the People/2418.py
{ "start": 0, "end": 219 }
class ____: def sortPeople(self, names: list[str], heights: list[int]) -> list[str]: return [height for _, height in sorted([(height, name) for name, height in zip(names, heights)], reverse=True)]
Solution
python
pypa__warehouse
tests/common/db/organizations.py
{ "start": 5791, "end": 5998 }
class ____(WarehouseFactory): class Meta: model = TeamRole role_name = TeamRoleType.Member user = factory.SubFactory(UserFactory) team = factory.SubFactory(TeamFactory)
TeamRoleFactory
python
ray-project__ray
doc/source/custom_directives.py
{ "start": 20257, "end": 114285 }
class ____: """Object which holds configuration data for a set of library examples.""" def __init__( self, path: Union[pathlib.Path, str], src_dir: Union[pathlib.Path, str] ): """Parse a config file containing examples to display in the example gallery. Parameters ---------...
ExampleConfig
python
huggingface__transformers
src/transformers/models/edgetam/modeling_edgetam.py
{ "start": 28587, "end": 30692 }
class ____(nn.Module): def __init__(self, config: EdgeTamMaskDecoderConfig): super().__init__() self.config = config self.num_hidden_layers = config.num_hidden_layers self.layers = nn.ModuleList() for i in range(self.num_hidden_layers): self.layers.append(EdgeTa...
EdgeTamTwoWayTransformer
python
ZoranPandovski__al-go-rithms
data_structures/binarySearch_tree/Python/binary_search_tree.py
{ "start": 122, "end": 1124 }
class ____: def __init__(self, username, name, email): self.username = username self.name = name self.email = email def __repr__(self): return "User(username='{}', name='{}', email='{}')".format(self.username, self.name, self.email) def __str__(self): re...
User
python
sqlalchemy__sqlalchemy
examples/space_invaders/space_invaders.py
{ "start": 1290, "end": 3142 }
class ____(Base): """Describe a "glyph", a graphical element to be painted on the screen. """ __tablename__ = "glyph" id = Column(Integer, primary_key=True) name = Column(String) type = Column(String) width = Column(Integer) height = Column(Integer) data = Column(String) al...
Glyph
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 4660, "end": 5431 }
class ____: @functools.cached_property def _by_meta(self): return [meta_nonempty(x._meta) if isinstance(x, Expr) else x for x in self.by] @functools.cached_property def _by_columns(self): return [x for x in self.by if not isinstance(x, Expr)] @property def split_by(self): ...
GroupByBase
python
doocs__leetcode
lcp/LCP 70. 沙地治理/Solution.py
{ "start": 0, "end": 533 }
class ____: def sandyLandManagement(self, size: int) -> List[List[int]]: ans = [[1, 1]] k = 0 for i in range(size, 1, -1): if k == 0: for j in range(1, i << 1, 2): ans.append([i, j]) elif k == 1: ans.append([i, 2]) ...
Solution
python
google__jax
tests/mosaic/flash_attention_test.py
{ "start": 1315, "end": 2785 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() if flash_attention is None: self.skipTest("Mosaic GPU not available.") if (not jtu.test_device_matches(["cuda"]) or not jtu.is_cuda_compute_capability_equal("9.0")): self.skipTest("Only works on GPU with capability sm90a") ...
FlashAttentionTestCase
python
spyder-ide__spyder
spyder/widgets/helperwidgets.py
{ "start": 25014, "end": 26904 }
class ____(QLabel): """Label to report a message to users.""" def __init__(self, parent): super().__init__("", parent) # Set main attributes self.setWordWrap(True) self.setVisible(False) # Set style css = qstylizer.style.StyleSheet() css.QLabel.setValue...
MessageLabel
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 15750, "end": 22261 }
class ____(NonStrictDataModel): """ :param binary: Binary to use when running the script :type binary: str :param repository: Name of the repository where the script is located :type repository: str :param tag: Repository tag :type tag: str :param branch: Repository branch id If not prov...
Script
python
django-haystack__django-haystack
test_haystack/discovery/models.py
{ "start": 31, "end": 183 }
class ____(models.Model): title = models.CharField(max_length=255) body = models.TextField() def __str__(self): return self.title
Foo
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 988, "end": 1328 }
class ____(Option): """An option that must have a boolean value or equivalent assigned. """ @classmethod def preprocess(cls, value): if value in [True, False]: return bool(value) else: raise OptionError("'%s' must have a boolean value assigned, got %s" % (cls.option,...
BooleanOption
python
pyparsing__pyparsing
examples/shapes.py
{ "start": 547, "end": 633 }
class ____(Shape): def area(self): return self.width * self.height
Rectangle
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/base.py
{ "start": 318, "end": 2288 }
class ____(metaclass=ABCMeta): """ Abstraction for any input. An instance of this class can be given to the constructor of a :class:`~prompt_toolkit.application.Application` and will also be passed to the :class:`~prompt_toolkit.eventloop.base.EventLoop`. """ @abstractmethod def fileno...
Input
python
keras-team__keras
keras/src/metrics/probabilistic_metrics.py
{ "start": 7885, "end": 10640 }
class ____(reduction_metrics.MeanMetricWrapper): """Computes the crossentropy metric between the labels and predictions. Use this crossentropy metric when there are two or more label classes. It expects labels to be provided as integers. If you want to provide labels that are one-hot encoded, please us...
SparseCategoricalCrossentropy
python
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 16674, "end": 19406 }
class ____(ViTMSNPreTrainedModel): def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False): r""" use_mask_token (`bool`, *optional*, defaults to `False`): Whether to use a mask token for masked image modeling. """ super().__init__(config) self.confi...
ViTMSNModel
python
PrefectHQ__prefect
tests/server/models/test_work_queues.py
{ "start": 6291, "end": 8284 }
class ____: async def test_update_work_queue(self, session, work_queue): result = await models.work_queues.update_work_queue( session=session, work_queue_id=work_queue.id, work_queue=schemas.actions.WorkQueueUpdate(is_paused=True), ) assert result ...
TestUpdateWorkQueue
python
django__django
django/contrib/auth/hashers.py
{ "start": 12813, "end": 13140 }
class ____(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1
PBKDF2SHA1PasswordHasher
python
joke2k__faker
faker/providers/person/az_AZ/__init__.py
{ "start": 152, "end": 17369 }
class ____(PersonProvider): formats_female = ( "{{first_name_female}} {{last_name_female}}", "{{first_name_female}} {{first_name_male}}", "{{first_name_female}} {{last_name_unisex}}", ) formats_male = ( "{{first_name_male}} {{last_name_male}}", "{{first_name_male}} {...
Provider
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 19507, "end": 19822 }
class ____(Literal): """Any list literal such as ``[1, 2, 3]``""" fields = ("items",) items: t.List[Expr] def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]: eval_ctx = get_eval_context(self, eval_ctx) return [x.as_const(eval_ctx) for x in self.items]
List
python
marshmallow-code__marshmallow
tests/test_schema.py
{ "start": 64556, "end": 66252 }
class ____(Schema): name = fields.Raw(required=True) def test_serialization_with_required_field(): user = User(name=None) RequiredUserSchema().dump(user) def test_deserialization_with_required_field(): with pytest.raises(ValidationError) as excinfo: RequiredUserSchema().load({}) data, er...
RequiredUserSchema
python
doocs__leetcode
solution/3000-3099/3063.Linked List Frequency/Solution.py
{ "start": 151, "end": 493 }
class ____: def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]: cnt = Counter() while head: cnt[head.val] += 1 head = head.next dummy = ListNode() for val in cnt.values(): dummy.next = ListNode(val, dummy.next) ...
Solution
python
sympy__sympy
sympy/categories/baseclasses.py
{ "start": 4610, "end": 5838 }
class ____(Morphism): """ Represents a morphism which has a name. Explanation =========== Names are used to distinguish between morphisms which have the same domain and codomain: two named morphisms are equal if they have the same domains, codomains, and names. Examples ======== ...
NamedMorphism
python
dask__distributed
distributed/diagnostics/nvml.py
{ "start": 1111, "end": 12133 }
class ____(NamedTuple): has_context: bool device_info: CudaDeviceInfo | None = None # Initialisation must occur per-process, so an initialised state is a # (state, pid) pair NVML_STATE = ( NVMLState.DISABLED_PYNVML_NOT_AVAILABLE if pynvml is None else NVMLState.UNINITIALIZED ) """Current initializ...
CudaContext
python
huggingface__transformers
src/transformers/models/qwen3/configuration_qwen3.py
{ "start": 917, "end": 9078 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configura...
Qwen3Config
python
huggingface__transformers
examples/modular-transformers/modular_test_detr.py
{ "start": 290, "end": 341 }
class ____(DeformableDetrModel): pass
TestDetrModel
python
Textualize__textual
docs/examples/how-to/center03.py
{ "start": 80, "end": 461 }
class ____(App): """How to center things.""" CSS = """ Screen { align: center middle; } #hello { background: blue 50%; border: wide white; width: auto; } """ def compose(self) -> ComposeResult: yield Static("Hello, World!", id="hello") if __na...
CenterApp
python
huggingface__transformers
tests/models/clip/test_modeling_clip.py
{ "start": 26148, "end": 28988 }
class ____(unittest.TestCase): @slow def test_inference(self): model_name = "openai/clip-vit-base-patch32" model = CLIPModel.from_pretrained(model_name, attn_implementation="sdpa").to(torch_device) processor = CLIPProcessor.from_pretrained(model_name) image = prepare_img() ...
CLIPModelIntegrationTest
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 20327, "end": 20535 }
class ____(PyObjectPtr): """ Class wrapping a gdb.Value that's a PyClassObject* i.e. a <classobj> instance within the process being debugged. """ _typename = 'PyClassObject'
PyClassObjectPtr
python
PyCQA__pylint
tests/pyreverse/test_writer.py
{ "start": 1853, "end": 9608 }
class ____: """Config object for tests.""" def __init__(self) -> None: for attr, value in _DEFAULTS.items(): setattr(self, attr, value) def _file_lines(path: str) -> list[str]: # we don't care about the actual encoding, but python3 forces us to pick one with open(path, encoding="l...
Config
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0113_disable_analytics_addons.py
{ "start": 148, "end": 498 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0112_alter_project_help_text"), ] operations = [ migrations.AlterField( model_name="addonsconfig", name="analytics_enabled", field=models.BooleanField(default=...
Migration
python
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 13401, "end": 14724 }
class ____(GradientCheckpointingLayer): """This corresponds to the Block class in the timm implementation.""" def __init__(self, config: ViTMSNConfig): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = ViTMSNAt...
ViTMSNLayer
python
jina-ai__jina
tests/unit/serve/stream/test_stream.py
{ "start": 237, "end": 4742 }
class ____: def __init__(self, num_requests, prefetch, iterate_sync_in_thread): self.num_requests = num_requests self.requests_handled = [] self.results_handled = [] self.request_ids = [random_identity() for _ in range(num_requests)] self.response_ids = [] args = Nam...
RequestStreamerWrapper
python
pypa__pipenv
pipenv/vendor/click/exceptions.py
{ "start": 1157, "end": 2523 }
class ____(ClickException): """An internal exception that signals a usage error. This typically aborts any further handling. :param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some si...
UsageError
python
openai__openai-python
src/openai/types/responses/response_input_item_param.py
{ "start": 7383, "end": 8068 }
class ____(TypedDict, total=False): action: Required[ShellCallAction] """The shell commands and limits that describe how to run the tool call.""" call_id: Required[str] """The unique ID of the function shell tool call generated by the model.""" type: Required[Literal["shell_call"]] """The type...
ShellCall
python
dask__dask
dask/diagnostics/progress.py
{ "start": 680, "end": 5001 }
class ____(Callback): """A progress bar for dask. Parameters ---------- minimum : int, optional Minimum time threshold in seconds before displaying a progress bar. Default is 0 (always display) width : int, optional Width of the bar dt : float, optional Update re...
ProgressBar
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/utils.py
{ "start": 558, "end": 7982 }
class ____: """Tracks the mean, variance and count of values.""" # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm def __init__(self, epsilon=1e-4, shape=(), dtype=np.float64): """Tracks the mean, variance and count of values.""" self.mean = np.zeros(sha...
RunningMeanStd
python
pdm-project__pdm
src/pdm/cli/commands/python.py
{ "start": 1537, "end": 2031 }
class ____(BaseCommand): """List all Python interpreters installed with PDM""" arguments = (verbose_option,) def handle(self, project: Project, options: Namespace) -> None: from findpython.providers.rye import RyeProvider ui = project.core.ui provider = RyeProvider(root=Path(proje...
ListCommand
python
Textualize__textual
src/textual/widgets/_header.py
{ "start": 1334, "end": 1721 }
class ____(Widget): """The space taken up by the clock on the right of the header.""" DEFAULT_CSS = """ HeaderClockSpace { dock: right; width: 10; padding: 0 1; } """ def render(self) -> RenderResult: """Render the header clock space. Returns: ...
HeaderClockSpace