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
getsentry__sentry
src/sentry_plugins/pagerduty/client.py
{ "start": 233, "end": 1287 }
class ____(ApiClient): client = "sentry" plugin_name = "pagerduty" allow_redirects = False def __init__(self, service_key=None): self.service_key = service_key super().__init__() def build_url(self, path): return INTEGRATION_API_URL def request(self, data): pay...
PagerDutyPluginClient
python
scikit-learn__scikit-learn
sklearn/linear_model/_least_angle.py
{ "start": 71523, "end": 83135 }
class ____(LassoLars): """Lasso model fit with Lars using BIC or AIC for model selection. The optimization objective for Lasso is:: (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 AIC is the Akaike information criterion [2]_ and BIC is the Bayes Information criterion [3]_. Such criteria ...
LassoLarsIC
python
ray-project__ray
python/ray/serve/batching.py
{ "start": 19759, "end": 20862 }
class ____(Protocol, Generic[SelfType, T, R]): async def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]: ... @overload # Sync function for `batch` called WITHOUT arguments def batch(_sync_func: Callable[[List[T]], List[R]], /) -> Callable[[T], R]: ... @overload # Async function fo...
_AsyncBatchingMethod
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image07.py
{ "start": 315, "end": 958 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image07.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(...
TestCompareXLSXFiles
python
pyca__cryptography
src/cryptography/hazmat/primitives/asymmetric/ec.py
{ "start": 608, "end": 1622 }
class ____: SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1") SECP224R1 = ObjectIdentifier("1.3.132.0.33") SECP256K1 = ObjectIdentifier("1.3.132.0.10") SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7") SECP384R1 = ObjectIdentifier("1.3.132.0.34") SECP521R1 = ObjectIdentifier("1.3.132.0.35") ...
EllipticCurveOID
python
doocs__leetcode
solution/1100-1199/1106.Parsing A Boolean Expression/Solution.py
{ "start": 0, "end": 697 }
class ____: def parseBoolExpr(self, expression: str) -> bool: stk = [] for c in expression: if c in 'tf!&|': stk.append(c) elif c == ')': t = f = 0 while stk[-1] in 'tf': t += stk[-1] == 't' ...
Solution
python
pypa__warehouse
warehouse/manage/forms.py
{ "start": 15351, "end": 17376 }
class ____(wtforms.Form): __params__ = ["add_existing_project", "existing_project_name", "new_project_name"] add_existing_project = wtforms.RadioField( "Add existing or new project?", choices=[("true", "Existing project"), ("false", "New project")], coerce=lambda string: True if string ...
AddOrganizationProjectForm
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/root/package.py
{ "start": 216, "end": 411 }
class ____(Package): homepage = "http://www.example.com" url = "http://www.example.com/root-1.0.tar.gz" version("1.0", md5="abcdef0123456789abcdef0123456789") depends_on("gmt")
Root
python
python-pillow__Pillow
src/PIL/PaletteFile.py
{ "start": 364, "end": 1216 }
class ____: """File handler for Teragon-style palette files.""" rawmode = "RGB" def __init__(self, fp: IO[bytes]) -> None: palette = [o8(i) * 3 for i in range(256)] while True: s = fp.readline() if not s: break if s.startswith(b"#"): ...
PaletteFile
python
coleifer__peewee
tests/postgres.py
{ "start": 28729, "end": 29894 }
class ____(ModelTestCase): database = db requires = [Register] def setUp(self): super(TestServerSide, self).setUp() with db.atomic(): for i in range(100): Register.create(value=i) def test_server_side_cursor(self): query = Register.select().order_by(...
TestServerSide
python
PyCQA__pylint
tests/functional/i/iterable_context.py
{ "start": 3920, "end": 4058 }
class ____: field: list[int] | None = None def method(self): return [f + 1 for f in self.field] if self.field else None
Model
python
astropy__astropy
astropy/time/tests/test_quantity_interaction.py
{ "start": 4044, "end": 11078 }
class ____: """Test interaction of TimeDelta with Quantities""" def test_valid_quantity_input(self): """Test that TimeDelta can take quantity input.""" q = 500.25 * u.day dt1 = TimeDelta(q, format="jd") assert dt1.value == q.value dt2 = TimeDelta(q, format="sec") ...
TestTimeDeltaQuantity
python
dateutil__dateutil
tests/_common.py
{ "start": 3690, "end": 4433 }
class ____(TZContextBase): """ Context manager that temporarily sets the `TZ` variable (for use on *nix-like systems). Because the effect is local to the shell anyway, this will apply *unless* a guard is set. If you do not want the TZ environment variable set, you may set the ``DATEUTIL_MAY_NOT...
TZEnvContext
python
google__jax
docs/sphinxext/source_include.py
{ "start": 2600, "end": 3521 }
class ____(SphinxDirective): has_content = False required_arguments = 2 optional_arguments = 1 option_spec = { "hl_lines": str, } def run(self): source_dir = Path(self.env.srcdir) filepath = source_dir / self.arguments[0] tag = self.arguments[1] lines_spec = self.arguments[2] if len(sel...
TaggedBlockDirective
python
scipy__scipy
scipy/linalg/tests/test_fblas.py
{ "start": 3412, "end": 3562 }
class ____(BaseAxpy): blas_func = fblas.zaxpy dtype = complex128 ################################################## # Test blas ?scal
TestZaxpy
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 115631, "end": 121648 }
class ____: async def test_rejects_cancelling_scheduled_flow_and_sets_to_cancelled( self, session, initialize_orchestration, ): """Scheduled flows should skip the cancelling state and be set immediately to cancelled because they don't have infra to shut down. """ ...
TestBypassCancellingFlowRunsWithNoInfra
python
joke2k__faker
tests/providers/test_address.py
{ "start": 41991, "end": 42751 }
class ____: """Test hr_HR address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in HrHrAddressProvider.cities def test_street_name(s...
TestHrHr
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 321177, "end": 321642 }
class ____(sgqlc.types.Input): """Autogenerated input type of UnpinIssue""" __schema__ = github_schema __field_names__ = ("issue_id", "client_mutation_id") issue_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="issueId") """The ID of the issue to be unpinned""" client_mutation_id...
UnpinIssueInput
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/variables/variables_test.py
{ "start": 29438, "end": 35434 }
class ____(test.TestCase): def testPartitionedVariable(self): with ops.Graph().as_default(): v0 = variables.Variable([0]) v1 = variables.Variable([1]) v0._set_save_slice_info( variables.Variable.SaveSliceInfo(v0.name, [2], [0], [1])) v1._set_save_slice_info( variables....
PartitionedVariableTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/instigation_logger.py
{ "start": 2285, "end": 3185 }
class ____(logging.Handler): """Persist logging records to an IO stream controlled by the ComputeLogManager.""" def __init__(self, write_stream: IO): self._write_stream = write_stream self._has_logged = False super().__init__() @property def has_logged(self): return sel...
CapturedLogHandler
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_service_pb2_grpc.py
{ "start": 2466, "end": 5031 }
class ____(object): """EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s). """ def SendEvents(self, request_iterator, context): """Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediate te...
EventListenerServicer
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 42417, "end": 42844 }
class ____(CoercionTest): # previously test_setitem_series_object in tests.indexing.test_coercion @pytest.fixture def obj(self): return Series(["a", "b", "c", "d"], dtype=object) @pytest.fixture def raises(self): return False @pytest.mark.parametrize( "val,exp_dtype,raises", ...
TestCoercionObject
python
mlflow__mlflow
mlflow/store/tracking/dbmodels/models.py
{ "start": 25472, "end": 26391 }
class ____(Base): __tablename__ = "trace_tags" key = Column(String(250)) """ Tag key: `String` (limit 250 characters). """ value = Column(String(8000), nullable=True) """ Value associated with tag: `String` (limit 250 characters). Could be *null*. """ request_id = Column( ...
SqlTraceTag
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 8888, "end": 9199 }
class ____: def test_License_plate(self, faker, num_samples): pattern: Pattern = re.compile(r"{patterns}".format(patterns="|".join(faker.license_plate_regex_formats()))) for _ in range(num_samples): plate = faker.license_plate() assert pattern.fullmatch(plate)
TestPlPl
python
tensorflow__tensorflow
tensorflow/python/platform/benchmark.py
{ "start": 5115, "end": 5485 }
class ____(type): """The Benchmark class registrar. Used by abstract Benchmark class.""" def __new__(mcs, clsname, base, attrs): newclass = type.__new__(mcs, clsname, base, attrs) if not newclass.is_abstract(): GLOBAL_BENCHMARK_REGISTRY.add(newclass) return newclass @tf_export("__internal__.te...
_BenchmarkRegistrar
python
networkx__networkx
networkx/algorithms/link_analysis/tests/test_pagerank.py
{ "start": 451, "end": 6233 }
class ____: @classmethod def setup_class(cls): G = nx.DiGraph() edges = [ (1, 2), (1, 3), # 2 is a dangling node (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), ...
TestPageRank
python
numpy__numpy
numpy/_core/tests/test_errstate.py
{ "start": 470, "end": 4628 }
class ____: @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm") @pytest.mark.skipif(arm_softfloat, reason='platform/cpu issue with FPU (gh-413,-15562)') def test_invalid(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) ...
TestErrstate
python
kamyu104__LeetCode-Solutions
Python/number-of-substrings-containing-all-three-characters.py
{ "start": 29, "end": 354 }
class ____(object): def numberOfSubstrings(self, s): """ :type s: str :rtype: int """ result, left = 0, [-1]*3 for right, c in enumerate(s): left[ord(c)-ord('a')] = right result += min(left)+1 return result # Time: O(n) # Space: O(1)...
Solution
python
keras-team__keras
keras/src/layers/reshaping/cropping2d.py
{ "start": 258, "end": 9044 }
class ____(Layer): """Cropping layer for 2D input (e.g. picture). It crops along spatial dimensions, i.e. height and width. Example: >>> input_shape = (2, 28, 28, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x) ...
Cropping2D
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 102015, "end": 104051 }
class ____(TestCase): @assume_test_silo_mode(SiloMode.CONTROL) def another_user(self, email_string, team=None, alt_email_string=None): user = self.create_user(email_string) if alt_email_string: UserEmail.objects.create(email=alt_email_string, user=user) assert UserEmail....
ActivityTestCase
python
tensorflow__tensorflow
tensorflow/python/keras/engine/training_utils_v1.py
{ "start": 68807, "end": 76022 }
class ____(object): """Encapsulates model inputs. Allows for transforming model inputs while keeping the same structure. """ def __init__(self, inputs): self._inputs = inputs self._is_dict = isinstance(self._inputs, dict) self._is_single_input = not isinstance(self._inputs, (list, tuple, dict)) ...
ModelInputs
python
facebook__pyre-check
client/tests/timer_test.py
{ "start": 411, "end": 1337 }
class ____(testslide.TestCase): def test_resolution(self) -> None: base_interval = 1000000000 ticker = regular_interval_ticker(base_interval) timer = Timer(get_current_time_in_nanosecond=lambda: next(ticker)) self.assertEqual(timer.stop_in_nanosecond(), base_interval) self.a...
TimerTest
python
pytorch__pytorch
test/optim/test_lrscheduler.py
{ "start": 1055, "end": 101450 }
class ____(TestCase): class SchedulerTestNet(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1) self.conv2 = torch.nn.Conv2d(1, 1, 1) def forward(self, x): return self.conv2(F.relu(self.conv1(x))) ...
TestLRScheduler
python
PyCQA__pylint
tests/functional/t/too/too_few_public_methods_37.py
{ "start": 934, "end": 992 }
class ____: x: float y: float @frozen
AttrsBarePoint
python
run-llama__llama_index
llama-index-core/llama_index/core/data_structs/data_structs.py
{ "start": 6440, "end": 6709 }
class ____(IndexDict): """A simple dictionary of documents, but loads a MultiModelVectorStore.""" @classmethod def get_type(cls) -> IndexStructType: """Get type.""" return IndexStructType.MULTIMODAL_VECTOR_STORE @dataclass
MultiModelIndexDict
python
fluentpython__example-code-2e
17-it-generator/sentence_iter.py
{ "start": 524, "end": 1520 }
class ____: def __init__(self, words): self.words = words # <3> self.index = 0 # <4> def __next__(self): try: word = self.words[self.index] # <5> except IndexError: raise StopIteration() # <6> self.index += 1 # <7> return word # <8>...
SentenceIterator
python
huggingface__transformers
tests/models/dpt/test_modeling_dpt_hybrid.py
{ "start": 11219, "end": 12191 }
class ____(unittest.TestCase): def test_inference_depth_estimation(self): image_processor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas") model = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(torch_device) image = prepare_img() inputs = image_proce...
DPTModelIntegrationTest
python
streamlit__streamlit
lib/streamlit/elements/widgets/radio.py
{ "start": 2054, "end": 2623 }
class ____(Generic[T]): options: Sequence[T] index: int | None def serialize(self, v: object) -> int | None: if v is None: return None return 0 if len(self.options) == 0 else index_(self.options, v) def deserialize(self, ui_value: int | None) -> T | None: idx = ui_...
RadioSerde
python
fastai__fastai
fastai/text/models/awdlstm.py
{ "start": 3148, "end": 4040 }
class ____(Module): "Apply dropout with probability `embed_p` to an embedding layer `emb`." def __init__(self, emb:nn.Embedding, # Wrapped embedding layer embed_p:float # Embdedding layer dropout probability ): self.emb,self.embed_p = emb,embed_p def forward(self, words, scale...
EmbeddingDropout
python
getsentry__sentry
src/sentry/apidocs/examples/explore_saved_query_examples.py
{ "start": 4052, "end": 4773 }
class ____: EXPLORE_SAVED_QUERY_GET_RESPONSE = [ OpenApiExample( "Explore Saved Query GET response", value=EXPLORE_SAVED_QUERY_OBJ, status_codes=["200"], response_only=True, ) ] EXPLORE_SAVED_QUERY_POST_RESPONSE = [ OpenApiExample( ...
ExploreExamples
python
great-expectations__great_expectations
great_expectations/_version.py
{ "start": 1097, "end": 1608 }
class ____: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep44...
VersioneerConfig
python
redis__redis-py
tests/test_cache.py
{ "start": 32417, "end": 43995 }
class ____: def test_get_eviction_policy(self): cache = DefaultCache(CacheConfig(max_size=5)) assert isinstance(cache.eviction_policy, LRUPolicy) def test_get_max_size(self): cache = DefaultCache(CacheConfig(max_size=5)) assert cache.config.get_max_size() == 5 def test_get_...
TestUnitDefaultCache
python
scipy__scipy
scipy/linalg/tests/test_decomp_update.py
{ "start": 66294, "end": 66357 }
class ____(BaseQRupdate): dtype = np.dtype('F')
TestQRupdate_F
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/query.py
{ "start": 5719, "end": 117496 }
class ____( _SelectFromElements, SupportsCloneAnnotations, HasPrefixes, HasSuffixes, HasHints, EventTarget, log.Identified, Generative, Executable, Generic[_T], ): """ORM-level SQL construction object. .. legacy:: The ORM :class:`.Query` object is a legacy construct ...
Query
python
kamyu104__LeetCode-Solutions
Python/find-distance-in-a-binary-tree.py
{ "start": 1595, "end": 2440 }
class ____(object): def findDistance(self, root, p, q): """ :type root: TreeNode :type p: int :type q: int :rtype: int """ def dfs(node, p, q, result): if not node: return -1 left = dfs(node.left, p, q, result) ...
Solution2
python
PyCQA__pyflakes
pyflakes/messages.py
{ "start": 2335, "end": 2542 }
class ____(Message): message = 'undefined name %r in __all__' def __init__(self, filename, loc, name): Message.__init__(self, filename, loc) self.message_args = (name,)
UndefinedExport
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
{ "start": 4066, "end": 7589 }
class ____(BaseModel): """Class to house the params that can optionally be set for Get XCom.""" map_index: int = -1 include_prior_dates: bool = False offset: int | None = None @router.get( "/{dag_id}/{run_id}/{task_id}/{key}", description="Get a single XCom Value", ) def get_xcom( dag_id:...
GetXcomFilterParams
python
mkdocs__mkdocs
mkdocs/tests/structure/page_tests.py
{ "start": 32595, "end": 58576 }
class ____(unittest.TestCase): def get_rendered_result( self, *, content: str, files: list[str], logs: str = '', **kwargs ) -> str: cfg = load_config(docs_dir=DOCS_DIR, **kwargs) fs = [File(f, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for f in files] pg = Page('Foo', fs...
RelativePathExtensionTests
python
pytransitions__transitions
tests/test_graphviz.py
{ "start": 13561, "end": 21934 }
class ____(TestDiagrams): machine_cls = HierarchicalGraphMachine \ # type: Type[Union[HierarchicalGraphMachine, LockedHierarchicalGraphMachine]] def setUp(self): super(TestDiagramsNested, self).setUp() self.states = ['A', 'B', {'name': 'C', 'children': [{'name': ...
TestDiagramsNested
python
tensorflow__tensorflow
tensorflow/python/framework/convert_to_constants.py
{ "start": 7532, "end": 12916 }
class ____(_Convertible): """A Convertible NodeDef.""" def __init__(self, node, function, enclosing_graph): super(_Node, self).__init__(enclosing_graph) self._node = node self._function = function def __str__(self): return self._node.name @staticmethod def new(node, function, enclosing_grap...
_Node
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/list.py
{ "start": 192, "end": 2352 }
class ____(WidgetParameterItem): """ WidgetParameterItem subclass providing comboBox that lets the user select from a list of options. """ def __init__(self, param, depth): self.targetValue = None WidgetParameterItem.__init__(self, param, depth) def makeWidget(self): w = Qt...
ListParameterItem
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/lark.py
{ "start": 2202, "end": 9882 }
class ____(st.SearchStrategy): """Low-level strategy implementation wrapping a Lark grammar. See ``from_lark`` for details. """ def __init__( self, grammar: Lark, start: str | None, explicit: dict[str, st.SearchStrategy[str]], alphabet: st.SearchStrategy[str], ...
LarkStrategy
python
dask__dask
dask/tokenize.py
{ "start": 556, "end": 15056 }
class ____(RuntimeError): pass def _tokenize(*args: object, **kwargs: object) -> str: token: object = _normalize_seq_func(args) if kwargs: token = token, _normalize_seq_func(sorted(kwargs.items())) # Pass `usedforsecurity=False` to support FIPS builds of Python return hashlib.md5(str(toke...
TokenizationError
python
Pylons__pyramid
src/pyramid/util.py
{ "start": 403, "end": 1708 }
class ____(_DottedNameResolver): def __init__( self, package=None ): # default to package = None for bw compat _DottedNameResolver.__init__(self, package) def text_(s, encoding='latin-1', errors='strict'): """If ``s`` is an instance of ``bytes``, return ``s.decode(encoding, errors)``,...
DottedNameResolver
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 96838, "end": 97460 }
class ____( MMPlusMMTemplateConfigMixin, MTIAConfigHeuristic ): """MM Plus MM template heuristic for MTIA""" def __init__(self) -> None: super().__init__() # Override mm_configs to use mm_plus_mm_configs self.mm_configs = self.mm_plus_mm_configs # NOTE: overriding exhaustive...
MTIAMMPlusMMTemplateConfigHeuristic
python
eth-brownie__brownie
brownie/typing.py
{ "start": 3614, "end": 3869 }
class ____(TypedDict): evm_version: EvmVersion | None solc: NotRequired[SolcConfig] vyper: VyperConfig version: NotRequired[str] optimizer: NotRequired[OptimizerSettings] OutputSelection = Dict[str, Dict[str, List[str]]]
CompilerConfig
python
ansible__ansible
test/units/parsing/vault/test_vault.py
{ "start": 20705, "end": 23692 }
class ____(unittest.TestCase): def setUp(self): self.vault_cipher = vault.VaultAES256() def test(self): self.assertIsInstance(self.vault_cipher, vault.VaultAES256) # TODO: tag these as slow tests def test_create_key_cryptography(self): b_password = b'hunter42' b_salt = ...
TestVaultCipherAes256
python
python__mypy
mypyc/test-data/fixtures/ir.py
{ "start": 7346, "end": 7784 }
class ____: @overload def __init__(self) -> None: pass @overload def __init__(self, x: object) -> None: pass @overload def __init__(self, string: str, encoding: str, err: str = ...) -> None: pass def __add__(self, s: bytes) -> bytearray: ... def __setitem__(self, i: int, o: int) -> None:...
bytearray
python
apache__airflow
airflow-core/tests/unit/dag_processing/bundles/test_dag_bundle_manager.py
{ "start": 7233, "end": 14443 }
class ____(BaseDagBundle): """Test bundle that provides a URL template.""" def __init__(self, *, subdir: str | None = None, **kwargs): super().__init__(**kwargs) self.subdir = subdir def refresh(self): pass def get_current_version(self): return "v1.0" @property ...
BundleWithTemplate
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 6567, "end": 6792 }
class ____(models.Model): fk = models.ForeignKey( PlainParentModelWithManager, on_delete=models.CASCADE, related_name="childmodel_set", ) objects = PlainMyManager()
PlainChildModelWithManager
python
PrefectHQ__prefect
tests/_internal/pydantic/test_validated_func.py
{ "start": 16788, "end": 17170 }
class ____(BaseModel): b: str = Field() """, namespace, ) # Update the function's globals to include B namespace["process_model"].__globals__.update(namespace) # Now test that validation actually works at runtime result = vf.validate_call_args((), {"model": {"a"...
B
python
google__jax
jax/_src/profiler.py
{ "start": 15315, "end": 17446 }
class ____: def __init__(self, retries: int, percentile: int): self.retries: int = retries self.percentile: int = percentile self.collected_fdo: str | None = None self.called_times: int = 0 self.fdo_profiles: list[Any] = [] self.current_session: _profiler.ProfilerSession | None = None def ...
PGLEProfiler
python
pytorch__pytorch
test/test_nn.py
{ "start": 645068, "end": 645254 }
class ____(TestCase): # issue gh-38137 def test_pickle_softsign(self): # Make sure it does not throw an exception s = pickle.dumps(F.softsign)
TestFunctionalPickle
python
mlflow__mlflow
mlflow/metrics/genai/prompt_template.py
{ "start": 39, "end": 2441 }
class ____: """A prompt template for a language model. A prompt template consists of an array of strings that will be concatenated together. It accepts a set of parameters from the user that can be used to generate a prompt for a language model. The template can be formatted using f-strings. Exam...
PromptTemplate
python
python__mypy
mypyc/analysis/dataflow.py
{ "start": 12888, "end": 13847 }
class ____(BaseAnalysisVisitor[Value]): def visit_branch(self, op: Branch) -> GenAndKill[Value]: return set(), set() def visit_return(self, op: Return) -> GenAndKill[Value]: return set(), set() def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]: return set(), set() ...
UndefinedVisitor
python
sympy__sympy
sympy/strategies/tests/test_traverse.py
{ "start": 1387, "end": 2082 }
class ____(Basic): pass def rl(x): if x.args and not isinstance(x.args[0], Integer): return Basic2(*x.args) return x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(S(1.0), S(2.0), Basic(S(3), S(4)))) == \ Basic2(S(1.0), S(2.0), Basic(S(3), S(4))) def ...
Basic2
python
huggingface__transformers
src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
{ "start": 3759, "end": 4452 }
class ____(Wav2Vec2FeedForward): def __init__(self, config, act_fn=None, hidden_size=None): nn.Module.__init__(self) act_fn = act_fn if act_fn is not None else config.hidden_act hidden_size = hidden_size if hidden_size is not None else config.hidden_size self.intermediate_dropout = n...
Wav2Vec2BertFeedForward
python
tensorflow__tensorflow
tensorflow/python/ops/weak_tensor_math_ops_test.py
{ "start": 19909, "end": 20849 }
class ____(test_util.TensorFlowTestCase): def testAcceptsRefs(self): if context.executing_eagerly(): var = resource_variable_ops.ResourceVariable(10, name="var") else: var = variables.Variable(10) result = math_ops.scalar_mul(3, var) init = variables.global_variables_initializer() wit...
ScalarMulTest
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/trt_convert.py
{ "start": 3712, "end": 4977 }
class ____(object): FP32 = "FP32" FP16 = "FP16" INT8 = "INT8" @staticmethod def supported_precision_modes(): precisions = [ TrtPrecisionMode.FP32, TrtPrecisionMode.FP16, TrtPrecisionMode.INT8 ] return precisions + [p.lower() for p in precisions] # Use a large enough number as the defaul...
TrtPrecisionMode
python
huggingface__transformers
src/transformers/models/zamba2/modular_zamba2.py
{ "start": 53015, "end": 53223 }
class ____(ZambaForSequenceClassification): pass __all__ = [ "Zamba2ForCausalLM", "Zamba2ForSequenceClassification", "Zamba2Model", "Zamba2PreTrainedModel", ]
Zamba2ForSequenceClassification
python
tensorflow__tensorflow
tensorflow/python/keras/initializers/initializers_v2.py
{ "start": 25222, "end": 26671 }
class ____(VarianceScaling): """Lecun normal initializer. Also available via the shortcut function `tf.keras.initializers.lecun_normal`. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initializ...
LecunNormal
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 118713, "end": 119112 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(OrganizationOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc...
OrganizationOrder
python
pytorch__pytorch
torch/fx/experimental/partitioner_utils.py
{ "start": 2164, "end": 2255 }
class ____(NamedTuple): name: str available_mem_bytes: int logical_id: int
Device
python
getsentry__sentry
tests/sentry/relocation/test_utils.py
{ "start": 1169, "end": 12045 }
class ____(RelocationUtilsTestCase): def test_bad_relocation_not_found(self, fake_message_builder: Mock) -> None: self.mock_message_builder(fake_message_builder) uuid = str(uuid4()) (rel, attempts_left) = start_relocation_task(uuid, OrderedTask.UPLOADING_COMPLETE, 3) assert fake_me...
RelocationStartTestCase
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/_collections_cy.py
{ "start": 2515, "end": 9219 }
class ____(Set[_T]): """A set implementation that maintains insertion order.""" __slots__ = ("_list",) _list: List[_T] @classmethod def __class_getitem__(cls, key: Any) -> type[Self]: return cls def __init__(self, d: Optional[Iterable[_T]] = None) -> None: if d is not None: ...
OrderedSet
python
ansible__ansible
test/lib/ansible_test/_internal/metadata.py
{ "start": 414, "end": 4310 }
class ____: """Metadata object for passing data to delegated tests.""" def __init__(self, debugger_flags: DebuggerFlags) -> None: """Initialize metadata.""" self.changes: dict[str, tuple[tuple[int, int], ...]] = {} self.cloud_config: t.Optional[dict[str, dict[str, t.Union[int, str, bool...
Metadata
python
numba__numba
numba/tests/npyufunc/test_parallel_low_work.py
{ "start": 255, "end": 1056 }
class ____(unittest.TestCase): _numba_parallel_test_ = False def test_low_workcount(self): # build parallel native code ufunc pv = Vectorize(vector_add, target='parallel') for ty in (int32, uint32, float32, float64): pv.add(ty(ty, ty)) para_ufunc = pv.build_ufunc() ...
TestParallelLowWorkCount
python
run-llama__llama_index
llama-index-integrations/callbacks/llama-index-callbacks-wandb/llama_index/callbacks/wandb/base.py
{ "start": 1446, "end": 2246 }
class ____(TypedDict): job_type: Optional[str] dir: Optional[str] config: Union[Dict, str, None] project: Optional[str] entity: Optional[str] reinit: Optional[bool] tags: Optional[Sequence] group: Optional[str] name: Optional[str] notes: Optional[str] magic: Optional[Union[di...
WandbRunArgs
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_engine.py
{ "start": 28916, "end": 30245 }
class ____(fixtures.TestBase): def test_ignore_no_transaction_on_rollback(self): """test #8231""" class ProgrammingError(Exception): pass dialect = base.dialect(ignore_no_transaction_on_rollback=True) dialect.dbapi = mock.Mock(ProgrammingError=ProgrammingError) ...
IgnoreNotransOnRollbackTest
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/groupsearchview.py
{ "start": 1928, "end": 2103 }
class ____(ViewValidator): starred = serializers.BooleanField(required=False) def validate(self, data): return super().validate(data)
GroupSearchViewPostValidator
python
getsentry__sentry
src/sentry/utils/github.py
{ "start": 429, "end": 1129 }
class ____: def __init__(self, *, client_id: str, client_secret: str) -> None: self._client_id = client_id self._client_secret = client_secret def get(self, url: str) -> dict[str, Any]: with build_session() as session: try: resp = session.get( ...
_GitHubClient
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 522397, "end": 531938 }
class ____(NumBinopNode): # '/' or '//' operator. cdivision = None truedivision = None # == "unknown" if operator == '/' ctruedivision = False cdivision_warnings = False zerodivision_check = None def find_compile_time_binary_operator(self, op1, op2): func = compile_time_binary_o...
DivNode
python
justquick__django-activity-stream
runtests/testapp/tests/test_django.py
{ "start": 441, "end": 2718 }
class ____(ActivityBaseTestCase): def setUp(self): super().setUp() self.user = self.User.objects.create(username='test') action.send(self.user, verb='was created') def test_accessor(self): self.assertEqual(len(Action.objects.testfoo(self.user)), 1) self.assertEqual( ...
TestAppTests
python
aimacode__aima-python
deep_learning4e.py
{ "start": 3130, "end": 3504 }
class ____(Layer): """1D softmax output layer in 19.3.2.""" def __init__(self, size=3): super().__init__(size) def forward(self, inputs, activation=SoftMax): assert len(self.nodes) == len(inputs) res = activation().function(inputs) for node, val in zip(self.nodes, res): ...
OutputLayer
python
apache__airflow
task-sdk/src/airflow/sdk/exceptions.py
{ "start": 7007, "end": 7121 }
class ____(AirflowException): """Raised when a task failed during deferral for some reason."""
TaskDeferralError
python
facebook__pyre-check
client/commands/infer.py
{ "start": 1987, "end": 2142 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): qualifier: str path: str line: int @dataclasses.dataclass(frozen=True)
RawAnnotationLocation
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 165724, "end": 168637 }
class ____(Request): """ Delete task configuration items :param task: Task ID :type task: str :param configuration: List of configuration itemss to delete :type configuration: Sequence[str] :param force: If set to True then both new and running task configuration can be deleted. Oth...
DeleteConfigurationRequest
python
eventlet__eventlet
eventlet/queue.py
{ "start": 5302, "end": 15036 }
class ____: """ This is a variant of Queue that behaves mostly like the standard :class:`Stdlib_Queue`. It differs by not supporting the :meth:`task_done <Stdlib_Queue.task_done>` or :meth:`join <Stdlib_Queue.join>` methods, and is a little faster for not having that overhead. """ def ...
LightQueue
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 7042, "end": 7529 }
class ____(FileSystemEvent): """ File system event representing directory modification on the file system. """ event_type = EVENT_TYPE_MODIFIED is_directory = True def __init__(self, src_path): super(DirModifiedEvent, self).__init__(src_path) def __repr__(self): return ("<...
DirModifiedEvent
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 14183, "end": 20310 }
class ____: MultiVector = _VectorIndexMultiVector Quantizer = _VectorIndexQuantizer @staticmethod def none() -> _VectorIndexConfigSkipCreate: """Create a `_VectorIndexConfigSkipCreate` object to be used when configuring Weaviate to not index your vectors. Use this method when defining ...
_VectorIndex
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-gemini/llama_index/llms/gemini/base.py
{ "start": 2226, "end": 19556 }
class ____(FunctionCallingLLM): """ Gemini LLM. Examples: `pip install llama-index-llms-gemini` ```python from llama_index.llms.gemini import Gemini llm = Gemini(model="models/gemini-ultra", api_key="YOUR_API_KEY") resp = llm.complete("Write a poem about a magic ba...
Gemini
python
huggingface__transformers
src/transformers/models/aria/modular_aria.py
{ "start": 40899, "end": 47800 }
class ____(ProcessorMixin): """ AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer. Args: image_processor (`AriaImageProcessor`, *optional*): The AriaImageProcessor to use for image preprocessing. tokenizer (`PreT...
AriaProcessor
python
realpython__materials
python-doctest/user.py
{ "start": 910, "end": 1278 }
class ____: def __init__(self, name, favorite_colors): """Initialize instances of User. Usage examples: >>> User( ... "John", {"#797EF6", "#4ADEDE", "#1AA7EC"} ... ) # doctest: +ELLIPSIS <sets.User object at 0x...> """ self.name = name sel...
User_Three
python
tiangolo__fastapi
tests/test_jsonable_encoder.py
{ "start": 934, "end": 1093 }
class ____: def __iter__(self): raise NotImplementedError() @property def __dict__(self): raise NotImplementedError()
Unserializable
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 42780, "end": 43443 }
class ____(sgqlc.types.Enum): """The corresponding operation type for the action Enumeration Choices: * `ACCESS`: An existing resource was accessed * `AUTHENTICATION`: A resource performed an authentication event * `CREATE`: A new resource was created * `MODIFY`: An existing resource was modif...
OperationType
python
openai__openai-python
src/openai/types/evals/runs/output_item_list_response.py
{ "start": 1633, "end": 1842 }
class ____(BaseModel): content: Optional[str] = None """The content of the message.""" role: Optional[str] = None """The role of the message (e.g. "system", "assistant", "user")."""
SampleOutput
python
falconry__falcon
falcon/inspect.py
{ "start": 15318, "end": 16294 }
class ____(_Traversable): """Describes the middleware of the app. Args: middlewareTree (MiddlewareTreeInfo): The middleware tree of the app. middlewareClasses (list[MiddlewareClassInfo]): The middleware classes of the app. independent (bool): Whether or not the middleware co...
MiddlewareInfo
python
ipython__ipython
IPython/core/prefilter.py
{ "start": 19761, "end": 21347 }
class ____(Configurable): handler_name = Unicode("normal") esc_strings: List = List([]) shell = Instance( "IPython.core.interactiveshell.InteractiveShellABC", allow_none=True ) prefilter_manager = Instance( "IPython.core.prefilter.PrefilterManager", allow_none=True ) def __i...
PrefilterHandler
python
pytorch__pytorch
benchmarks/tensorexpr/reduction.py
{ "start": 2587, "end": 2849 }
class ____(ReduceBench): def __init__(self, mode, device, dtype, M, N, K, skip_input_transform): super().__init__(mode, device, dtype, "mid", M, N, K, skip_input_transform) @staticmethod def module(): return "reduce_mid"
ReduceMidBench
python
facebook__pyre-check
tools/generate_taint_models/tests/get_dynamic_graphql_sources_test.py
{ "start": 1063, "end": 1894 }
class ____: id: int resolver1: bool resolver2: bool resolver3: bool resolver4: bool lambda_resolver: bool queryType = GraphQLObjectType( name="queryType", description="GraphQLObject directly created at top level", fields={ "no_resolver": GraphQLField(GraphQLNonNull(GraphQLI...
DirectObject