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
tests/models/blip_2/test_processing_blip_2.py
{ "start": 878, "end": 1537 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Blip2Processor @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") return tokenizer_class.from_pretrained("hf-internal-testing/tiny-random-GPT2Model") @clas...
Blip2ProcessorTest
python
catalyst-team__catalyst
catalyst/contrib/losses/ce.py
{ "start": 119, "end": 925 }
class ____(nn.Module): """@TODO: Docs. Contribution is welcome.""" def __init__(self, size_average=True): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.size_average = size_average def forward(self, input_: torch.Tensor, target: torch.Tensor) -> torch.Tensor: ...
NaiveCrossEntropyLoss
python
walkccc__LeetCode
solutions/3367. Maximize Sum of Weights after Edge Removals/3367.py
{ "start": 0, "end": 887 }
class ____: def maximizeSumOfWeights(self, edges: list[list[int]], k: int) -> int: graph = [[] for _ in range(len(edges) + 1)] for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w)) def dfs(u: int, prev: int) -> tuple[int, int]: """ Returns (the weight sum of...
Solution
python
numba__numba
numba/core/typing/builtins.py
{ "start": 12249, "end": 12668 }
class ____(ConcreteTemplate): cases = [signature(types.boolean, types.boolean)] cases += [signature(types.boolean, op) for op in sorted(types.signed_domain)] cases += [signature(types.boolean, op) for op in sorted(types.unsigned_domain)] cases += [signature(types.boolean, op) for op in sorted(types.real...
UnaryNot
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 22498, "end": 25145 }
class ____(PrefectBaseModel): """Represents one instance of a trigger firing""" id: UUID = Field(default_factory=uuid7) trigger: ServerTriggerTypes = Field( default=..., description="The trigger that is firing" ) trigger_states: Set[TriggerState] = Field( default=..., descr...
Firing
python
doocs__leetcode
lcof2/剑指 Offer II 038. 每日温度/Solution.py
{ "start": 0, "end": 346 }
class ____: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: ans = [0] * len(temperatures) stk = [] for i, t in enumerate(temperatures): while stk and temperatures[stk[-1]] < t: j = stk.pop() ans[j] = i - j stk.append(...
Solution
python
astropy__astropy
astropy/table/connect.py
{ "start": 2760, "end": 4574 }
class ____(registry.UnifiedReadWrite): """ Write this Table object out in the specified format. This function provides the Table interface to the astropy unified I/O layer. This allows easily writing a file in many supported data formats using syntax such as:: >>> from astropy.table import ...
TableWrite
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 95079, "end": 102319 }
class ____(StrategyBase): """A list of devices with a state & compute distribution policy. See [the guide](https://www.tensorflow.org/guide/distribute_strategy) for overview and examples. Note: Not all `tf.distribute.Strategy` implementations currently support TensorFlow's partitioned variables (where a sin...
StrategyV1
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 4215, "end": 4348 }
class ____(ShowFieldTypeAndContent, Model2A): objects = MyManager() field4 = models.CharField(max_length=30)
ModelWithMyManager
python
explosion__spaCy
spacy/tests/test_errors.py
{ "start": 87, "end": 333 }
class ____(metaclass=ErrorsWithCodes): E001 = "error description" def test_add_codes(): assert Errors.E001 == "[E001] error description" with pytest.raises(AttributeError): Errors.E002 assert isclass(Errors.__class__)
Errors
python
apache__airflow
providers/standard/src/airflow/providers/standard/hooks/filesystem.py
{ "start": 931, "end": 2887 }
class ____(BaseHook): """ Allows for interaction with an file server. Connection should have a name and a path specified under extra: example: Connection Id: fs_test Connection Type: File (path) Host, Schema, Login, Password, Port: empty Extra: {"path": "/tmp"} """ conn_name_a...
FSHook
python
Farama-Foundation__Gymnasium
tests/vector/test_vector_env_info.py
{ "start": 3904, "end": 5327 }
class ____(gym.Env): def __init__(self, infos): self.observation_space = Box(0, 1) self.action_space = Box(0, 1) self.infos = infos def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None, ) -> tuple[ObsType, dict[str, Any]...
ReturnInfoEnv
python
huggingface__transformers
src/transformers/models/apertus/modeling_apertus.py
{ "start": 2651, "end": 3378 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ ApertusRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): inpu...
ApertusRMSNorm
python
python-poetry__poetry
src/poetry/inspection/lazy_wheel.py
{ "start": 1001, "end": 1098 }
class ____(Exception): """Raised when a lazy wheel is unsupported."""
LazyWheelUnsupportedError
python
pytorch__pytorch
test/inductor/test_layout_optim.py
{ "start": 487, "end": 1123 }
class ____(nn.Module): def __init__(self, dim=512, manual_graph_break=False): super().__init__() self.conv1 = nn.Conv2d(3, dim, kernel_size=3, stride=2, bias=False) self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, stride=2, bias=False) self.manual_graph_break = manual_graph_break ...
Model2Conv
python
getsentry__sentry
tests/sentry/auth/providers/fly/test_provider.py
{ "start": 344, "end": 3026 }
class ____(TestCase): def setUp(self) -> None: self.auth_provider = AuthProvider.objects.create( provider=ChannelName.FLY_IO.value, organization_id=self.organization.id ) super().setUp() def test_refresh_identity_without_refresh_token(self) -> None: auth_identity = A...
FlyOAuth2ProviderTest
python
sympy__sympy
sympy/tensor/array/dense_ndim_array.py
{ "start": 4719, "end": 6403 }
class ____(DenseNDimArray, MutableNDimArray): def __new__(cls, iterable=None, shape=None, **kwargs): return cls._new(iterable, shape, **kwargs) @classmethod def _new(cls, iterable, shape, **kwargs): shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) f...
MutableDenseNDimArray
python
scrapy__scrapy
tests/test_squeues_request.py
{ "start": 4568, "end": 4752 }
class ____(TestRequestQueueBase): is_fifo = False @pytest.fixture def q(self, crawler): return LifoMemoryQueue.from_crawler(crawler=crawler)
TestLifoMemoryQueueRequest
python
wandb__wandb
wandb/vendor/pygments/lexers/jvm.py
{ "start": 18630, "end": 21751 }
class ____(RegexLexer): """ For Gosu source code. .. versionadded:: 1.5 """ name = 'Gosu' aliases = ['gosu'] filenames = ['*.gs', '*.gsx', '*.gsp', '*.vark'] mimetypes = ['text/x-gosu'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names ...
GosuLexer
python
spack__spack
lib/spack/spack/error.py
{ "start": 6513, "end": 6602 }
class ____(SpecError): """Raised when a spec file name is invalid."""
SpecFilenameError
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance19.py
{ "start": 280, "end": 328 }
class ____(ABC, metaclass=Meta1): pass
Parent1
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 93379, "end": 114314 }
class ____(Request): """ Clone an existing task :param task: ID of the task :type task: str :param new_task_name: The name of the cloned task. If not provided then taken from the original task :type new_task_name: str :param new_task_comment: The comment of the cloned task. If not p...
CloneRequest
python
kamyu104__LeetCode-Solutions
Python/friend-circles.py
{ "start": 31, "end": 953 }
class ____(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if s...
Solution
python
facebook__pyre-check
documentation/examples/pytorch/sources/_torch/__init__.py
{ "start": 633, "end": 693 }
class ____(Generic[DType, Shape], torch.Tensor): pass
Tensor
python
ipython__ipython
IPython/core/completer.py
{ "start": 17104, "end": 17899 }
class ____: """Completion item to be included in the dictionary returned by new-style Matcher (API v2). .. warning:: Provisional This class is used to describe the currently supported attributes of simple completion items, and any additional implementation details should not b...
SimpleCompletion
python
doocs__leetcode
solution/0900-0999/0967.Numbers With Same Consecutive Differences/Solution.py
{ "start": 0, "end": 482 }
class ____: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: def dfs(x: int): if x >= boundary: ans.append(x) return last = x % 10 if last + k <= 9: dfs(x * 10 + last + k) if last - k >= 0 and k != 0: ...
Solution
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_leap_year.py
{ "start": 634, "end": 1629 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_leap_year" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(...
ColumnValuesToBeValidLeapYear
python
scrapy__scrapy
tests/spiders.py
{ "start": 16107, "end": 16306 }
class ____(BytesReceivedCallbackSpider): def bytes_received(self, data, request, spider): self.meta["bytes_received"] = data raise StopDownload(fail=True)
BytesReceivedErrbackSpider
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 5154, "end": 6603 }
class ____(StringField): """A field that validates input as an URL.""" _URL_REGEX = LazyRegexCompiler( r"^(?:[a-z0-9\.\-]*)://" # scheme is validated separately r"(?:(?:[A-Z0-9](?:[A-Z0-9-_]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|" # domain... r"localhost|" # loc...
URLField
python
pandas-dev__pandas
pandas/tests/extension/base/ops.py
{ "start": 4338, "end": 7694 }
class ____(BaseOpsUtil): """ Various Series and DataFrame arithmetic ops methods. Subclasses supporting various ops should set the class variables to indicate that they support ops of that kind * series_scalar_exc = TypeError * frame_scalar_exc = TypeError * series_array_exc = TypeError ...
BaseArithmeticOpsTests
python
tqdm__tqdm
tqdm/std.py
{ "start": 1533, "end": 1638 }
class ____(TqdmWarning, DeprecationWarning): # not suppressed if raised pass
TqdmDeprecationWarning
python
getsentry__sentry
src/sentry/users/api/serializers/identity.py
{ "start": 604, "end": 1025 }
class ____(Serializer): def serialize( self, obj: Identity, attrs: Mapping[str, Any], user: User | RpcUser | AnonymousUser, **kwargs: Any, ) -> IdentitySerializerResponse: return { "id": str(obj.id), "identityProvider": serialize(obj.idp), ...
IdentitySerializer
python
run-llama__llama_index
llama-index-core/llama_index/core/storage/docstore/types.py
{ "start": 709, "end": 8404 }
class ____(ABC): # ===== Save/load ===== def persist( self, persist_path: str = DEFAULT_PERSIST_PATH, fs: Optional[fsspec.AbstractFileSystem] = None, ) -> None: """Persist the docstore to a file.""" # ===== Main interface ===== @property @abstractmethod def d...
BaseDocumentStore
python
ipython__ipython
IPython/core/payload.py
{ "start": 892, "end": 1763 }
class ____(Configurable): _payload: List = List([]) def write_payload(self, data, single=True): """Include or update the specified `data` payload in the PayloadManager. If a previous payload with the same source exists and `single` is True, it will be overwritten with the new one. ...
PayloadManager
python
anthropics__anthropic-sdk-python
tests/lib/test_bedrock.py
{ "start": 598, "end": 6141 }
class ____(TypedDict): # Available regions: https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html#available-regions name: t.Union[t.Literal["default"], str] region: str def profile_to_ini(profile: AwsConfigProfile) -> str: """ Convert an AWS config profile to an INI for...
AwsConfigProfile
python
PyCQA__pydocstyle
src/pydocstyle/config.py
{ "start": 4575, "end": 33218 }
class ____: """Responsible for parsing configuration from files and CLI. There are 2 types of configurations: Run configurations and Check configurations. Run Configurations: ------------------ Responsible for deciding things that are related to the user interface and configuration discove...
ConfigurationParser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py
{ "start": 387, "end": 479 }
class ____: def fn(self, returnable: T1) -> T1: ... T2 = TypeVar("T2", Async, Sync)
Sync
python
catalyst-team__catalyst
tests/catalyst/callbacks/test_batch_overfit.py
{ "start": 117, "end": 1654 }
class ____(dl.Callback): def __init__(self): super().__init__(order=dl.CallbackOrder.external) def on_loader_start(self, runner): # 320 samples with 32 batch size # -> 1 batch size = 32 # -> 0.1 portion = 32 assert len(runner.loaders[runner.loader_key]) == 32 def _prep...
BatchOverfitCallbackCheck
python
ionelmc__pytest-benchmark
tests/test_with_testcase.py
{ "start": 285, "end": 575 }
class ____(unittest.TestCase): @pytest.fixture(autouse=True) def setupBenchmark(self, benchmark_weave): self.benchmark_weave = benchmark_weave def test_foo2(self): self.benchmark_weave('time.sleep') time.sleep(0.0000001)
TerribleTerribleWayToWritePatchTests
python
huggingface__transformers
src/transformers/models/falcon_mamba/modular_falcon_mamba.py
{ "start": 25958, "end": 26023 }
class ____(MambaCausalLMOutput): pass
FalconMambaCausalLMOutput
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor2.py
{ "start": 649, "end": 693 }
class ____(Generic[_T1]): pass
CaveDweller
python
modin-project__modin
modin/core/execution/python/implementations/pandas_on_python/partitioning/partition_manager.py
{ "start": 1232, "end": 1722 }
class ____(PandasDataframePartitionManager): """ Class for managing partitions with pandas storage format and Python engine. Inherits all functionality from ``PandasDataframePartitionManager`` base class. """ _partition_class = PandasOnPythonDataframePartition _column_partitions_class = Pandas...
PandasOnPythonDataframePartitionManager
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar18.py
{ "start": 315, "end": 1830 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar18.xlsx") self.ignore_files = [ "xl/printerSettings/printerSettings1.bin", "xl/chartsheets/_rels/sheet1.xml.re...
TestCompareXLSXFiles
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 90450, "end": 90522 }
class ____(Binop): operation = operator.lt _operator_repr = "<"
LT
python
google__jax
jax/experimental/jax2tf/tests/flax_models/cnn.py
{ "start": 736, "end": 1234 }
class ____(nn.Module): """A simple CNN model.""" @nn.compact def __call__(self, x): x = nn.Conv(features=32, kernel_size=(3, 3))(x) x = nn.relu(x) x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2)) x = nn.Conv(features=64, kernel_size=(3, 3))(x) x = nn.relu(x) x = nn.avg_pool(x, wind...
CNN
python
anthropics__anthropic-sdk-python
src/anthropic/lib/_extras/_common.py
{ "start": 165, "end": 348 }
class ____(AnthropicError): def __init__(self, *, library: str, extra: str) -> None: super().__init__(INSTRUCTIONS.format(library=library, extra=extra))
MissingDependencyError
python
Textualize__textual
docs/examples/guide/layout/utility_containers.py
{ "start": 132, "end": 636 }
class ____(App): CSS_PATH = "utility_containers.tcss" def compose(self) -> ComposeResult: yield Horizontal( Vertical( Static("One"), Static("Two"), classes="column", ), Vertical( Static("Three"), ...
UtilityContainersExample
python
pytorch__pytorch
torch/_dynamo/utils.py
{ "start": 169485, "end": 173095 }
class ____(int): def __add__(self, other: Any) -> CompileCounterInt: return CompileCounterInt(super().__add__(other)) def set_feature_use(feature: str, usage: bool) -> None: """ Records whether we are using a feature Generally a feature is a JK. """ # Note that sometimes (tests etc...)...
CompileCounterInt
python
tensorflow__tensorflow
tensorflow/python/ops/numpy_ops/np_interop_test.py
{ "start": 2473, "end": 12184 }
class ____(tf.test.TestCase): def setUp(self): super(InteropTest, self).setUp() physical_devices = tf.config.list_physical_devices('CPU') configs = tf.config.get_logical_device_configuration(physical_devices[0]) if configs is None: logical_devices = [ tf.config.LogicalDeviceConfigurat...
InteropTest
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 49621, "end": 50148 }
class ____(FieldValues): """ Valid and invalid values for `DateTimeField` with a custom input format. """ valid_inputs = { '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=utc), } invalid_inputs = { '2001-01-01T20:50': ['Datetime has wrong format. Use one of the...
TestCustomInputFormatDateTimeField
python
bokeh__bokeh
src/bokeh/models/nodes.py
{ "start": 4618, "end": 6412 }
class ____(Coordinate): """ Represents a symbolic coordinate (by name). .. note:: This model is experimental and may change at any point. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ...
Node
python
django__django
tests/i18n/tests.py
{ "start": 78116, "end": 78583 }
class ____(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override(...
TranslationFallbackI18NTests
python
encode__starlette
starlette/authentication.py
{ "start": 4306, "end": 4570 }
class ____(BaseUser): def __init__(self, username: str) -> None: self.username = username @property def is_authenticated(self) -> bool: return True @property def display_name(self) -> str: return self.username
SimpleUser
python
pytorch__pytorch
torch/_subclasses/complex_tensor/_core.py
{ "start": 347, "end": 4692 }
class ____(Tensor): """A class that decomposes all ops on complex Tensors into their real and imaginary parts.""" _re: Tensor _im: Tensor def __new__(cls, real: Tensor, imag: Tensor) -> Self: """Initialize a ComplexTensor from its real and imaginary parts.""" from ._ops.common import R...
ComplexTensor
python
kamyu104__LeetCode-Solutions
Python/non-overlapping-intervals.py
{ "start": 473, "end": 993 }
class ____(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda interval: interval[0]) result, prev = 0, 0 for i in xrange(1, len(intervals)): if intervals[i][0] < inter...
Solution2
python
wandb__wandb
wandb/vendor/promise-2.3.0/tests/test_spec.py
{ "start": 174, "end": 13441 }
class ____: """ A helper class with some side effects we can test. """ def __init__(self): self.count = 0 def tick(self): self.count += 1 def value(self): return self.count def test_3_2_1(): """ Test that the arguments to 'then' are optional. """ ...
Counter
python
pyqtgraph__pyqtgraph
pyqtgraph/dockarea/Dock.py
{ "start": 8456, "end": 12456 }
class ____(VerticalLabel): sigClicked = QtCore.Signal(object, object) sigCloseClicked = QtCore.Signal() def __init__(self, text, closable=False, fontSize="12px"): self.dim = False self.fixedWidth = False self.fontSize = fontSize VerticalLabel.__init__(self, text, orientatio...
DockLabel
python
huggingface__transformers
tests/models/cohere/test_modeling_cohere.py
{ "start": 1328, "end": 5841 }
class ____: config_class = CohereConfig if is_torch_available(): model_class = CohereModel for_causal_lm_class = CohereForCausalLM def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_toke...
CohereModelTester
python
google__pytype
pytype/pytd/booleq.py
{ "start": 174, "end": 1558 }
class ____: """Base class for boolean terms.""" __slots__ = () def simplify(self, assignments): """Simplify this term, given a list of possible values for each variable. Args: assignments: A list of possible values for each variable. A dictionary mapping strings (variable name) to sets of...
BooleanTerm
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/spacetobatch_op_test.py
{ "start": 3202, "end": 3455 }
class ____(object): @staticmethod def space_to_batch(*args, **kwargs): return gen_array_ops.space_to_batch(*args, **kwargs) @staticmethod def batch_to_space(*args, **kwargs): return gen_array_ops.batch_to_space(*args, **kwargs)
CppOpImpl
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 48429, "end": 61562 }
class ____(NonStrictDataModel): """ :param id: Dataset ID :type id: str :param name: Dataset name :type name: str :param user: Associated user ID :type user: str :param company: Company ID :type company: str :param created: Dataset creation time (UTC) :type created: datetime....
Dataset
python
keras-team__keras
keras/src/ops/core.py
{ "start": 27616, "end": 28397 }
class ____(Operation): def __init__(self, dtype, *, name=None): super().__init__(name=name) self.dtype = backend.standardize_dtype(dtype) def call(self, x): return backend.core.cast(x, self.dtype) def compute_output_spec(self, x): return backend.KerasTensor(shape=x.shape, d...
Cast
python
streamlit__streamlit
lib/tests/streamlit/runtime/context_test.py
{ "start": 7255, "end": 8572 }
class ____(unittest.TestCase): """Test StreamlitCookies class methods.""" def test_cookies_getitem(self): """Test that __getitem__ returns cookie value.""" cookies = StreamlitCookies({"session_id": "abc123", "user_id": "456"}) assert cookies["session_id"] == "abc123" assert cook...
StreamlitCookiesTest
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 24157, "end": 24811 }
class ____(PointEvent): ''' Announce the start of a rotate event on a Bokeh plot. Attributes: sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coo...
RotateStart
python
doocs__leetcode
solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/Solution.py
{ "start": 0, "end": 293 }
class ____: def reinitializePermutation(self, n: int) -> int: ans, i = 0, 1 while 1: ans += 1 if i < n >> 1: i <<= 1 else: i = (i - (n >> 1)) << 1 | 1 if i == 1: return ans
Solution
python
geekcomputers__Python
thread_signal.py
{ "start": 95, "end": 738 }
class ____(threading.Thread): def __init__(self, event): threading.Thread.__init__(self) self.event = event def run(self): while self.event.is_set(): print("sub thread") sleep(2) else: print("sub thread end") exit() def handler_t...
producer
python
numba__numba
numba/core/typing/collections.py
{ "start": 596, "end": 839 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws (val,) = args if isinstance(val, (types.Container)): return signature(types.intp, val) @infer_global(operator.truth)
ContainerLen
python
pyca__cryptography
src/cryptography/fernet.py
{ "start": 661, "end": 5225 }
class ____: def __init__( self, key: bytes | str, backend: typing.Any = None, ) -> None: try: key = base64.urlsafe_b64decode(key) except binascii.Error as exc: raise ValueError( "Fernet key must be 32 url-safe base64-encoded bytes."...
Fernet
python
ApeWorX__ape
tests/integration/cli/utils.py
{ "start": 462, "end": 899 }
class ____: """ A class that extracts a callable test's name and module name. """ def __init__(self, test_method: Callable): self.module_full_name = test_method.__module__ self.name = test_method.__name__ @property def module_name(self) -> str: return self.module_full_n...
NodeId
python
ray-project__ray
python/ray/util/client/dataclient.py
{ "start": 7522, "end": 22951 }
class ____: def __init__(self, client_worker: "Worker", client_id: str, metadata: list): """Initializes a thread-safe datapath over a Ray Client gRPC channel. Args: client_worker: The Ray Client worker that manages this client client_id: the generated ID representing this cl...
DataClient
python
huggingface__transformers
src/transformers/models/m2m_100/modeling_m2m_100.py
{ "start": 40429, "end": 45875 }
class ____(M2M100PreTrainedModel): _tied_weights_keys = { "decoder.embed_tokens.weight": "shared.weight", "encoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: M2M100Config): super().__init__(config) padding_idx, vocab_size = config.pad_token_id, conf...
M2M100Model
python
conda__conda
conda/models/prefix_graph.py
{ "start": 14427, "end": 16633 }
class ____(PrefixGraph): """ Compared with PrefixGraph, this class takes in more than one record of a given name, and operates on that graph from the higher view across any matching dependencies. It is not a Prefix thing, but more like a "graph of all possible candidates" thing, and is used for uns...
GeneralGraph
python
getsentry__sentry
tests/sentry/middleware/test_access_log_middleware.py
{ "start": 8509, "end": 9667 }
class ____(LogCaptureAPITestCase): endpoint = "concurrent-ratelimit-endpoint" def test_concurrent_request_finishes(self) -> None: self._caplog.set_level(logging.INFO, logger="sentry") for i in range(10): self.get_success_response() # these requests were done in succession, s...
TestAccessLogConcurrentRateLimited
python
pyinstaller__pyinstaller
PyInstaller/depend/analysis.py
{ "start": 3064, "end": 51122 }
class ____(ModuleGraph): """ Directed graph whose nodes represent modules and edges represent dependencies between these modules. This high-level subclass wraps the lower-level `ModuleGraph` class with support for graph and runtime hooks. While each instance of `ModuleGraph` represents a set of disconn...
PyiModuleGraph
python
h5py__h5py
h5py/tests/test_file.py
{ "start": 677, "end": 4585 }
class ____(TestCase): """ Feature: Opening files with Python-style modes. """ def test_default(self): """ Default semantics in the presence or absence of a file """ fname = self.mktemp() # No existing file; error with pytest.raises(FileNotFoundError): w...
TestFileOpen
python
python__mypy
mypyc/test/test_rarray.py
{ "start": 268, "end": 1488 }
class ____(unittest.TestCase): def test_basics(self) -> None: a = RArray(int_rprimitive, 10) assert a.item_type == int_rprimitive assert a.length == 10 def test_str_conversion(self) -> None: a = RArray(int_rprimitive, 10) assert str(a) == "int[10]" assert repr(a)...
TestRArray
python
Netflix__metaflow
metaflow/sidecar/sidecar_subprocess.py
{ "start": 1028, "end": 9708 }
class ____(object): def __init__(self, worker_type): # type: (str, dict) -> None self._worker_type = worker_type # Sub-process launched and poller used self._process = None self._poller = None # Retry counts when needing to send a MUST_SEND message self._sen...
SidecarSubProcess
python
pytorch__pytorch
torch/ao/nn/quantized/reference/modules/rnn.py
{ "start": 10422, "end": 12539 }
class ____(RNNCellBase): """ We'll store weight_qparams for all the weights (weight_ih and weight_hh), we need to pass in a `weight_qparams_dict` that maps from weight name, e.g. weight_ih, to the weight_qparams for that weight """ def __init__( self, input_size: int, hi...
GRUCell
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1048012, "end": 1048422 }
class ____(VegaLiteSchema): """ RowColboolean schema wrapper. Parameters ---------- column : bool row : bool """ _schema = {"$ref": "#/definitions/RowCol<boolean>"} def __init__( self, column: Optional[bool] = Undefined, row: Optional[bool] = Undefined, ...
RowColboolean
python
django__django
django/db/models/lookups.py
{ "start": 22713, "end": 22801 }
class ____(StartsWith): lookup_name = "istartswith" @Field.register_lookup
IStartsWith
python
MongoEngine__mongoengine
tests/fields/test_enum_field.py
{ "start": 4831, "end": 4913 }
class ____(Document): color = EnumField(Color, default=Color.RED)
ModelWithColor
python
neetcode-gh__leetcode
python/0463-island-perimeter.py
{ "start": 0, "end": 635 }
class ____: def islandPerimeter(self, grid: List[List[int]]) -> int: visit = set() def dfs(i, j): if i >= len(grid) or j >= len(grid[0]) or i < 0 or j < 0 or grid[i][j] == 0: return 1 if (i, j) in visit: return 0 visit.add((i, j))...
Solution
python
numba__numba
numba/core/ir.py
{ "start": 40097, "end": 40405 }
class ____(SlotEqualityCheckMixin): """Describes a loop-block """ __slots__ = "entry", "exit" def __init__(self, entry, exit): self.entry = entry self.exit = exit def __repr__(self): args = self.entry, self.exit return "Loop(entry=%s, exit=%s)" % args
Loop
python
MongoEngine__mongoengine
mongoengine/base/common.py
{ "start": 367, "end": 2796 }
class ____: """Wrapper for the document registry (providing a singleton pattern). This is part of MongoEngine's internals, not meant to be used directly by end-users """ @staticmethod def get(name): doc = _document_registry.get(name, None) if not doc: # Possible old styl...
_DocumentRegistry
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/cloud_build.py
{ "start": 24161, "end": 25394 }
class ____(GoogleBaseHook): """Asynchronous Hook for the Google Cloud Build Service.""" @GoogleBaseHook.fallback_to_default_project_id async def get_cloud_build( self, id_: str, project_id: str = PROVIDE_PROJECT_ID, retry: AsyncRetry | _MethodDefault = DEFAULT, timeo...
CloudBuildAsyncHook
python
pytorch__pytorch
test/distributed/nn/jit/test_instantiator.py
{ "start": 647, "end": 1823 }
class ____(TestCase): def test_get_arg_return_types_from_interface(self): ( args_str, arg_types_str, return_type_str, ) = instantiator.get_arg_return_types_from_interface(MyModuleInterface) self.assertEqual(args_str, "tensor, number, word") self.as...
TestInstantiator
python
huggingface__transformers
tests/quantization/fp_quant_integration/test_fp_quant.py
{ "start": 5889, "end": 6090 }
class ____(FPQuantBaseTest): @classmethod def getQuantizationConfig(cls): return FPQuantConfig(forward_dtype="nvfp4", pseudoquantization=True) @require_qutlass
FPQuantNVFP4PseudoquantTest
python
getsentry__sentry
src/sentry/models/avatars/organization_avatar.py
{ "start": 247, "end": 1001 }
class ____(AvatarBase): """ An OrganizationAvatar associates an Organization with their avatar photo File and contains their preferences for avatar type. """ AVATAR_TYPES = ((0, "letter_avatar"), (1, "upload")) FILE_TYPE = "avatar.file" file_id = BoundedBigIntegerField(unique=True, null=T...
OrganizationAvatar
python
davidhalter__parso
parso/pgen2/generator.py
{ "start": 4577, "end": 14580 }
class ____: """ Most grammars will have certain keywords and operators that are mentioned in the grammar as strings (e.g. "if") and not token types (e.g. NUMBER). This class basically is the former. """ def __init__(self, value: str): self.value = value def __repr__(self): ...
ReservedString
python
doocs__leetcode
solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/Solution.py
{ "start": 0, "end": 122 }
class ____: def makeStringsEqual(self, s: str, target: str) -> bool: return ("1" in s) == ("1" in target)
Solution
python
pandas-dev__pandas
pandas/tests/indexes/base_class/test_reshape.py
{ "start": 153, "end": 3138 }
class ____: def test_repeat(self): repeats = 2 index = Index([1, 2, 3]) expected = Index([1, 1, 2, 2, 3, 3]) result = index.repeat(repeats) tm.assert_index_equal(result, expected) def test_insert(self): # GH 7256 # validate neg/pos inserts result...
TestReshape
python
readthedocs__readthedocs.org
readthedocs/organizations/views/private.py
{ "start": 5493, "end": 5900 }
class ____(PrivateViewMixin, OrganizationOwnerView, DeleteViewWithMessage): success_message = _("Owner removed") http_method_names = ["post"] def post(self, request, *args, **kwargs): if self._is_last_user(): return HttpResponseBadRequest(_("User is the last owner, can't be removed")) ...
DeleteOrganizationOwner
python
chardet__chardet
chardet/euckrprober.py
{ "start": 1295, "end": 1687 }
class ____(MultiByteCharSetProber): def __init__(self) -> None: super().__init__() self.coding_sm = CodingStateMachine(EUCKR_SM_MODEL) self.distribution_analyzer = EUCKRDistributionAnalysis() self.reset() @property def charset_name(self) -> str: return "EUC-KR" ...
EUCKRProber
python
pydata__xarray
xarray/tests/test_plot.py
{ "start": 43502, "end": 48002 }
class ____: @pytest.fixture(autouse=True) def setUp(self): x = np.arange(start=0, stop=10, step=2) y = np.arange(start=9, stop=-7, step=-3) xy = np.dstack(np.meshgrid(x, y)) distance = np.linalg.norm(xy, axis=2) self.darray = DataArray(distance, list(zip(("y", "x"), (y, x...
TestDiscreteColorMap
python
jschneier__django-storages
tests/test_s3.py
{ "start": 37053, "end": 37316 }
class ____(TestCase): def setUp(self): self.storage = s3.S3StaticStorage() self.storage._connections.connection = mock.MagicMock() def test_querystring_auth(self): self.assertFalse(self.storage.querystring_auth)
S3StaticStorageTests
python
matplotlib__matplotlib
lib/matplotlib/backend_bases.py
{ "start": 42029, "end": 42884 }
class ____(Event): """ An event triggered by a draw operation on the canvas. In most backends, callbacks subscribed to this event will be fired after the rendering is complete but before the screen is updated. Any extra artists drawn to the canvas's renderer will be reflected without an explici...
DrawEvent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_format17.py
{ "start": 350, "end": 1336 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("format17.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with a pattern only.""" workbook = Wo...
TestCompareXLSXFiles
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_Q.py
{ "start": 2547, "end": 3808 }
class ____(Benchmark): r""" Quintic objective function. This class defines the Quintic [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Quintic}}(x) = \sum_{i=1}^{n} \left|{x_{i}^{5} - 3 x_{i}^{4} + 4 x_{i}^{3} + 2 ...
Quintic
python
astropy__astropy
astropy/utils/misc.py
{ "start": 11798, "end": 18090 }
class ____(json.JSONEncoder): """Support for data types that JSON default encoder does not do. This includes: * Numpy array or number * Complex number * Set * Bytes * astropy.UnitBase * astropy.Quantity Examples -------- >>> import json >>> ...
JsonCustomEncoder
python
huggingface__transformers
tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py
{ "start": 16706, "end": 17754 }
class ____(unittest.TestCase): @slow def test_inference(self): model = VisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian", logit_scale_init_value=1.0) processor = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian") image = Image.open("./tests/...
VisionTextDualEncoderIntegrationTest