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
apache__airflow
providers/apache/hive/tests/unit/apache/hive/transfers/test_hive_to_samba.py
{ "start": 1579, "end": 4346 }
class ____(TestHiveEnvironment): def setup_method(self, method): self.kwargs = dict( hql="hql", destination_filepath="destination_filepath", samba_conn_id="samba_default", hiveserver2_conn_id="hiveserver2_default", task_id="test_hive_to_samba_opera...
TestHive2SambaOperator
python
cython__cython
Cython/Compiler/Symtab.py
{ "start": 99863, "end": 101779 }
class ____(Scope): # Namespace of a C struct or union. def __init__(self, name="?"): Scope.__init__(self, name, outer_scope=None, parent_scope=None) def declare_var(self, name, type, pos, cname=None, visibility='private', api=False, in_pxd=False, is_cdef=Fa...
StructOrUnionScope
python
walkccc__LeetCode
solutions/1196. How Many Apples Can You Put into the Basket/1196.py
{ "start": 0, "end": 209 }
class ____: def maxNumberOfApples(self, weight: list[int]) -> int: summ = 0 for i, w in enumerate(sorted(weight)): summ += w if summ > 5000: return i return len(weight)
Solution
python
bokeh__bokeh
src/bokeh/models/text.py
{ "start": 2814, "end": 4073 }
class ____(MathText): """ Render mathematical content using `LaTeX <https://www.latex-project.org/>`_ notation. See :ref:`ug_styling_mathtext` in the |user guide| for more information. .. note:: Bokeh uses `MathJax <https://www.mathjax.org>`_ to render text containing mathematical nota...
TeX
python
getsentry__sentry
src/social_auth/backends/visualstudio.py
{ "start": 610, "end": 1066 }
class ____(OAuthBackend): """Visual Studio OAuth authentication backend""" name = "visualstudio" EXTRA_DATA = [("id", "id"), ("refresh_token", "refresh_token")] def get_user_details(self, response): """Return user details from Visual Studio account""" return { "email": resp...
VisualStudioBackend
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 855204, "end": 858337 }
class ____(sgqlc.types.Type, Node, Closable, Updatable): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "body", "body_html", "columns", "created_at", "creator", "database_id", "name", "number", ...
Project
python
getsentry__sentry
tests/sentry/seer/autofix/test_autofix.py
{ "start": 40838, "end": 44329 }
class ____(TestCase): @patch("sentry.seer.autofix.autofix._get_github_username_for_user") @patch("sentry.seer.autofix.autofix.requests.post") @patch("sentry.seer.autofix.autofix.sign_with_seer_secret") def test_call_autofix(self, mock_sign, mock_post, mock_get_username) -> None: """Tests the _ca...
TestCallAutofix
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 72996, "end": 77020 }
class ____(BaseTest): def test_from_triple(self): f = llvm.Target.from_triple with self.assertRaises(RuntimeError) as cm: f("foobar") self.assertIn("No available targets are compatible with", str(cm.exception)) triple = llvm.get_default_triple() ...
TestTarget
python
pennersr__django-allauth
allauth/socialaccount/providers/tumblr/views.py
{ "start": 186, "end": 373 }
class ____(OAuth): url = "https://api.tumblr.com/v2/user/info" def get_user_info(self): data = self.query(self.url).json() return data["response"]["user"]
TumblrAPI
python
matplotlib__matplotlib
lib/matplotlib/offsetbox.py
{ "start": 36920, "end": 38188 }
class ____(AnchoredOffsetbox): """ AnchoredOffsetbox with Text. """ def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs): """ Parameters ---------- s : str Text. loc : str Location code. See `AnchoredOffsetbox`. ...
AnchoredText
python
sqlalchemy__sqlalchemy
test/dialect/mysql/test_query.py
{ "start": 10477, "end": 11794 }
class ____(fixtures.TestBase): __only_on__ = "mysql >= 5.7", "mariadb" __backend__ = True @combinations( (True), (False), (None), ("unset"), argnames="nullable", ) def test_column_computed_for_nullable(self, connection, nullable): """test #10056 ...
ComputedTest
python
sphinx-doc__sphinx
sphinx/search/pt.py
{ "start": 199, "end": 617 }
class ____(SearchLanguage): lang = 'pt' language_name = 'Portuguese' js_stemmer_rawcode = 'portuguese-stemmer.js' stopwords = PORTUGUESE_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('portuguese') ...
SearchPortuguese
python
fastai__fastai
fastai/callback/azureml.py
{ "start": 317, "end": 2694 }
class ____(Callback): """ Log losses, metrics, model architecture summary to AzureML. If `log_offline` is False, will only log if actually running on AzureML. A custom AzureML `Run` class can be passed as `azurerun`. If `log_to_parent` is True, will also log to the parent run, if exists (e.g. in Az...
AzureMLCallback
python
readthedocs__readthedocs.org
readthedocs/projects/admin.py
{ "start": 12984, "end": 13313 }
class ____(admin.ModelAdmin): """Admin view for :py:class:`ImportedFile`.""" raw_id_fields = ("project", "version") list_display = ("path", "version", "build") list_select_related = ("project", "version", "version__project") search_fields = ("project__slug", "version__slug", "path", "build")
ImportedFileAdmin
python
walkccc__LeetCode
solutions/359. Logger Rate Limiter/359-2.py
{ "start": 0, "end": 276 }
class ____: def __init__(self): self.okTime = {} # {message: ok time} def shouldPrintMessage(self, timestamp: int, message: str) -> bool: if timestamp < self.okTime.get(message, 0): return False self.okTime[message] = timestamp + 10 return True
Logger
python
sympy__sympy
sympy/polys/rings.py
{ "start": 6540, "end": 24916 }
class ____(DefaultPrinting, IPolys[Er], Generic[Er]): """Multivariate distributed polynomial ring.""" symbols: tuple[Expr, ...] gens: tuple[PolyElement[Er], ...] ngens: int _gens_set: set[PolyElement] domain: Domain[Er] order: MonomialOrder _hash: int _hash_tuple: tuple _one: li...
PolyRing
python
huggingface__transformers
tests/quantization/bnb/test_4bit.py
{ "start": 29764, "end": 30306 }
class ____(BaseSerializationTest): """ tests more combinations of parameters """ def test_nf4_single_safe(self): self.test_serialization(quant_type="nf4", double_quant=False) # nf4 double safetensors quantization is tested in test_serialization() method from the parent class def test_...
ExtendedSerializationTest
python
huggingface__transformers
src/transformers/models/eomt/modeling_eomt.py
{ "start": 45545, "end": 54055 }
class ____(EomtPreTrainedModel): main_input_name = "pixel_values" def __init__(self, config: EomtConfig): super().__init__(config) self.config = config self.num_hidden_layers = config.num_hidden_layers self.embeddings = EomtEmbeddings(config) self.layernorm = nn.LayerNor...
EomtForUniversalSegmentation
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_check_health.py
{ "start": 9202, "end": 9334 }
class ____: num_warning_checks: int total_num_checks: int @whitelist_for_serdes @record.record
AssetHealthCheckWarningMetadata
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 124197, "end": 129764 }
class ____(OneFormerPreTrainedModel): main_input_name = ["pixel_values", "task_inputs"] def __init__(self, config: OneFormerConfig): super().__init__(config) self.pixel_level_module = OneFormerPixelLevelModule(config) self.transformer_module = OneFormerTransformerModule(in_features=conf...
OneFormerModel
python
langchain-ai__langchain
libs/core/langchain_core/structured_query.py
{ "start": 2295, "end": 2668 }
class ____(BaseModel): """Base class for all expressions.""" def accept(self, visitor: Visitor) -> Any: """Accept a visitor. Args: visitor: visitor to accept. Returns: result of visiting. """ return getattr(visitor, f"visit_{_to_snake_case(self....
Expr
python
cython__cython
Cython/Compiler/FlowControl.py
{ "start": 23006, "end": 50821 }
class ____(CythonTransform): def find_in_stack(self, env): if env == self.env: return self.flow for e, flow in reversed(self.stack): if e is env: return flow assert False def visit_ModuleNode(self, node): dot_output = self.current_directi...
ControlFlowAnalysis
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/legacy/valid_asset_subset.py
{ "start": 766, "end": 6519 }
class ____(SerializableEntitySubset[AssetKey]): """Legacy construct used for doing operations over EntitySubsets that are known to be valid. This functionality is subsumed by EntitySubset. """ def inverse(self, partitions_def: Optional[PartitionsDefinition]) -> "ValidAssetSubset": """Returns th...
ValidAssetSubset
python
huggingface__transformers
tests/models/stablelm/test_modeling_stablelm.py
{ "start": 1391, "end": 5960 }
class ____(unittest.TestCase): @slow def test_model_stablelm_3b_4e1t_logits(self): input_ids = {"input_ids": torch.tensor([[510, 8588, 310, 1900, 9386]], dtype=torch.long, device=torch_device)} model = StableLmForCausalLM.from_pretrained("stabilityai/stablelm-3b-4e1t").to(torch_device) ...
StableLmModelIntegrationTest
python
huggingface__transformers
src/transformers/models/flava/configuration_flava.py
{ "start": 14809, "end": 17720 }
class ____(PreTrainedConfig): model_type = "flava_image_codebook" base_config_key = "image_codebook_config" r""" [`FlavaImageCodebookConfig`] is the configuration class to store the configuration of a [`FlavaImageCodebook`]. It is used to instantiate an FLAVA model according to the specified argume...
FlavaImageCodebookConfig
python
fastai__fastai
fastai/text/core.py
{ "start": 4335, "end": 4602 }
class ____(): "Basic tokenizer that just splits on spaces" def __init__(self, split_char=' ', **kwargs): self.split_char=split_char def __call__(self, items): return (t.split(self.split_char) for t in items) # %% ../../nbs/30_text.core.ipynb 39
BaseTokenizer
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py
{ "start": 8178, "end": 17580 }
class ____(object): _kinds = ( (GraphQLScalarType, TypeKind.SCALAR), (GraphQLObjectType, TypeKind.OBJECT), (GraphQLInterfaceType, TypeKind.INTERFACE), (GraphQLUnionType, TypeKind.UNION), (GraphQLEnumType, TypeKind.ENUM), (GraphQLInputObjectType, TypeKind.INPUT_OBJECT)...
TypeFieldResolvers
python
ray-project__ray
python/ray/tune/tests/test_tune_restore.py
{ "start": 4060, "end": 16229 }
class ____(unittest.TestCase): class FailureInjectorCallback(Callback): """Adds random failure injection to the TrialExecutor.""" def __init__(self, num_trials=20, delay_s=0.3): self.num_trials = num_trials self.delay_s = delay_s self.fail_at = None def ...
TuneFailResumeGridTest
python
kamyu104__LeetCode-Solutions
Python/count-connected-components-in-lcm-graph.py
{ "start": 1522, "end": 2012 }
class ____(object): def countComponents(self, nums, threshold): """ :type nums: List[int] :type threshold: int :rtype: int """ uf = UnionFind(threshold) lookup = [-1]*threshold for x in nums: if x-1 >= threshold: continue ...
Solution2
python
getsentry__sentry
tests/sentry/utils/test_query.py
{ "start": 1134, "end": 6159 }
class ____(TestCase): range_wrapper = RangeQuerySetWrapper def test_basic(self) -> None: total = 10 for _ in range(total): self.create_user() qs = User.objects.all() assert len(list(self.range_wrapper(qs, step=2))) == total assert len(list(self.range_wrapp...
RangeQuerySetWrapperTest
python
streamlit__streamlit
lib/tests/streamlit/web/bootstrap_test.py
{ "start": 998, "end": 15803 }
class ____(IsolatedAsyncioTestCase): """Test bootstrap.py's printing functions. (We use `IsolatedAsyncioTestCase` to ensure that an asyncio event loop exists in tests that implicitly rely on one.) """ def setUp(self): self.orig_stdout = sys.stdout sys.stdout = StringIO() def t...
BootstrapPrintTest
python
conda__conda
conda/models/records.py
{ "start": 21446, "end": 23313 }
class ____(SolvedRecord): """Representation of a package that is installed in a local conda environmnet. Specialization of :class:`PackageRecord` that adds information for packages that are installed in a local conda environment or prefix. Note that this class does not add new fields to the :attr:`Pac...
PrefixRecord
python
dateutil__dateutil
setup.py
{ "start": 477, "end": 1375 }
class ____(TestCommand): def run(self): sys.stderr.write("Running 'test' with setup.py is not supported. " "Use 'pytest' or 'tox' to run the tests.\n") sys.exit(1) ### # Load metadata def README(): with io.open('README.rst', encoding='utf-8') as f: readme_line...
Unsupported
python
numba__numba
numba/core/base.py
{ "start": 877, "end": 5850 }
class ____(object): """ An object matching an actual signature against a registry of formal signatures and choosing the best candidate, if any. In the current implementation: - a "signature" is a tuple of type classes or type instances - the "best candidate" is the most specific match """ ...
OverloadSelector
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 29916, "end": 30506 }
class ____(ActionTool): ''' *toolbar icon*: |copy_icon| The copy tool is an action tool, that allows copying the rendered contents of a plot or a collection of plots to system's clipboard. This tools is browser dependent and may not function in certain browsers, or require additional permissions to...
CopyTool
python
spack__spack
lib/spack/spack/environment/environment.py
{ "start": 120039, "end": 120176 }
class ____(SpackEnvironmentError): """Class for errors in applying develop information to an environment."""
SpackEnvironmentDevelopError
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-huggingface-openvino/llama_index/embeddings/huggingface_openvino/base.py
{ "start": 697, "end": 9646 }
class ____(BaseEmbedding): model_id_or_path: str = Field(description="Huggingface model id or local path.") max_length: int = Field(description="Maximum length of input.") pooling: str = Field(description="Pooling strategy. One of ['cls', 'mean'].") normalize: bool = Field(default=True, description="Nor...
OpenVINOEmbedding
python
TheAlgorithms__Python
neural_network/input_data.py
{ "start": 1047, "end": 3784 }
class ____(typing.NamedTuple): train: "_DataSet" validation: "_DataSet" test: "_DataSet" # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = np.dtype(np.uint32).newbyteorder(">") return np.fro...
_Datasets
python
facebook__pyre-check
client/configuration/exceptions.py
{ "start": 480, "end": 610 }
class ____(InvalidConfiguration): def __init__(self, message: str) -> None: super().__init__(message)
InvalidPythonVersion
python
lepture__authlib
authlib/jose/errors.py
{ "start": 2781, "end": 2981 }
class ____(JoseError): error = "insecure_claim" def __init__(self, claim): description = f"Insecure claim '{claim}'" super().__init__(description=description)
InsecureClaimError
python
PyCQA__pylint
tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.py
{ "start": 6226, "end": 6558 }
class ____: def __init__(self, x, y): # [missing-param-doc, missing-type-doc] """test_constr_params_in_init_google Example of a class with missing constructor parameter documentation (Google style) Args: y: bla missing constructor parameter documentation ...
ClassFoo
python
Textualize__textual
src/textual/command.py
{ "start": 10183, "end": 12010 }
class ____(Provider): """A simple provider which the caller can pass commands to.""" def __init__( self, screen: Screen[Any], commands: list[CommandListItem], ) -> None: # Convert all commands to SimpleCommand instances super().__init__(screen, None) self._co...
SimpleProvider
python
pytorch__pytorch
torch/nn/modules/pooling.py
{ "start": 52019, "end": 53089 }
class ____(_AdaptiveMaxPoolNd): r"""Applies a 1D adaptive max pooling over an input signal composed of several input planes. The output size is :math:`L_{out}`, for any input size. The number of output features is equal to the number of input planes. Args: output_size: the target output size :...
AdaptiveMaxPool1d
python
walkccc__LeetCode
solutions/2912. Number of Ways to Reach Destination in the Grid/2912-2.py
{ "start": 0, "end": 1233 }
class ____: def numberOfWays( self, n: int, m: int, k: int, source: list[int], dest: list[int], ) -> int: MOD = 1_000_000_007 # the number of ways of `source` to `dest` using steps so far ans = int(source == dest) # the number of ways of `source` to dest's row usi...
Solution
python
getsentry__sentry
src/sentry/integrations/github_enterprise/handlers/github_enterprise_handler.py
{ "start": 415, "end": 586 }
class ____(TicketingActionHandler): group = ActionHandler.Group.TICKET_CREATION provider_slug = IntegrationProviderSlug.GITHUB_ENTERPRISE
GithubEnterpriseActionHandler
python
xlwings__xlwings
xlwings/main.py
{ "start": 112968, "end": 119799 }
class ____: """ The chart object is a member of the :meth:`charts <xlwings.main.Charts>` collection: >>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.charts[0] # or sht.charts['ChartName'] <Chart 'Chart 1' in <Sheet [Book1]Sheet1>> """ def __init__(self, name_or_...
Chart
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/shortcuts/prompt.py
{ "start": 7014, "end": 60747 }
class ____(Generic[_T]): """ PromptSession for a prompt application, which can be used as a GNU Readline replacement. This is a wrapper around a lot of ``prompt_toolkit`` functionality and can be a replacement for `raw_input`. All parameters that expect "formatted text" can take either just pl...
PromptSession
python
django__django
tests/model_enums/tests.py
{ "start": 7990, "end": 8126 }
class ____(frozenset, models.Choices): A = {1, 2} B = {2, 3} UNION = A | B DIFFERENCE = A - B INTERSECTION = A & B
Set
python
kamyu104__LeetCode-Solutions
Python/check-if-point-is-reachable.py
{ "start": 58, "end": 423 }
class ____(object): def isReachable(self, targetX, targetY): """ :type targetX: int :type targetY: int :rtype: bool """ def gcd(a, b): while b: a, b = b, a%b return a g = gcd(targetX, targetY) return g == (g...
Solution
python
joke2k__faker
tests/providers/test_barcode.py
{ "start": 10232, "end": 10472 }
class ____(_LocaleNorthAmericaMixin): """Tests fr_CA barcode provider""" num_samples = 1000 @staticmethod def get_provider_class(): from faker.providers.barcode.fr_CA import Provider return Provider
TestFrCa
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 14664, "end": 15072 }
class ____(TypedDict): id: str title: str dateCreated: str createdBy: UserSerializerResponse environment: list[str] filters: DashboardFilters lastVisited: str | None widgetDisplay: list[str] widgetPreview: list[dict[str, str]] permissions: DashboardPermissionsResponse | None ...
DashboardListResponse
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/padded_batch_test.py
{ "start": 1649, "end": 16253 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( count=[32, 34], padded_shapes=[[None], [25]], drop_remainder=[True, False]))) d...
PaddedBatchTest
python
walkccc__LeetCode
solutions/3285. Find Indices of Stable Mountains/3285.py
{ "start": 0, "end": 180 }
class ____: def stableMountains(self, height: list[int], threshold: int) -> list[int]: return [i for i in range(1, len(height)) if height[i - 1] > threshold]
Solution
python
sqlalchemy__sqlalchemy
test/sql/test_ddlemit.py
{ "start": 646, "end": 21899 }
class ____(fixtures.TestBase): def _mock_connection(self, item_exists): def has_item(connection, name, schema): return item_exists(name) def has_index(connection, tablename, idxname, schema): return item_exists(idxname) return Mock( dialect=Mock( ...
EmitDDLTest
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 7585, "end": 9661 }
class ____(ToolBase): """ Change to the current cursor while inaxes. This tool, keeps track of all `ToolToggleBase` derived tools, and updates the cursor when a tool gets triggered. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._id_drag = None ...
ToolSetCursor
python
doocs__leetcode
solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.py
{ "start": 0, "end": 135 }
class ____: def differenceOfSums(self, n: int, m: int) -> int: return sum(i if i % m else -i for i in range(1, n + 1))
Solution
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 24783, "end": 25366 }
class ____(Expr): """Get an attribute or item from an expression and prefer the item.""" fields = ("node", "arg", "ctx") node: Expr arg: Expr ctx: str def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any: if self.ctx != "load": raise Impossible() eval_c...
Getitem
python
pypa__setuptools
setuptools/_distutils/text_file.py
{ "start": 209, "end": 12101 }
class ____: """Provides a file-like object that takes care of all the things you commonly want to do when processing a text file that has some line-by-line syntax: strip comments (as long as "#" is your comment character), skip blank lines, join adjacent lines by escaping the newline (ie. backslash ...
TextFile
python
spack__spack
lib/spack/spack/vendor/archspec/cpu/schema.py
{ "start": 386, "end": 3710 }
class ____(collections.abc.MutableMapping): """Lazy dictionary that gets constructed on first access to any object key Args: factory (callable): factory function to construct the dictionary """ def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = arg...
LazyDictionary
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_spans_performance.py
{ "start": 61703, "end": 65892 }
class ____(OrganizationEventsSpansEndpointTestBase): URL = "sentry-api-0-organization-events-spans-stats" def test_require_span_param(self) -> None: response = self.client.get( self.url, data={"project": self.project.id}, format="json", ) assert resp...
OrganizationEventsSpansStatsEndpointTest
python
networkx__networkx
networkx/utils/tests/test_config.py
{ "start": 526, "end": 8717 }
class ____(Config): pass @pytest.mark.parametrize("cfg", [EmptyConfig(), Config()]) def test_config_empty(cfg): assert dir(cfg) == [] with pytest.raises(AttributeError): cfg.x = 1 with pytest.raises(KeyError): cfg["x"] = 1 with pytest.raises(AttributeError): cfg.x with ...
EmptyConfig
python
gevent__gevent
src/greentest/3.14/test_weakref.py
{ "start": 34067, "end": 37431 }
class ____(TestBase): def test_subclass_refs(self): class MyRef(weakref.ref): def __init__(self, ob, callback=None, value=42): self.value = value super().__init__(ob, callback) def __call__(self): self.called = True ret...
SubclassableWeakrefTestCase
python
huggingface__transformers
src/transformers/models/gpt2/modeling_gpt2.py
{ "start": 25566, "end": 34779 }
class ____(GPT2PreTrainedModel): def __init__(self, config): super().__init__(config) self.embed_dim = config.hidden_size self.wte = nn.Embedding(config.vocab_size, self.embed_dim) self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim) self.drop = nn.Dropo...
GPT2Model
python
tensorflow__tensorflow
tensorflow/python/layers/utils_test.py
{ "start": 958, "end": 3948 }
class ____(test.TestCase): def testConvertDataFormat(self): self.assertEqual('NCDHW', utils.convert_data_format('channels_first', 5)) self.assertEqual('NCHW', utils.convert_data_format('channels_first', 4)) self.assertEqual('NCW', utils.convert_data_format('channels_first', 3)) self.assertEqual('NHWC...
ConvUtilsTest
python
doocs__leetcode
solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/Solution.py
{ "start": 0, "end": 626 }
class ____: def maxValueAfterReverse(self, nums: List[int]) -> int: ans = s = sum(abs(x - y) for x, y in pairwise(nums)) for x, y in pairwise(nums): ans = max(ans, s + abs(nums[0] - y) - abs(x - y)) ans = max(ans, s + abs(nums[-1] - x) - abs(x - y)) for k1, k2 in pair...
Solution
python
walkccc__LeetCode
solutions/53. Maximum Subarray/53-2.py
{ "start": 0, "end": 197 }
class ____: def maxSubArray(self, nums: list[int]) -> int: ans = -math.inf summ = 0 for num in nums: summ = max(num, summ + num) ans = max(ans, summ) return ans
Solution
python
bokeh__bokeh
tests/unit/bokeh/server/test_auth_provider.py
{ "start": 9593, "end": 10005 }
class ____(RequestHandler): pass """, func, suffix='.py') def test_login_handler_wrong_type(self) -> None: def func(filename: str): with pytest.raises(ValueError) as e: bsa.AuthModule(filename) assert str(e) == "LoginHandler must be a Tornado RequestHandler" ...
LoginHandler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 28471, "end": 28696 }
class ____(_ReturnsStringKey, RoleImpl): __slots__ = () def _post_coercion(self, element, *, as_key=False, **kw): if as_key: return element.key else: return element
DMLColumnImpl
python
huggingface__transformers
tests/models/mgp_str/test_modeling_mgp_str.py
{ "start": 1317, "end": 4108 }
class ____: def __init__( self, parent, is_training=False, batch_size=13, image_size=(32, 128), patch_size=4, num_channels=3, max_token_length=27, num_character_labels=38, num_bpe_labels=99, num_wordpiece_labels=99, hidd...
MgpstrModelTester
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py
{ "start": 9166, "end": 14008 }
class ____: FILTER = {"Name": "replication-task-arn", "Values": [TASK_ARN]} MOCK_DATA = { "replication_task_id": "test_task", "source_endpoint_arn": "source-endpoint-arn", "target_endpoint_arn": "target-endpoint-arn", "replication_instance_arn": "replication-instance-arn", ...
TestDmsDescribeTasksOperator
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/batch_test.py
{ "start": 17813, "end": 20777 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( dataset_range=[100], batch_size=[2, 7]))) def testBatch( self, dataset_range: int, batc...
BatchGlobalShuffleTest
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 5452, "end": 5904 }
class ____(BaseConfig): extension: str bypass_reason: Optional[str] = Field(description="Reason why this type is considered unsupported.") @validator("extension", always=True) def extension_properly_formatted(cls, extension: str) -> str: if not extension.startswith(".") or len(extension) < 2: ...
UnsupportedFileTypeConfig
python
jmcnamara__XlsxWriter
xlsxwriter/chartsheet.py
{ "start": 405, "end": 5653 }
class ____(worksheet.Worksheet): """ A class for writing the Excel XLSX Chartsheet file. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self...
Chartsheet
python
catalyst-team__catalyst
catalyst/callbacks/metrics/segmentation.py
{ "start": 214, "end": 4129 }
class ____(BatchMetricCallback): """IOU metric callback. Args: input_key: input key to use for metric calculation, specifies our `y_pred` target_key: output key to use for metric calculation, specifies our `y_true` class_dim: indicates class dimension (K) for ``outputs`` and ...
IOUCallback
python
django__django
tests/extra_regress/models.py
{ "start": 104, "end": 746 }
class ____(models.Model): base = models.ForeignKey("self", models.SET_NULL, null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now) def save(self, *args, force_insert=False, force_update=False, **kwargs): super().save( ...
RevisionableModel
python
RaRe-Technologies__gensim
gensim/test/test_matutils.py
{ "start": 4924, "end": 10561 }
class ____(unittest.TestCase): # test unitvec def test_sparse_npfloat32(self): input_vector = sparse.csr_matrix(np.asarray([[1, 0, 0, 0, 3], [0, 0, 4, 3, 0]])).astype(np.float32) unit_vector = matutils.unitvec(input_vector) man_unit_vector = manual_unitvec(input_vector) self.asse...
UnitvecTestCase
python
pytorch__pytorch
test/dynamo/test_package.py
{ "start": 1006, "end": 23980 }
class ____(torch._inductor.test_case.TestCase): def path(self): path = os.path.join(cache_dir(), f"package_{self.id()}") os.makedirs(path, exist_ok=True) return path def setUp(self): super().setUp() torch._dynamo.reset() torch._dynamo.utils.counters.clear() ...
TestPackage
python
celery__celery
t/unit/tasks/test_canvas.py
{ "start": 3411, "end": 11484 }
class ____(CanvasCase): def test_getitem_property_class(self): assert Signature.task assert Signature.args assert Signature.kwargs assert Signature.options assert Signature.subtask_type def test_getitem_property(self): assert SIG.task == 'TASK' assert SIG...
test_Signature
python
pallets__jinja
tests/test_utils.py
{ "start": 4447, "end": 6367 }
class ____: def test_lorem_ipsum_markup(self): """Test that output of lorem_ipsum is Markup by default.""" assert isinstance(generate_lorem_ipsum(), Markup) def test_lorem_ipsum_html(self): """Test that output of lorem_ipsum is a string_type when not html.""" assert isinstance(g...
TestLoremIpsum
python
ray-project__ray
python/ray/util/client/logsclient.py
{ "start": 700, "end": 4945 }
class ____: def __init__(self, client_worker: "Worker", metadata: list): """Initializes a thread-safe log stream over a Ray Client gRPC channel. Args: client_worker: The Ray Client worker that manages this client metadata: metadata to pass to gRPC requests """ ...
LogstreamClient
python
kamyu104__LeetCode-Solutions
Python/count-beautiful-numbers.py
{ "start": 99, "end": 1070 }
class ____(object): def beautifulNumbers(self, l, r): """ :type l: int :type r: int :rtype: int """ def count(x): s = map(lambda x: ord(x)-ord('0'), str(x)) dp = [collections.defaultdict(int) for _ in xrange(2)] dp[1][1, 0] = 1 ...
Solution
python
Textualize__textual
src/textual/events.py
{ "start": 25553, "end": 25907 }
class ____(Event, bubble=False): """Sent to App when a file delivery fails.""" key: str """The delivery key associated with the delivery.""" exception: BaseException """The exception that was raised during the delivery.""" name: str | None = None """Optional name returned to the app to id...
DeliveryFailed
python
mlflow__mlflow
mlflow/genai/scorers/builtin_scorers.py
{ "start": 63604, "end": 67942 }
class ____(BuiltInScorer): """ Completeness evaluates whether an AI assistant fully addresses all user questions in a single user prompt. For evaluating the completeness of a conversation, use the ConversationCompleteness scorer instead. This scorer analyzes a single turn of interaction (user ...
Completeness
python
numpy__numpy
numpy/fft/tests/test_helper.py
{ "start": 5167, "end": 5562 }
class ____: def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] assert_array_almost_equal(9 * fft.fftfreq(9), x) assert_array_almost_equal(9 * pi * fft.fftfreq(9, pi), x) x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1] assert_array_almost_equal(10 * fft.fftfreq(10), x) ...
TestFFTFreq
python
django__django
tests/admin_inlines/admin.py
{ "start": 5687, "end": 5831 }
class ____(forms.ModelForm): extra_field = forms.CharField() class Meta: model = FootNote fields = "__all__"
FootNoteForm
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 108883, "end": 109053 }
class ____(spack.error.SpackError): """ Raised when gpg has no default key added. """ def __init__(self, msg): super().__init__(msg)
NoKeyException
python
pandas-dev__pandas
pandas/core/indexes/accessors.py
{ "start": 16637, "end": 18047 }
class ____(Properties): """ Accessor object for datetimelike properties of the Series values. Returns a Series indexed like the original Series. Raises TypeError if the Series does not contain datetimelike values. Examples -------- >>> seconds_series = pd.Series( ... pd.period_rang...
PeriodProperties
python
apache__airflow
airflow-core/tests/unit/assets/test_manager.py
{ "start": 1889, "end": 7311 }
class ____: def test_register_asset_change_asset_doesnt_exist(self, mock_task_instance): asset = Asset(uri="asset_doesnt_exist", name="not exist") mock_session = mock.Mock(spec=Session) # Gotta mock up the query results mock_session.scalar.return_value = None asset_manger =...
TestAssetManager
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 140662, "end": 140800 }
class ____(str, Enum): PREFIX = "prefix" WHITESPACE = "whitespace" WORD = "word" MULTILINGUAL = "multilingual"
TokenizerType
python
sanic-org__sanic
examples/simple_async_view.py
{ "start": 124, "end": 511 }
class ____(HTTPMethodView): def get(self, request): return text("I am get method") def post(self, request): return text("I am post method") def put(self, request): return text("I am put method") def patch(self, request): return text("I am patch method") def delete...
SimpleView
python
scikit-image__scikit-image
src/skimage/feature/orb.py
{ "start": 636, "end": 13148 }
class ____(FeatureDetector, DescriptorExtractor): """Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor. Parameters ---------- n_keypoints : int, optional Number of keypoints to be returned. The function will return the best `n_keypoints` according to t...
ORB
python
pytorch__pytorch
torch/_dynamo/symbolic_convert.py
{ "start": 210505, "end": 216368 }
class ____(InliningInstructionTranslator): generated_items: list[VariableTracker] # Flag whether or not the InlineGenerator should consume the entire iterator def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.generated_items = [] self.gene...
InliningGeneratorInstructionTranslator
python
altair-viz__altair
altair/vegalite/v6/api.py
{ "start": 145119, "end": 148040 }
class ____(channels._EncodingMixin): data: Any def facet( self, facet: Optional[str | Facet] = Undefined, row: Optional[str | FacetFieldDef | Row] = Undefined, column: Optional[str | FacetFieldDef | Column] = Undefined, data: Optional[ChartDataType] = Undefined, ...
_EncodingMixin
python
pypa__pip
src/pip/_vendor/pkg_resources/__init__.py
{ "start": 96195, "end": 112210 }
class ____: """Wrap an actual or potential sys.path entry w/metadata""" PKG_INFO = 'PKG-INFO' def __init__( self, location: str | None = None, metadata: _MetadataType = None, project_name: str | None = None, version: str | None = None, py_version: str | None...
Distribution
python
PrefectHQ__prefect
tests/server/models/test_task_run_states.py
{ "start": 10069, "end": 11068 }
class ____: async def test_delete_task_run_state(self, db, task_run, session): # create a task run to read task_run_state = ( await models.task_runs.set_task_run_state( session=session, task_run_id=task_run.id, state=Running(), ...
TestDeleteTaskRunState
python
django__django
tests/select_related/models.py
{ "start": 1999, "end": 2314 }
class ____(models.Model): tag = models.CharField(max_length=30) content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="select_related_tagged_items" ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id")
TaggedItem
python
python-poetry__poetry
tests/utils/env/test_env.py
{ "start": 1259, "end": 20183 }
class ____(VirtualEnv): def __init__( self, path: Path, base: Path | None = None, sys_path: list[str] | None = None, ) -> None: super().__init__(path, base=base) self._sys_path = sys_path @property def sys_path(self) -> list[str]: if self._sys_pa...
MockVirtualEnv
python
encode__django-rest-framework
tests/models.py
{ "start": 1571, "end": 1865 }
class ____(RESTFrameworkModel): name = models.CharField(max_length=100) target = models.ForeignKey(ForeignKeyTarget, related_name='sources', help_text='Target', verbose_name='Target', on_delete=models.CASCADE)
ForeignKeySource
python
plotly__plotly.py
plotly/graph_objs/layout/polar/radialaxis/_tickfont.py
{ "start": 235, "end": 9940 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.polar.radialaxis" _path_str = "layout.polar.radialaxis.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "wei...
Tickfont
python
getsentry__sentry
tests/sentry/integrations/github/test_integration.py
{ "start": 4036, "end": 86349 }
class ____(IntegrationTestCase): provider = GitHubIntegrationProvider base_url = "https://api.github.com" def setUp(self) -> None: super().setUp() self.installation_id = "install_1" self.user_id = "user_1" self.app_id = "app_1" self.access_token = "xxxxx-xxxxxxxxx-x...
GitHubIntegrationTest