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 | pytest-dev__pytest | src/_pytest/unittest.py | {
"start": 2217,
"end": 7365
} | class ____(Class):
# Marker for fixturemanger.getfixtureinfo()
# to declare that our children do not support funcargs.
nofuncargs = True
def newinstance(self):
# TestCase __init__ takes the method (test) name. The TestCase
# constructor treats the name "runTest" as a special no-op, so i... | UnitTestCase |
python | sqlalchemy__sqlalchemy | test/orm/test_mapper.py | {
"start": 81171,
"end": 82658
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"foo",
metadata,
Column("id", Integer, primary_key=True),
Column("someprop", Integer),
)
def _test(self, value, instancelevel=None):
class Foo:
... | IsUserlandTest |
python | google__jax | jax/experimental/colocated_python/func.py | {
"start": 1424,
"end": 1643
} | class ____:
"""User function wrapped by colocated_python."""
fun: Callable[..., Any]
fun_sourceinfo: str | None
fun_signature: inspect.Signature | None
@dataclasses.dataclass(frozen=True, slots=True)
| FunctionInfo |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 1633,
"end": 2055
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.MultifieldUniqueModel
sqlalchemy_get_or_create = ("slug", "text",)
sqlalchemy_session = models.session
sqlalchemy_session_persistence = 'commit'
id = factory.Sequence(lambda n: n)
slug = factory.Sequence(lambda n... | WithMultipleGetOrCreateFieldsFactory |
python | fsspec__filesystem_spec | fsspec/core.py | {
"start": 23238,
"end": 23829
} | class ____(io.TextIOWrapper):
"""TextIOWrapper cannot be pickled. This solves it.
Requires that ``buffer`` be pickleable, which all instances of
AbstractBufferedFile are.
"""
def __init__(
self,
buffer,
encoding=None,
errors=None,
newline=None,
line_... | PickleableTextIOWrapper |
python | jazzband__django-pipeline | pipeline/forms.py | {
"start": 3010,
"end": 7847
} | class ____(type):
"""Metaclass for the PipelineFormMedia class.
This is responsible for converting CSS/JavaScript packages defined in
Pipeline into lists of files to include on a page. It handles access to the
:py:attr:`css` and :py:attr:`js` attributes on the class, generating a
list of files to r... | PipelineFormMediaMetaClass |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 541014,
"end": 541355
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("PullRequestReviewThread", graphql_name="node")
| PullRequestReviewThreadEdge |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 39963,
"end": 42032
} | class ____(TestCase):
@njit
def foo(fromty, toty):
l = listobject.new_list(toty)
l.append(fromty(0))
def check_good(self, fromty, toty):
TestItemCasting.foo(fromty, toty)
def check_bad(self, fromty, toty):
with self.assertRaises(TypingError) as raises:
Test... | TestItemCasting |
python | mkdocs__mkdocs | mkdocs/utils/__init__.py | {
"start": 11543,
"end": 12280
} | class ____:
"""Same as a read-only property, but allows overwriting the field for good."""
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __get__(self, instance, owner=None):
if instance is None:
return self
return self.func(instance)... | weak_property |
python | django__django | tests/invalid_models_tests/test_relative_fields.py | {
"start": 74711,
"end": 84133
} | class ____(SimpleTestCase):
def test_m2m_field_argument_validation(self):
"""
ManyToManyField accepts the ``through_fields`` kwarg
only if an intermediary table is specified.
"""
class Fan(models.Model):
pass
with self.assertRaisesMessage(
Va... | M2mThroughFieldsTests |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_hive_to_dynamodb.py | {
"start": 1258,
"end": 5887
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
dag = DAG("test_dag_id", schedule=None, default_args=args)
self.dag = dag
self.sql = "SELECT 1"
self.hook = DynamoDBHook(aws_conn_id="aws_default", region_name="us-east-1")
@stati... | TestHiveToDynamoDBOperator |
python | kamyu104__LeetCode-Solutions | Python/validate-binary-search-tree.py | {
"start": 1049,
"end": 1511
} | class ____(object):
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
return self.isValidBSTRecu(root, float("-inf"), float("inf"))
def isValidBSTRecu(self, root, low, high):
if root is None:
return True
return low < root.val and root.val < ... | Solution2 |
python | kamyu104__LeetCode-Solutions | Python/longest-non-decreasing-subarray-after-replacing-at-most-one-element.py | {
"start": 42,
"end": 702
} | class ____(object):
def longestSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right = [1]*len(nums)
for i in reversed(xrange(len(nums)-1)):
if nums[i] <= nums[i+1]:
right[i] = right[i+1]+1
result = min(max(right)+1,... | Solution |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 10070,
"end": 11055
} | class ____:
def setup_method(self):
self.rdt = None
self.dec = 14
self.type = None
@pytest.fixture
def idct_lock(self):
return threading.Lock()
def test_definition(self, idct_lock):
for i in FFTWDATA_SIZES:
with idct_lock:
xr, yr, dt ... | _TestIDCTBase |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_pathconverter.py | {
"start": 4176,
"end": 8194
} | class ____(util.MdCase):
"""Test absolute paths."""
extension = ["pymdownx.pathconverter"]
extension_configs = {
"pymdownx.pathconverter": {
"base_path": "/Some/fake/path",
"absolute": True
}
}
def test_in_script(self):
"""Test that we do not parse i... | TestAbsolute |
python | keras-team__keras | keras/src/metrics/f_score_metrics_test.py | {
"start": 14009,
"end": 15160
} | class ____(testing.TestCase):
def test_config(self):
f1_obj = f_score_metrics.F1Score(dtype="float32")
config = f1_obj.get_config()
self.assertNotIn("beta", config)
# Check save and restore config
f1_obj = f_score_metrics.F1Score.from_config(config)
self.assertEqual(... | F1ScoreTest |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 10581,
"end": 10715
} | class ____(PrefectException):
"""Raised when an incorrect URL is provided to a GitHub filesystem block."""
| InvalidRepositoryURLError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 1795,
"end": 1918
} | class ____(ColumnArgumentRole):
__slots__ = ()
_role_name = "Column expression or string key"
| ColumnArgumentOrKeyRole |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 58904,
"end": 61736
} | class ____(nn.Module):
"""Split Residual Vector Quantizer."""
def __init__(self, config: MimiConfig):
super().__init__()
self.codebook_size = config.codebook_size
self.frame_rate = config.frame_rate
self.max_num_quantizers = config.num_quantizers
self.num_semantic_quant... | MimiSplitResidualVectorQuantizer |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 79412,
"end": 84346
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
... | MMGroundingDinoModelOutput |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 4777,
"end": 5008
} | class ____:
def m[S](self: S) -> S:
type S = int
print(S) # not a reference to the type variable, so not touched by the autofix
return 42
MetaType = TypeVar("MetaType")
| NamesShadowingTypeVarAreNotTouched |
python | django__django | tests/invalid_models_tests/test_ordinary_fields.py | {
"start": 28056,
"end": 29058
} | class ____(SimpleTestCase):
def test_pillow_installed(self):
try:
from PIL import Image # NOQA
except ImportError:
pillow_installed = False
else:
pillow_installed = True
class Model(models.Model):
field = models.ImageField(upload_to="... | ImageFieldTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py | {
"start": 13582,
"end": 17073
} | class ____(GoogleCloudBaseOperator):
"""
Creates a new alert or updates an existing policy identified the name field in the alerts parameter.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:StackdriverUpsertAlertOperator`
:p... | StackdriverUpsertAlertOperator |
python | ray-project__ray | python/ray/train/v2/jax/config.py | {
"start": 515,
"end": 3055
} | class ____(BackendConfig):
use_tpu: bool = False
use_gpu: bool = False
@property
def backend_cls(self):
return _JaxBackend
def _setup_jax_distributed_environment(
master_addr_with_port: str,
num_workers: int,
index: int,
use_tpu: bool,
use_gpu: bool,
resources_per_work... | JaxConfig |
python | RaRe-Technologies__gensim | gensim/models/basemodel.py | {
"start": 0,
"end": 1554
} | class ____:
def print_topic(self, topicno, topn=10):
"""Get a single topic as a formatted string.
Parameters
----------
topicno : int
Topic id.
topn : int
Number of words from topic that will be used.
Returns
-------
str
... | BaseTopicModel |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 283580,
"end": 284231
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("DiscussionCommentEdge"), graphql_name="edges"
)
nodes = s... | DiscussionCommentConnection |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/codegen/computation_kernel_emitter_test.py | {
"start": 1735,
"end": 3303
} | class ____(parameterized.TestCase):
def test_basic_call(self):
dtype = np.dtype(np.float32)
lhs_literal = base_utilities.create_scalar_literal(1.0, dtype)
lhs_parameter = testlib_base.HloInstruction.create_parameter(
0, lhs_literal.shape(), "lhs"
)
rhs_literal = base_utilities.create_sc... | CallKernelTest |
python | langchain-ai__langchain | libs/core/langchain_core/messages/tool.py | {
"start": 8194,
"end": 12584
} | class ____(TypedDict):
"""A chunk of a tool call (yielded when streaming).
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
all string attributes are concatenated. Chunks are only merged if their
values of `index` are equal and not None.
Example:
```python
left_chunks = ... | ToolCallChunk |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 13033,
"end": 13150
} | class ____(models.Model):
fk = models.ForeignKey(SecondLevelInheritedModel, on_delete=models.CASCADE)
| MultiOneToOne |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1598236,
"end": 1598737
} | class ____(sgqlc.types.Union):
"""Types which can be parameters for `RepositoryRule` objects."""
__schema__ = github_schema
__types__ = (
BranchNamePatternParameters,
CommitAuthorEmailPatternParameters,
CommitMessagePatternParameters,
CommitterEmailPatternParameters,
... | RuleParameters |
python | paramiko__paramiko | paramiko/rsakey.py | {
"start": 1222,
"end": 7546
} | class ____(PKey):
"""
Representation of an RSA key which can be used to sign and verify SSH2
data.
"""
name = "ssh-rsa"
HASHES = {
"ssh-rsa": hashes.SHA1,
"ssh-rsa-cert-v01@openssh.com": hashes.SHA1,
"rsa-sha2-256": hashes.SHA256,
"rsa-sha2-256-cert-v01@openssh.c... | RSAKey |
python | pytorch__pytorch | test/mobile/model_test/quantization_ops.py | {
"start": 1805,
"end": 4389
} | class ____:
def __init__(self) -> None:
super().__init__()
self.module = self.M()
def getModule(self):
return torch.ao.quantization.quantize_dynamic(self.module, dtype=torch.qint8)
class M(torch.nn.Module):
def __init__(self) -> None:
super(DynamicQuantModule.M,... | DynamicQuantModule |
python | numpy__numpy | numpy/f2py/_backends/_distutils.py | {
"start": 289,
"end": 2385
} | class ____(Backend):
def __init__(sef, *args, **kwargs):
warnings.warn(
"\ndistutils has been deprecated since NumPy 1.26.x\n"
"Use the Meson backend instead, or generate wrappers"
" without -c and use a custom build script",
VisibleDeprecationWarning,
... | DistutilsBackend |
python | fluentpython__example-code | 17-futures/countries/flags2_await.py | {
"start": 443,
"end": 3083
} | class ____(Exception): # <1>
def __init__(self, country_code):
self.country_code = country_code
async def get_flag(base_url, cc): # <2>
url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
with closing(await aiohttp.request('GET', url)) as resp:
if resp.status == 200:
imag... | FetchError |
python | ray-project__ray | doc/source/tune/doc_code/trial_checkpoint.py | {
"start": 4409,
"end": 5081
} | class ____(tune.Callback):
def __init__(self, iterations_per_checkpoint: int):
self.steps_per_checkpoint = iterations_per_checkpoint
self._trials_last_checkpoint = {}
def on_trial_result(
self, iteration: int, trials: list[Trial], trial: Trial, result: dict, **info
):
curren... | CheckpointByStepsTaken |
python | doocs__leetcode | solution/1500-1599/1525.Number of Good Ways to Split a String/Solution.py | {
"start": 0,
"end": 298
} | class ____:
def numSplits(self, s: str) -> int:
cnt = Counter(s)
vis = set()
ans = 0
for c in s:
vis.add(c)
cnt[c] -= 1
if cnt[c] == 0:
cnt.pop(c)
ans += len(vis) == len(cnt)
return ans
| Solution |
python | has2k1__plotnine | plotnine/themes/seaborn_rcmod.py | {
"start": 15337,
"end": 15502
} | class ____(_RCAesthetics):
"""Light wrapper on a dict to set context temporarily."""
_keys = _context_keys
_set = staticmethod(set_context)
| _PlottingContext |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 4295,
"end": 4399
} | class ____(BaseStringEnumerationType):
"""Set of enumerated xsd:string values."""
| XsdStringEnumeration |
python | kamyu104__LeetCode-Solutions | Python/sorted-gcd-pair-queries.py | {
"start": 146,
"end": 779
} | class ____(object):
def gcdValues(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[int]
:rtype: List[int]
"""
cnt1 = collections.Counter(nums)
cnt2 = [0]*(max(nums)+1)
for g in reversed(xrange(1, len(cnt2))):
c = sum(cnt1... | Solution |
python | encode__django-rest-framework | tests/browsable_api/views.py | {
"start": 327,
"end": 524
} | class ____(BasePermission):
def has_object_permission(self, request, view, obj):
return request.user.is_staff or (request.user == obj.owner.organization_user.user)
| OrganizationPermissions |
python | weaviate__weaviate-python-client | weaviate/gql/aggregate.py | {
"start": 1791,
"end": 17410
} | class ____(GraphQL):
"""AggregateBuilder class used to aggregate Weaviate objects."""
def __init__(self, class_name: str):
"""Initialize a AggregateBuilder class instance.
Args:
class_name: Class name of the objects to be aggregated.
"""
self._class_name: str = _cap... | AggregateBuilder |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 13802,
"end": 17816
} | class ____(_BaseDataclass):
"""
Common parameters used for chat inference
Args:
temperature (float): A param used to control randomness and creativity during inference.
**Optional**, defaults to ``1.0``
max_tokens (int): The maximum number of new tokens to generate.
... | ChatParams |
python | lepture__authlib | authlib/integrations/flask_oauth2/requests.py | {
"start": 1281,
"end": 1480
} | class ____(JsonRequest):
def __init__(self, request: Request):
super().__init__(request.method, request.url, request.headers)
self.payload = FlaskJsonPayload(request)
| FlaskJsonRequest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 19152,
"end": 19270
} | class ____(test.TestCase, _LUSolve):
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
| LUSolveStatic |
python | modin-project__modin | modin/config/envvars.py | {
"start": 1290,
"end": 2597
} | class ____(Parameter, type=str, abstract=True):
"""Base class for environment variables-based configuration."""
varname: Optional[str] = None
@classmethod
def _get_value_from_config(cls) -> Any:
"""
Read the value from environment variable.
Returns
-------
Any
... | EnvironmentVariable |
python | lxml__lxml | src/lxml/html/tests/test_select.py | {
"start": 47,
"end": 1771
} | class ____(unittest.TestCase):
@staticmethod
def _evaluate_select(options, multiple=False):
options = ''.join('<option' + (' selected="selected"' if selected else '') + '>' + option + '</option>'
for option, selected in options)
string = '<title>test</title><form><selec... | SelectTest |
python | getsentry__sentry | tests/sentry/ratelimits/utils/test_get_ratelimit_key.py | {
"start": 1012,
"end": 1555
} | class ____(Endpoint):
permission_classes = (AllowAny,)
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(20, 1, CONCURRENT_RATE_LIMIT),
RateLimitCategory.USER: RateLimit(20, 1, CONCURRENT_RA... | APITestEndpoint |
python | getsentry__sentry | src/sentry/api/endpoints/organization_releases.py | {
"start": 37459,
"end": 39421
} | class ____(OrganizationReleasesBaseEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, organization: Organization) -> Response:
"""
List an Organization's Releases specifically for building timeseries
`````````````````````````````... | OrganizationReleasesStatsEndpoint |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 40549,
"end": 47660
} | class ____(fixtures.ORMTest):
def _fixture(self):
class Post:
def __init__(self, name):
self.name = name
__hash__ = None
def __eq__(self, other):
return other is not None and other.name == self.name
class Blog:
def __... | PendingBackrefTest |
python | allegroai__clearml | clearml/binding/frameworks/lightgbm_bind.py | {
"start": 344,
"end": 5299
} | class ____(PatchBaseModelIO):
_current_task = None
__patched = None
@staticmethod
def update_current_task(task: Any, **kwargs: Any) -> None:
PatchLIGHTgbmModelIO._current_task = task
if not task:
return
PatchLIGHTgbmModelIO._patch_model_io()
PostImportHookPat... | PatchLIGHTgbmModelIO |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_natural_language.py | {
"start": 1398,
"end": 5656
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
self.hook = CloudNaturalLanguageHook(gcp_conn_id="test")
@mock.patch(
"a... | TestCloudNaturalLanguageHook |
python | ray-project__ray | python/ray/data/preprocessor.py | {
"start": 534,
"end": 698
} | class ____(RuntimeError):
"""Error raised when the preprocessor needs to be fitted first."""
pass
@PublicAPI(stability="beta")
| PreprocessorNotFittedException |
python | getsentry__sentry | tests/apidocs/endpoints/releases/test_deploys.py | {
"start": 321,
"end": 2457
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
project = self.create_project(name="foo")
release = self.create_release(project=project, version="1")
release.add_project(project)
prod_deploy = Deploy.objects.create(
environment_id=Environment.objects.create(
... | ReleaseDeploysDocs |
python | spack__spack | lib/spack/spack/vendor/jinja2/lexer.py | {
"start": 13075,
"end": 13414
} | class ____(tuple):
"""A special tuple for marking a point in the state that can have
lstrip applied.
"""
__slots__ = ()
# Even though it looks like a no-op, creating instances fails
# without this.
def __new__(cls, *members, **kwargs): # type: ignore
return super().__new__(cls, me... | OptionalLStrip |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ltc_address.py | {
"start": 1891,
"end": 4641
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid Litecoin addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
... | ExpectColumnValuesToBeValidLtcAddress |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 132550,
"end": 134245
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
host: str,
port: int,
database: str,
username: str,
password: Optional[str] = None,
jdbc_url_params: Optional[str] = None,
ssl: Optional[bool] = None,
):
... | CockroachdbSource |
python | spyder-ide__spyder | spyder/utils/snippets/nodes.py | {
"start": 2582,
"end": 5521
} | class ____(ASTNode):
"""
AST node representing a text sequence.
The sequence is composed of one or more LeafNodes or any ASTNode.
"""
KIND = NodeKind.TEXT
def __init__(self, *tokens):
ASTNode.__init__(self)
self._tokens = tokens
for i, token in enumerate(tokens):
... | TextNode |
python | facebook__pyre-check | scripts/callgraph_utilities.py | {
"start": 4536,
"end": 5321
} | class ____(InputFormat):
def extract_caller(self, qualifier: str) -> str:
return self.format_qualifier(qualifier)
@staticmethod
def format_qualifier(qualifier: str) -> str:
qualifier = qualifier.replace("<locals>.", "")
split = qualifier.split(":")
if len(split) != 2:
... | DynamicCallGraphInputFormat |
python | spack__spack | lib/spack/spack/llnl/util/tty/log.py | {
"start": 4407,
"end": 11397
} | class ____(preserve_terminal_settings):
"""Context manager to disable line editing and echoing.
Use this with ``sys.stdin`` for keyboard input, e.g.::
with keyboard_input(sys.stdin) as kb:
while True:
kb.check_fg_bg()
r, w, x = select.select([sys.stdin], [],... | keyboard_input |
python | nedbat__coveragepy | coverage/plugin_support.py | {
"start": 5263,
"end": 7025
} | class ____(CoveragePlugin):
"""Wrap a plugin, and use debug to report on what it's doing."""
def __init__(self, plugin: CoveragePlugin, debug: LabelledDebug) -> None:
super().__init__()
self.plugin = plugin
self.debug = debug
def file_tracer(self, filename: str) -> FileTracer | Non... | DebugPluginWrapper |
python | kamyu104__LeetCode-Solutions | Python/power-of-two.py | {
"start": 29,
"end": 179
} | class ____(object):
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
return n > 0 and (n & (n - 1)) == 0
| Solution |
python | tensorflow__tensorflow | tensorflow/python/util/fast_module_type_test.py | {
"start": 908,
"end": 1223
} | class ____(FastModuleType):
def _getattribute1(self, name): # pylint: disable=unused-argument
return 2
def _getattribute2(self, name): # pylint: disable=unused-argument
raise AttributeError("Pass to getattr")
def _getattr(self, name): # pylint: disable=unused-argument
return 3
| ChildFastModule |
python | PrefectHQ__prefect | src/prefect/runner/_observers.py | {
"start": 677,
"end": 777
} | class ____(Protocol):
def __call__(self, flow_run_id: uuid.UUID) -> None: ...
| OnCancellingCallback |
python | PrefectHQ__prefect | src/prefect/task_runners.py | {
"start": 1404,
"end": 7861
} | class ____(abc.ABC, Generic[F]):
"""
Abstract base class for task runners.
A task runner is responsible for submitting tasks to the task run engine running
in an execution environment. Submitted tasks are non-blocking and return a future
object that can be used to wait for the task to complete and ... | TaskRunner |
python | python-visualization__folium | folium/plugins/feature_group_sub_group.py | {
"start": 107,
"end": 2705
} | class ____(JSCSSMixin, Layer):
"""
Creates a Feature Group that adds its child layers into a parent group when
added to a map (e.g. through LayerControl). Useful to create nested groups,
or cluster markers from multiple overlays. From [0].
[0] https://github.com/ghybs/Leaflet.FeatureGroup.SubGroup
... | FeatureGroupSubGroup |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_multiprotocol.py | {
"start": 283,
"end": 4816
} | class ____(Executor):
@requests
def foo(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.text = 'processed'
@pytest.mark.parametrize(
'ports,protocols',
[
*[
([random_port(), random_port(), random_port()], list(protocols))
for protocols in ... | MyExecutor |
python | ethereum__web3.py | web3/_utils/encoding.py | {
"start": 4734,
"end": 7487
} | class ____:
"""
Friendly JSON serializer & deserializer
When encoding or decoding fails, this class collects
information on which fields failed, to show more
helpful information in the raised error messages.
"""
def _json_mapping_errors(self, mapping: dict[Any, Any]) -> Iterable[str]:
... | FriendlyJsonSerde |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 17693,
"end": 18324
} | class ____(unittest.TestCase):
"""A base class for socket tests.
Subclasses must provide methods newSocket() to return a new socket
and bindSock(sock) to bind it to an unused address.
Creates a socket self.serv and sets self.serv_addr to its address.
"""
def setUp(self):
self.serv = s... | SocketTestBase |
python | walkccc__LeetCode | solutions/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum/2996.py | {
"start": 0,
"end": 275
} | class ____:
def missingInteger(self, nums: list[int]) -> int:
numsSet = set(nums)
ans = nums[0]
for i in range(1, len(nums)):
if nums[i] != nums[i - 1] + 1:
break
ans += nums[i]
while ans in numsSet:
ans += 1
return ans
| Solution |
python | google__pytype | pytype/metrics.py | {
"start": 5102,
"end": 5624
} | class ____(Metric):
"""A monotonically increasing metric."""
def __init__(self, name):
super().__init__(name)
self._total = 0
def inc(self, count=1):
"""Increment the metric by the specified amount."""
if count < 0:
raise ValueError("Counter must be monotonically increasing.")
if not _... | Counter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec3.py | {
"start": 1576,
"end": 1657
} | class ____:
def __call__(self, x: int | str, y: int = 3) -> None: ...
| Callback1 |
python | kamyu104__LeetCode-Solutions | Python/maximize-sum-of-weights-after-edge-removals.py | {
"start": 2590,
"end": 4509
} | class ____(object):
def maximizeSumOfWeights(self, edges, k):
"""
:type edges: List[List[int]]
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target):
i = left
... | Solution2 |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_image_ops_test.py | {
"start": 1306,
"end": 2454
} | class ____(test.TestCase):
def _testBrightness(self, x_np, y_np, delta, tol=1e-6):
with self.cached_session():
x = _get_weak_tensor(x_np, shape=x_np.shape)
y = image_ops.adjust_brightness(x, delta)
y_tf = self.evaluate(y)
self.assertIsInstance(y, WeakTensor)
self.assertAllClose(y_t... | AdjustBrightnessTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/discogs/views.py | {
"start": 357,
"end": 1050
} | class ____(OAuthAdapter):
provider_id = "discogs"
request_token_url = "https://api.discogs.com/oauth/request_token" # nosec
access_token_url = "https://api.discogs.com/oauth/access_token" # nosec
authorize_url = "https://discogs.com/oauth/authorize"
def complete_login(self, request, app, token, r... | DiscogsOAuthAdapter |
python | vyperlang__vyper | tests/evm_backends/revm_env.py | {
"start": 235,
"end": 4725
} | class ____(BaseEnv):
invalid_opcode_error = "InvalidFEOpcode"
out_of_gas_error = "OutOfGas"
contract_size_limit_error = "CreateContractSizeLimit"
initcode_size_limit_error = "CreateInitCodeSizeLimit"
def __init__(
self,
gas_limit: int,
account_keys: list[PrivateKey],
... | RevmEnv |
python | getsentry__sentry | tests/sentry/sentry_apps/external_requests/test_select_requester.py | {
"start": 837,
"end": 13224
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(name="foo")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(slug="boop", organization=self.org)
self.sentry_app = self.create_sentry_app(
... | TestSelectRequester |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/vertex_ai/generative_model.py | {
"start": 18097,
"end": 19485
} | class ____(GoogleBaseHook):
"""Use the Vertex AI SDK for Python to create and manage your experiment runs."""
@GoogleBaseHook.fallback_to_default_project_id
def delete_experiment_run(
self,
experiment_run_name: str,
experiment_name: str,
location: str,
project_id: st... | ExperimentRunHook |
python | kamyu104__LeetCode-Solutions | Python/put-boxes-into-the-warehouse-i.py | {
"start": 506,
"end": 1068
} | class ____(object):
def maxBoxesInWarehouse(self, boxes, warehouse):
"""
:type boxes: List[int]
:type warehouse: List[int]
:rtype: int
"""
boxes.sort()
for i in xrange(1, len(warehouse)):
warehouse[i] = min(warehouse[i], warehouse[i-1])
res... | Solution2 |
python | numpy__numpy | tools/swig/test/testFlat.py | {
"start": 3668,
"end": 3925
} | class ____(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
######################################################################
| intTestCase |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_exception_variations.py | {
"start": 1535,
"end": 8776
} | class ____(__TestCase):
def test_try_except_else_finally(self):
hit_except = False
hit_else = False
hit_finally = False
try:
raise Exception('nyaa!')
except:
hit_except = True
else:
hit_else = True
finally:
hit_... | ExceptTestCases |
python | apache__airflow | providers/dbt/cloud/tests/unit/dbt/cloud/utils/test_openlineage.py | {
"start": 5270,
"end": 8063
} | class ____:
@patch("importlib.metadata.version", return_value="2.3.0")
@patch("airflow.providers.openlineage.plugins.listener.get_openlineage_listener")
@patch("airflow.providers.openlineage.plugins.adapter.OpenLineageAdapter.build_task_instance_run_id")
@patch("airflow.providers.openlineage.plugins.ada... | TestGenerateOpenLineageEventsFromDbtCloudRun |
python | scipy__scipy | scipy/interpolate/_fitpack2.py | {
"start": 56420,
"end": 61350
} | class ____(BivariateSpline):
"""
Bivariate spline approximation over a rectangular mesh.
Can be used for both smoothing and interpolating data.
Parameters
----------
x,y : array_like
1-D arrays of coordinates in strictly ascending order.
Evaluated points outside the data range ... | RectBivariateSpline |
python | google__jax | tests/pjit_test.py | {
"start": 3399,
"end": 44770
} | class ____(jtu.BufferDonationTestCase):
@jtu.with_mesh([('x', 1)])
def testDeviceBufferAval(self):
@partial(pjit, in_shardings=None, out_shardings=P('x'))
def f(x):
return x
shape = (2, 2)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
actual = f(x)
expected = x
... | PJitTest |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 80117,
"end": 82783
} | class ____(SocketDummyServerTestCase):
def test_stream_none_unchunked_response_does_not_hang(self) -> None:
done_event = Event()
def socket_handler(listener: socket.socket) -> None:
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
... | TestStream |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 421636,
"end": 421902
} | class ____(BatchRequest):
"""
Updates a batch of tasks.
Headers Content type should be 'application/json-lines'.
"""
_service = "tasks"
_action = "update_batch"
_version = "2.20"
_batched_request_cls = UpdateRequest
| UpdateBatchRequest |
python | apache__airflow | airflow-core/src/airflow/jobs/scheduler_job_runner.py | {
"start": 6160,
"end": 7716
} | class ____:
"""
Dataclass to represent concurrency maps.
It contains a map from (dag_id, task_id) to # of task instances, a map from (dag_id, task_id)
to # of task instances in the given state list and a map from (dag_id, run_id, task_id)
to # of task instances in the given state list in each DAG r... | ConcurrencyMap |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-pebblo/llama_index/readers/pebblo/base.py | {
"start": 510,
"end": 9182
} | class ____(BaseReader):
"""
Pebblo Safe Loader class is a wrapper around document loaders enabling the data
to be scrutinized.
"""
_discover_sent: bool = False
_loader_sent: bool = False
def __init__(
self,
llama_reader: BaseReader,
name: str,
owner: str = "... | PebbloSafeReader |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_ignore_error04.py | {
"start": 315,
"end": 973
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("ignore_error04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | openai__gym | gym/wrappers/transform_reward.py | {
"start": 115,
"end": 1332
} | class ____(RewardWrapper):
"""Transform the reward via an arbitrary function.
Warning:
If the base environment specifies a reward range which is not invariant under :attr:`f`, the :attr:`reward_range` of the wrapped environment will be incorrect.
Example:
>>> import gym
>>> env = g... | TransformReward |
python | huggingface__transformers | src/transformers/models/kosmos2_5/modeling_kosmos2_5.py | {
"start": 35888,
"end": 36837
} | class ____(nn.Module):
def __init__(self, config: Kosmos2_5TextConfig):
super().__init__()
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
self.fc1 = nn.Linear(config.embed_dim, config... | Kosmos2_5TextFFN |
python | scipy__scipy | scipy/sparse/linalg/_eigen/tests/test_svds.py | {
"start": 3501,
"end": 4028
} | class ____(LinearOperator):
def __init__(self, A):
self.A = A
self.dtype = A.dtype
self.shape = A.shape
def _matvec(self, x):
assert_equal(max(x.shape), np.size(x))
return self.A.dot(x)
def _rmatvec(self, x):
assert_equal(max(x.shape), np.size(x))
re... | CheckingLinearOperator |
python | dask__distributed | distributed/pytest_resourceleaks.py | {
"start": 5397,
"end": 5935
} | class ____(ResourceChecker, name="threads"):
def measure(self) -> set[threading.Thread]:
return set(threading.enumerate())
def has_leak(
self, before: set[threading.Thread], after: set[threading.Thread]
) -> bool:
return not after <= before
def format(
self, before: set... | ActiveThreadsChecker |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 26707,
"end": 36506
} | class ____(DefinedFunction):
r"""
Harmonic numbers
The nth harmonic number is given by `\operatorname{H}_{n} =
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
More generally:
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
As `n \rightarrow \infty`, `\operatorname{... | harmonic |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 23146,
"end": 23544
} | class ____(sgqlc.types.Enum):
"""The possible GitHub Enterprise deployments where this user can
exist.
Enumeration Choices:
* `CLOUD`: The user is part of a GitHub Enterprise Cloud
deployment.
* `SERVER`: The user is part of a GitHub Enterprise Server
deployment.
"""
__schema_... | EnterpriseUserDeployment |
python | django__django | tests/template_tests/filter_tests/test_slice.py | {
"start": 843,
"end": 1738
} | class ____(SimpleTestCase):
def test_zero_length(self):
self.assertEqual(slice_filter("abcdefg", "0"), "")
def test_index(self):
self.assertEqual(slice_filter("abcdefg", "1"), "a")
def test_index_integer(self):
self.assertEqual(slice_filter("abcdefg", 1), "a")
def test_negativ... | FunctionTests |
python | tensorflow__tensorflow | tensorflow/python/data/ops/shuffle_op.py | {
"start": 1330,
"end": 2826
} | class ____(dataset_ops.UnaryUnchangedStructureDataset):
"""A `Dataset` that randomly shuffles the elements of its input."""
def __init__(
self,
input_dataset,
buffer_size,
seed=None,
reshuffle_each_iteration=True,
name=None,
):
"""See `Dataset.shuffle()` for details."""
... | _ShuffleDataset |
python | kamyu104__LeetCode-Solutions | Python/sum-of-k-mirror-numbers.py | {
"start": 1384,
"end": 2274
} | class ____(object):
def kMirror(self, k, n):
"""
:type k: int
:type n: int
:rtype: int
"""
def num_gen(k):
digits = ['0']
while True:
for i in xrange(len(digits)//2, len(digits)):
if int(digits[i])+1 < k:
... | Solution2 |
python | ray-project__ray | python/ray/util/scheduling_strategies.py | {
"start": 5524,
"end": 7616
} | class ____:
"""
Label based node affinity scheduling strategy
scheduling_strategy=NodeLabelSchedulingStrategy({
"region": In("us"),
"gpu_type": Exists(),
})
"""
def __init__(
self, hard: LabelMatchExpressionsT, *, soft: LabelMatchExpressionsT = None
):
self.... | NodeLabelSchedulingStrategy |
python | pennersr__django-allauth | allauth/account/migrations/0005_emailaddress_idx_upper_email.py | {
"start": 131,
"end": 530
} | class ____(migrations.Migration):
dependencies = [
("account", "0004_alter_emailaddress_drop_unique_email"),
]
operations = [
migrations.AddIndex(
model_name="emailaddress",
index=models.Index(
django.db.models.functions.text.Upper("email"),
... | Migration |
python | scipy__scipy | scipy/optimize/tests/test__shgo.py | {
"start": 12054,
"end": 15915
} | class ____:
"""
Global optimisation tests with Simplicial sampling:
"""
def test_f1_1_simplicial(self):
"""Multivariate test function 1:
x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
run_test(test1_1, n=1, sampling_method='simplicial')
def test_f1_2_simplicial(self):
... | TestShgoSimplicialTestFunctions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.