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
ansible__ansible
lib/ansible/module_utils/errors.py
{ "start": 293, "end": 725 }
class ____(Exception): """Single argument spec validation error""" def __init__(self, message): super(AnsibleValidationError, self).__init__(message) self.error_message = message """The error message passed in when the exception was raised.""" @property def msg(self): "...
AnsibleValidationError
python
viewflow__viewflow
tests/fsm/test_fsm__conditions.py
{ "start": 615, "end": 1491 }
class ____(TestCase): def test_conditions_met(self): publication = _Publication("test" * 251) publication.publish() def test_unmet_conditions_raises_exception(self): publication = _Publication("test" * 249) with self.assertRaises(TransitionNotAllowed): publication.pu...
_Test
python
Pylons__pyramid
src/pyramid/security.py
{ "start": 9537, "end": 12319 }
class ____: """Mixin for Request class providing compatibility properties.""" @property def unauthenticated_userid(self): """ .. deprecated:: 2.0 ``unauthenticated_userid`` does not have an equivalent in the new security system. Use :attr:`.authenticated_userid` or ...
AuthenticationAPIMixin
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataplex.py
{ "start": 7019, "end": 8013 }
class ____: @mock.patch(HOOK_STR) def test_execute(self, hook_mock): op = DataplexListTasksOperator( project_id=PROJECT_ID, region=REGION, lake_id=LAKE_ID, task_id="list_dataplex_task", api_version=API_VERSION, gcp_conn_id=GCP_CONN_...
TestDataplexListTasksOperator
python
getsentry__sentry
src/sentry/taskworker/scheduler/runner.py
{ "start": 2882, "end": 6058 }
class ____: """An individual task that can be scheduled to be run.""" def __init__(self, *, key: str, task: Task[Any, Any], schedule: timedelta | crontab) -> None: self._key = key self._task = task scheduler: Schedule if isinstance(schedule, crontab): scheduler = Cro...
ScheduleEntry
python
walkccc__LeetCode
solutions/2093. Minimum Cost to Reach City With Discounts/2093.py
{ "start": 0, "end": 798 }
class ____: def minimumCost( self, n: int, highways: list[list[int]], discounts: int, ) -> int: graph = [[] for _ in range(n)] minHeap = [(0, 0, discounts)] # (d, u, leftDiscounts) minDiscounts = {} for city1, city2, toll in highways: graph[city1].append((city2, toll)...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 39715, "end": 40176 }
class ____(InvokeDDLBase): @contextlib.contextmanager def with_ddl_events(self, target, **kw): """helper context manager that will apply appropriate DDL events to a CREATE or DROP operation.""" target.dispatch.before_drop( target, self.connection, _ddl_runner=self, **kw ...
InvokeDropDDLBase
python
pytorch__pytorch
tools/stats/utilization_stats_lib.py
{ "start": 263, "end": 393 }
class ____: avg: float | None = None max: float | None = None raw: list[float] | None = None @dataclass
UtilizationStats
python
imageio__imageio
imageio/plugins/_bsdf.py
{ "start": 30259, "end": 31712 }
class ____(object): """Base class to implement BSDF extensions for special data types. Extension classes are provided to the BSDF serializer, which instantiates the class. That way, the extension can be somewhat dynamic: e.g. the NDArrayExtension exposes the ndarray class only when numpy is importe...
Extension
python
getsentry__sentry
src/sentry/workflow_engine/utils/log_context.py
{ "start": 1448, "end": 1841 }
class ____: """The data consulted when modifying log records.""" verbose: bool = False # TODO: Hide `extra` and have a `set_extra` method to ensure nobody is using # context extra data in business logic. extra: dict[str, Any] = field(default_factory=dict) _log_context_state = contextvars.Context...
LogContextData
python
doocs__leetcode
solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/Solution.py
{ "start": 0, "end": 571 }
class ____: def maxProfit(self, prices: List[int], profits: List[int]) -> int: n = len(prices) ans = -1 for j, x in enumerate(profits): left = right = 0 for i in range(j): if prices[i] < prices[j] and left < profits[i]: left = profi...
Solution
python
wandb__wandb
tests/system_tests/test_functional/metaflow/flow_pytorch.py
{ "start": 3387, "end": 4943 }
class ____(nn.Module): def __init__(self): super().__init__() self.fc = nn.Linear(784, 10) def forward(self, x): x = torch.flatten(x, 1) x = self.fc(x) output = F.log_softmax(x, dim=1) return output def train(model, device, train_loader, optimizer, epoch, log_i...
Net
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/util.py
{ "start": 5710, "end": 5886 }
class ____(Protocol): def __call__(self, name: str, module_name: str) -> Any: ... eval_name_only = cast(_EvalNameOnly, _de_stringify_partial(_eval_name_only))
_EvalNameOnly
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_theme12.py
{ "start": 350, "end": 2230 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_theme12.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Wo...
TestCompareXLSXFiles
python
apache__airflow
providers/smtp/tests/unit/smtp/notifications/test_smtp.py
{ "start": 2797, "end": 8571 }
class ____: @mock.patch("airflow.providers.smtp.notifications.smtp.SmtpHook") def test_notifier(_self, mock_smtphook_hook, create_dag_without_db): notifier = send_smtp_notification(**NOTIFIER_DEFAULT_PARAMS) notifier({"dag": create_dag_without_db(TEST_DAG_ID)}) mock_smtphook_hook.return_...
TestSmtpNotifier
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 2976, "end": 3163 }
class ____(Proto_ContraRecurs): # This should generate a reportIncompatibleMethodOverride error. def m(self, x: "Impl_ContraRecursExplicit1") -> None: ...
Impl_ContraRecursExplicit1
python
google__pytype
pytype/tests/test_type_comments1.py
{ "start": 105, "end": 8405 }
class ____(test_base.BaseTest): """Tests for type comments.""" def test_function_unspecified_args(self): ty = self.Infer(""" def foo(x): # type: (...) -> int return x """) self.assertTypesMatchPytd( ty, """ def foo(x) -> int: ... """, ) def test_fu...
FunctionCommentTest
python
pypa__warehouse
tests/unit/integration/test_package.py
{ "start": 91, "end": 879 }
class ____: def test_set(self): cache = integrations.PublicKeysCache(cache_time=10) cache.set(now=1, value="foo") assert cache.cached_at == 1 assert cache.cache == "foo" def test_get_no_cache(self): cache = integrations.PublicKeysCache(cache_time=10) with pytes...
TestCache
python
langchain-ai__langchain
libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py
{ "start": 1473, "end": 3346 }
class ____(BaseOutputParser): """Trajectory output parser.""" @property def _type(self) -> str: return "agent_trajectory" def parse(self, text: str) -> TrajectoryEval: """Parse the output text and extract the score and reasoning. Args: text: The output text to pars...
TrajectoryOutputParser
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 11752, "end": 12102 }
class ____(BaseModel): """ DAG schedule reference serializer for assets. """ model_config = ConfigDict( extra="forbid", ) dag_id: Annotated[str, Field(title="Dag Id")] created_at: Annotated[datetime, Field(title="Created At")] updated_at: Annotated[datetime, Field(title="Updated...
DagScheduleAssetReference
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 23875, "end": 26087 }
class ____(NonStrictDataModel): """ :param input: The list of task input models :type input: Sequence[TaskModelItem] :param output: The list of task output models :type output: Sequence[TaskModelItem] """ _schema = { "properties": { "input": { "descriptio...
TaskModels
python
spack__spack
lib/spack/spack/solver/splicing.py
{ "start": 308, "end": 3031 }
class ____(NamedTuple): #: The spec being spliced into a parent splice_spec: Spec #: The name of the child that splice spec is replacing child_name: str #: The hash of the child that ``splice_spec`` is replacing child_hash: str def _resolve_collected_splices( specs: List[Spec], splices: Di...
Splice
python
pydata__xarray
xarray/tests/test_indexes.py
{ "start": 893, "end": 984 }
class ____(Index): def __init__(self, dims) -> None: self.dims = dims
CustomIndex
python
Textualize__textual
docs/examples/guide/styles/box_sizing01.py
{ "start": 401, "end": 1193 }
class ____(App): def compose(self) -> ComposeResult: self.widget1 = Static(TEXT) yield self.widget1 self.widget2 = Static(TEXT) yield self.widget2 def on_mount(self) -> None: self.widget1.styles.background = "purple" self.widget2.styles.background = "darkgreen" ...
BoxSizing
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 2444, "end": 2558 }
class ____(Contra[Contra[Contra[T_co]]]): ... Co_TA = Co[T_co] Contra_TA = Contra[T_contra]
ContraToContraToContra
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 9668, "end": 9896 }
class ____(BaseModel): """ DAG Tags Collection serializer for responses. """ tags: Annotated[list[str], Field(title="Tags")] total_entries: Annotated[int, Field(title="Total Entries")]
DAGTagCollectionResponse
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 110688, "end": 112510 }
class ____(LogitsProcessor): r""" [`LogitsProcessor`] enforcing alternated generation between the two codebooks of Bark. <Tip warning={true}> This logits processor is exclusively compatible with [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark)'s fine submodel. See the model docum...
AlternatingCodebooksLogitsProcessor
python
pytorch__pytorch
benchmarks/tensorexpr/rnn_eltwise.py
{ "start": 40, "end": 1984 }
class ____(benchmark.Benchmark): def __init__(self, mode, device, dtype, b, hs): super().__init__(mode, device, dtype) self.b = b self.hs = hs self.input = self.rand( [b, 4 * hs], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.hx = sel...
RNNEltwise
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 3607, "end": 3668 }
class ____(RuntimeError): reason: str
MetadataMismatchError
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/hooks/test_hive.py
{ "start": 2015, "end": 13716 }
class ____: @mock.patch("tempfile.tempdir", "/tmp/") @mock.patch("tempfile._RandomNameSequence.__next__") @mock.patch("subprocess.Popen") def test_run_cli(self, mock_popen, mock_temp_dir): mock_subprocess = MockSubProcess() mock_popen.return_value = mock_subprocess mock_temp_dir....
TestHiveCliHook
python
justquick__django-activity-stream
actstream/feeds.py
{ "start": 3999, "end": 5630 }
class ____(Atom1Feed): """ Feed rendering class for the v1.0 Atom Activity Stream Spec """ def root_attributes(self): attrs = super(ActivityStreamsAtomFeed, self).root_attributes() attrs['xmlns:activity'] = 'http://activitystrea.ms/spec/1.0/' return attrs def add_root_eleme...
ActivityStreamsAtomFeed
python
django__django
tests/expressions/tests.py
{ "start": 115054, "end": 116204 }
class ____(SimpleTestCase): def test_equal(self): self.assertEqual( OrderBy(F("field"), nulls_last=True), OrderBy(F("field"), nulls_last=True), ) self.assertNotEqual( OrderBy(F("field"), nulls_last=True), OrderBy(F("field")), ) def...
OrderByTests
python
doocs__leetcode
solution/0800-0899/0841.Keys and Rooms/Solution2.py
{ "start": 0, "end": 321 }
class ____: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: vis = set() q = deque([0]) while q: i = q.popleft() if i in vis: continue vis.add(i) q.extend(j for j in rooms[i]) return len(vis) == len(rooms)
Solution
python
plotly__plotly.py
plotly/graph_objs/sunburst/_marker.py
{ "start": 233, "end": 21266 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "sunburst" _path_str = "sunburst.marker" _valid_props = { "autocolorscale", "cauto", "cmax", "cmid", "cmin", "coloraxis", "colorbar", "colors", "colorscale", "colorssrc", ...
Marker
python
numpy__numpy
tools/swig/test/testTensor.py
{ "start": 13761, "end": 14065 }
class ____(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" self.result = int(self.result) ######################################################################
ulongTestCase
python
python-visualization__folium
folium/features.py
{ "start": 3063, "end": 7030 }
class ____(JSCSSMixin): """ Creates a Vega chart element. Parameters ---------- data: JSON-like str or object The Vega description of the chart. It can also be any object that has a method `to_json`, so that you can (for instance) provide a `vincent` chart. width: int or...
Vega
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 22128, "end": 22903 }
class ____(ExpressionElementImpl, RoleImpl): __slots__ = () def _literal_coercion( # type: ignore[override] self, element, *, expr, operator, bindparam_type=None, argname=None, **kw, ): try: return expr._bind_param(operato...
BinaryElementImpl
python
great-expectations__great_expectations
contrib/time_series_expectations/time_series_expectations/generator/time_series_generator.py
{ "start": 88, "end": 416 }
class ____(TypedDict): """Parameters for a trend segment of a time series. Each segment of a time series has a different alpha and beta value, corresponding to a different slope and intercept. Boundaries between segments are called "cutpoints." """ alpha: float beta: float cutpoint: int ...
TrendParams
python
google__jax
tests/lax_test.py
{ "start": 177011, "end": 191576 }
class ____(jtu.JaxTestCase): @parameterized.named_parameters( dict(testcase_name=f"_{dtype.__name__}", dtype=dtype) for dtype in jtu.dtypes.supported([np.float32, np.float64, np.complex64, np.complex128])) def testMPMathUtils(self, dtype): try: import mpmath except ImportError as msg: s...
FunctionAccuracyTest
python
django__django
tests/queries/tests.py
{ "start": 175660, "end": 176112 }
class ____(TestCase): def test_ticket_22429(self): sc1 = School.objects.create() st1 = Student.objects.create(school=sc1) sc2 = School.objects.create() st2 = Student.objects.create(school=sc2) cr = Classroom.objects.create(school=sc1) cr.students.add(st1) q...
Ticket22429Tests
python
PyCQA__pylint
tests/functional/r/regression/regression_implicit_none_with_no_return.py
{ "start": 70, "end": 402 }
class ____: def func(self): print('hello') @property def index(self): print('world') # Since these are not assigned anywhere, assignment-from-none etc. # in typecheck does not warn a = A() # double call is workaround for #4426 a.func()() # [not-callable] [1, 2, 3][a.index] # [invalid-s...
A
python
ZoranPandovski__al-go-rithms
data_structures/Arrays/Python/valid_parenthesis.py
{ "start": 614, "end": 1771 }
class ____: def isValid(self, s: str) -> bool: # Here we use a list/stack to store the opening brackets. # when we encounter an opening bracket, we store it in the temp list # When we encounter a closing bracket, we check if the last encountered opening bracket is a match....
Solution
python
getsentry__sentry
src/sentry/grouping/fingerprinting/__init__.py
{ "start": 737, "end": 5359 }
class ____: def __init__( self, rules: Sequence[FingerprintRule], version: int | None = None, bases: Sequence[str] | None = None, ) -> None: if version is None: version = VERSION self.version = version self.rules = rules self.bases = ba...
FingerprintingConfig
python
fastai__fastai
fastai/losses.py
{ "start": 3537, "end": 4430 }
class ____(Module): y_int=True # y interpolation def __init__(self, gamma:float=2.0, # Focusing parameter. Higher values down-weight easy examples' contribution to loss weight:Tensor=None, # Manual rescaling weight given to each class reduction:str='mean' # PyTorch reduction to apply to...
FocalLoss
python
huggingface__transformers
src/transformers/models/informer/modeling_informer.py
{ "start": 12107, "end": 17709 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
InformerAttention
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 2990, "end": 3295 }
class ____(models.Model): some_objects = CustomPollManager() all_objects = models.Manager() question = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") hidden = models.BooleanField(default=False) history = HistoricalRecords()
PollWithCustomManager
python
django__django
django/contrib/postgres/fields/hstore.py
{ "start": 3256, "end": 3383 }
class ____(Transform): lookup_name = "values" function = "avals" output_field = ArrayField(TextField())
ValuesTransform
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_checks.py
{ "start": 2131, "end": 3722 }
class ____(graphene.ObjectType): timestamp = graphene.Field( graphene.NonNull(graphene.Float), description="When the check evaluation was stored" ) checkName = graphene.NonNull(graphene.String) assetKey = graphene.NonNull(GrapheneAssetKey) targetMaterialization = graphene.Field(GrapheneAsset...
GrapheneAssetCheckEvaluation
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/dataproc.py
{ "start": 6408, "end": 6605 }
class ____(BaseGoogleLink): """Helper class for constructing Dataproc Batch Link.""" name = "Dataproc Batch" key = "dataproc_batch" format_str = DATAPROC_BATCH_LINK
DataprocBatchLink
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/contexts/click_pipeline_context.py
{ "start": 452, "end": 5275 }
class ____(BaseModel, Singleton): """ A replacement class for the Click context object passed to click functions. This class is meant to serve as a singleton object that initializes and holds onto a single instance of the Dagger client, which is used to create containers for running pipelines. """ ...
ClickPipelineContext
python
pytorch__pytorch
test/fx/test_fx_split.py
{ "start": 4203, "end": 8144 }
class ____(TestCase): class TestModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear1 = torch.nn.Linear(2, 3) self.linear2 = torch.nn.Linear(4, 5) self.linear3 = torch.nn.Linear(6, 7) self.linear4 = torch.nn.Linear(8,...
TestSplitByTags
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 9127, "end": 9263 }
class ____(IncrementalShopifyStreamWithDeletedEvents): data_field = "price_rules" deleted_events_api_name = "PriceRule"
PriceRules
python
instagram__MonkeyType
tests/test_tracing.py
{ "start": 524, "end": 1127 }
class ____(CallTraceLogger): def __init__(self): super(TraceCollector, self).__init__() self.traces = [] self.flushed = False def log(self, trace: CallTrace): self.traces.append(trace) def flush(self): self.flushed = True def simple_add(a: int, b: int) -> int: ...
TraceCollector
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property17.py
{ "start": 389, "end": 477 }
class ____(Protocol[T_co]): @property def root(self) -> Proto[T_co]: ...
RootProto
python
getsentry__sentry-python
sentry_sdk/consts.py
{ "start": 27523, "end": 53823 }
class ____: def __init__( self, dsn=None, # type: Optional[str] *, max_breadcrumbs=DEFAULT_MAX_BREADCRUMBS, # type: int release=None, # type: Optional[str] environment=None, # type: Optional[str] server_name=None, # type: Optional[str] shutdown_ti...
ClientConstructor
python
django__django
tests/middleware_exceptions/middleware.py
{ "start": 1669, "end": 1873 }
class ____(BaseMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): log.append("processed view %s" % view_func.__name__) return None
ProcessViewNoneMiddleware
python
huggingface__transformers
src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py
{ "start": 3918, "end": 5732 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.conv = nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size=config.num_conv_pos_embeddings, padding=config.num_conv_pos_embeddings // 2, groups=config.num_...
Wav2Vec2ConformerPositionalConvEmbedding
python
kubernetes-client__python
kubernetes/base/dynamic/test_client.py
{ "start": 905, "end": 18916 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.config = base.get_e2e_configuration() def test_cluster_custom_resources(self): client = DynamicClient(api_client.ApiClient(configuration=self.config)) with self.assertRaises(ResourceNotFoundError): ch...
TestDynamicClient
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol24.py
{ "start": 209, "end": 286 }
class ____(Protocol): def meth(_self, self: Any, x: int) -> int: ...
ProtoB
python
huggingface__transformers
src/transformers/models/persimmon/modeling_persimmon.py
{ "start": 33543, "end": 33651 }
class ____(GenericForSequenceClassification, PersimmonPreTrainedModel): ...
PersimmonForSequenceClassification
python
spack__spack
lib/spack/spack/vendor/six.py
{ "start": 6897, "end": 12005 }
class ____(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itert...
_MovedItems
python
h5py__h5py
h5py/_hl/datatype.py
{ "start": 434, "end": 1548 }
class ____(HLObject): """ Represents an HDF5 named datatype stored in a file. To store a datatype, simply assign it to a name in a group: >>> MyGroup["name"] = numpy.dtype("f") >>> named_type = MyGroup["name"] >>> assert named_type.dtype == numpy.dtype("f") """ @p...
Datatype
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/variables/dense_update_ops_test.py
{ "start": 984, "end": 3452 }
class ____(test.TestCase): def _initAssignFetch(self, x, y, use_gpu): """Initialize a param to init and update it with y.""" super(AssignOpTest, self).setUp() with test_util.device(use_gpu=use_gpu): p = variables.Variable(x) assign = state_ops.assign(p, y) self.evaluate(p.initializer) ...
AssignOpTest
python
getsentry__sentry
src/sentry/integrations/on_call/spec.py
{ "start": 609, "end": 824 }
class ____(OnCallSpec): @property def provider_slug(self): return IntegrationProviderSlug.PAGERDUTY @property def action_service(self): return ActionService.PAGERDUTY
PagerDutyOnCallSpec
python
scipy__scipy
scipy/interpolate/_cubic.py
{ "start": 2570, "end": 5947 }
class ____(PPoly): """Piecewise cubic interpolator to fit values and first derivatives (C1 smooth). The result is represented as a `PPoly` instance. Parameters ---------- x : array_like, shape (n,) 1-D array containing values of the independent variable. Values must be real, finite...
CubicHermiteSpline
python
pyca__cryptography
tests/hazmat/primitives/test_serialization.py
{ "start": 61664, "end": 64794 }
class ____: def test_load_der_private_key(self, backend): data = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8-enc.der"), lambda derfile: derfile.read(), mode="rb", ) unencrypted = load_vectors_from_file( os.path.join...
TestEd448Serialization
python
django-guardian__django-guardian
guardian/testapp/tests/test_mixins.py
{ "start": 1080, "end": 1229 }
class ____(PermissionRequiredMixin, RemoveDatabaseView): permission_required = "testapp.add_post" accept_global_perms = True
GlobalNoObjectView
python
jpadilla__pyjwt
jwt/exceptions.py
{ "start": 1747, "end": 1788 }
class ____(PyJWTError): pass
PyJWKError
python
pytorch__pytorch
test/inductor/test_loop_ordering.py
{ "start": 1457, "end": 1692 }
class ____: available_buffer_names = () @staticmethod def get_backend(cls, *args): return TritonScheduling(cls) def can_buffer_be_removed_through_fusion(self, *args, **kwargs): return False
MockScheduler
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/openai_functions/qa_with_structure.py
{ "start": 752, "end": 4899 }
class ____(BaseModel): """An answer to the question, with sources.""" answer: str = Field(..., description="Answer to the question that was asked") sources: list[str] = Field( ..., description="List of sources used to answer the question", ) @deprecated( since="0.2.13", remova...
AnswerWithSources
python
huggingface__transformers
src/transformers/models/hubert/modular_hubert.py
{ "start": 7750, "end": 11526 }
class ____(Wav2Vec2Model, HubertPreTrainedModel): def __init__(self, config: HubertConfig): super().__init__(config) self.config = config self.feature_extractor = HubertFeatureEncoder(config) self.feature_projection = HubertFeatureProjection(config) if config.mask_time_prob ...
HubertModel
python
huggingface__transformers
tests/models/seggpt/test_modeling_seggpt.py
{ "start": 13788, "end": 18752 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return SegGptImageProcessor.from_pretrained("BAAI/seggpt-vit-large") if is_vision_available() else None @slow def test_one_shot_inference(self): model = SegGptForImageSegmentation.from_pretrained("BAAI/se...
SegGptModelIntegrationTest
python
lepture__authlib
authlib/jose/rfc7516/models.py
{ "start": 1552, "end": 2763 }
class ____: name = None description = None algorithm_type = "JWE" algorithm_location = "enc" IV_SIZE = None CEK_SIZE = None def generate_cek(self): return os.urandom(self.CEK_SIZE // 8) def generate_iv(self): return os.urandom(self.IV_SIZE // 8) def check_iv(self,...
JWEEncAlgorithm
python
scrapy__scrapy
tests/test_downloadermiddleware.py
{ "start": 5086, "end": 6134 }
class ____(TestManagerBase): """Tests middleware returning a response from process_exception.""" @deferred_f_from_coro_f async def test_process_response_called(self): req = Request("http://example.com/index.html") resp = Response("http://example.com/index.html") calls = [] ...
TestResponseFromProcessException
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 43453, "end": 43664 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("ONE_DAY", "ONE_MONTH", "ONE_WEEK", "PERMANENT", "THREE_DAYS")
UserBlockDuration
python
OmkarPathak__pygorithm
tests/test_sorting.py
{ "start": 3961, "end": 4140 }
class ____(unittest.TestCase, TestSortingAlgorithm): inplace = True alph_support = True @staticmethod def sort(arr): return heap_sort.sort(arr)
TestHeapSort
python
skorch-dev__skorch
skorch/tests/test_probabilistic.py
{ "start": 3071, "end": 4024 }
class ____(gpytorch.models.ApproximateGP): """GP classification for variational inference""" def __init__(self, inducing_points, eps=1e-6): variational_distribution = gpytorch.variational.CholeskyVariationalDistribution( inducing_points.size(0)) variational_strategy = gpytorch.variat...
VariationalBinaryClassificationModule
python
huggingface__transformers
tests/models/textnet/test_modeling_textnet.py
{ "start": 10654, "end": 11854 }
class ____(unittest.TestCase): @slow def test_inference_no_head(self): processor = TextNetImageProcessor.from_pretrained("czczup/textnet-base") model = TextNetModel.from_pretrained("czczup/textnet-base").to(torch_device) # prepare image url = "http://images.cocodataset.org/val20...
TextNetModelIntegrationTest
python
getsentry__sentry
src/sentry/backup/sanitize.py
{ "start": 1203, "end": 1348 }
class ____(SanitizationError): """ Thrown when the supplied JSON is not recognizable as a serialized Django model. """
InvalidJSONError
python
ray-project__ray
python/ray/tune/integration/ray_train.py
{ "start": 443, "end": 1513 }
class ____(UserCallback): """Propagate metrics and checkpoint paths from Ray Train workers to Ray Tune.""" def __init__(self): if not _in_tune_session(): raise RuntimeError("TuneReportCallback must be used in a Tune session.") self._training_actor_item_queue = ( get_sess...
TuneReportCallback
python
pypa__hatch
tests/cli/test/test_test.py
{ "start": 14805, "end": 17663 }
class ____: def test_flag(self, hatch, temp_dir, config_file, env_run, mocker): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.e...
TestParallel
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 2175, "end": 2784 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__(event_id=6, name="MEMBER_JOIN_TEAM", api_name="member.join-team") def render(self, audit_log_entry: AuditLogEntry) -> str: if audit_log_entry.target_user == audit_log_entry.actor: return "joined team {team_slug}...
MemberJoinTeamAuditLogEvent
python
Textualize__textual
src/textual/_parser.py
{ "start": 756, "end": 3307 }
class ____(Generic[T]): """Base class for a simple parser.""" read1 = Read1 peek1 = Peek1 def __init__(self) -> None: self._eof = False self._tokens: Deque[T] = deque() self._gen = self.parse(self._tokens.append) self._awaiting: Read1 | Peek1 = next(self._gen) s...
Parser
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_message_param.py
{ "start": 312, "end": 477 }
class ____(TypedDict, total=False): content: Required[Union[str, Iterable[BetaContentBlockParam]]] role: Required[Literal["user", "assistant"]]
BetaMessageParam
python
python-pillow__Pillow
src/PIL/ImageFont.py
{ "start": 26820, "end": 63101 }
class ____: """Wrapper for writing rotated or mirrored text""" def __init__( self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None ): """ Wrapper that creates a transposed font from any existing font object. :param font: A font object. ...
TransposedFont
python
pandas-dev__pandas
pandas/io/formats/info.py
{ "start": 27341, "end": 29668 }
class ____(_DataFrameTableBuilder, _TableBuilderVerboseMixin): """ Dataframe info table builder for verbose output. """ def __init__( self, *, info: DataFrameInfo, with_counts: bool, ) -> None: self.info = info self.with_counts = with_counts s...
_DataFrameTableBuilderVerbose
python
plotly__plotly.py
plotly/graph_objs/heatmap/_legendgrouptitle.py
{ "start": 233, "end": 2939 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "heatmap" _path_str = "heatmap.legendgrouptitle" _valid_props = {"font", "text"} @property def font(self): """ Sets this legend group's title font. The 'font' property is an instance of Font that may be specifi...
Legendgrouptitle
python
eventlet__eventlet
eventlet/green/http/client.py
{ "start": 31052, "end": 57274 }
class ____: _http_vsn = 11 _http_vsn_str = 'HTTP/1.1' response_class = HTTPResponse default_port = HTTP_PORT auto_open = 1 debuglevel = 0 @staticmethod def _is_textIO(stream): """Test whether a file-like object is a text or a binary stream. """ return isinstanc...
HTTPConnection
python
sympy__sympy
sympy/combinatorics/galois.py
{ "start": 1921, "end": 2529 }
class ____(Enum): """ Names for the transitive subgroups of S4. """ C4 = "C4" V = "V" D4 = "D4" A4 = "A4" S4 = "S4" def get_perm_group(self): if self == S4TransitiveSubgroups.C4: return CyclicGroup(4) elif self == S4TransitiveSubgroups.V: retu...
S4TransitiveSubgroups
python
huggingface__transformers
src/transformers/models/ministral/modeling_ministral.py
{ "start": 15192, "end": 18804 }
class ____(MinistralPreTrainedModel): def __init__(self, config: MinistralConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) se...
MinistralModel
python
dask__dask
dask/dataframe/dask_expr/_backends.py
{ "start": 544, "end": 860 }
class ____(ToBackend): @staticmethod def operation(df, options): return to_pandas_dispatch(df, **options) def _simplify_down(self): if isinstance(self.frame._meta, (pd.DataFrame, pd.Series, pd.Index)): # We already have pandas data return self.frame
ToPandasBackend
python
scipy__scipy
scipy/fftpack/tests/test_basic.py
{ "start": 7612, "end": 8930 }
class ____: def setup_method(self): np.random.seed(1234) def test_definition(self): for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]: x = np.array(t, dtype=self.rdt) y = rfft(x) y1 = direct_rdft(x) assert_array_almost_equal(y,y1) ...
_TestRFFTBase
python
sympy__sympy
sympy/physics/quantum/tests/test_state.py
{ "start": 1086, "end": 1198 }
class ____(TimeDepKet): @classmethod def default_args(self): return ("test", "t")
CustomTimeDepKet
python
ansible__ansible
lib/ansible/module_utils/_internal/_datatag/__init__.py
{ "start": 13249, "end": 13816 }
class ____(AnsibleSerializableWrapper[datetime.datetime]): __slots__ = _NO_INSTANCE_STORAGE @classmethod def _from_dict(cls: t.Type[_TAnsibleSerializable], d: t.Dict[str, t.Any]) -> datetime.datetime: value = datetime.datetime.fromisoformat(d['iso8601']) value.replace(fold=d['fold']) ...
AnsibleSerializableDateTime
python
allegroai__clearml
clearml/utilities/dicts.py
{ "start": 1714, "end": 3421 }
class ____(BlobsDict): """A dictionary that applies an arbitrary key-altering function before accessing the keys.""" def __init__(self, *args: Any, **kwargs: Any) -> None: super(NestedBlobsDict, self).__init__(*args, **kwargs) def __getitem__(self, keys_str: str = "") -> Any: if keys_s...
NestedBlobsDict
python
mlflow__mlflow
mlflow/utils/search_utils.py
{ "start": 55901, "end": 65983 }
class ____(SearchUtils): NUMERIC_ATTRIBUTES = {"version_number", "creation_timestamp", "last_updated_timestamp"} VALID_SEARCH_ATTRIBUTE_KEYS = { "name", "version_number", "run_id", "source_path", } VALID_ORDER_BY_ATTRIBUTE_KEYS = { "name", "version_number"...
SearchModelVersionUtils
python
huggingface__transformers
tests/models/mllama/test_modeling_mllama.py
{ "start": 1568, "end": 3916 }
class ____: def __init__( self, parent, ignore_index=-100, seq_length=7, is_training=True, text_config={ "model_type": "mllama", "vocab_size": 99, "hidden_size": 32, "num_hidden_layers": 2, "num_attention_hea...
MllamaText2TextModelTester
python
sympy__sympy
sympy/codegen/scipy_nodes.py
{ "start": 357, "end": 1396 }
class ____(Function): """ Minus one plus cosine of x, i.e. cos(x) - 1. For use when x is close to zero. Helper class for use with e.g. scipy.special.cosm1 See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.cosm1.html """ nargs = 1 def fdiff(self, argindex=1): """ ...
cosm1
python
pytorch__pytorch
torch/distributed/fsdp/_exec_order_utils.py
{ "start": 403, "end": 668 }
class ____(Enum): """Used internally for execution order validation.""" NONE = auto() # no deviation yet WARNING = auto() # deviated this iteration; currently issuing warnings WARNED = auto() # deviated in a previous iteration
_ExecOrderWarnStatus
python
pallets__werkzeug
src/werkzeug/datastructures/etag.py
{ "start": 69, "end": 3278 }
class ____(cabc.Collection[str]): """A set that can be used to check if one etag is present in a collection of etags. """ def __init__( self, strong_etags: cabc.Iterable[str] | None = None, weak_etags: cabc.Iterable[str] | None = None, star_tag: bool = False, ): ...
ETags