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 | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 6870,
"end": 7537
} | class ____:
additional_fields = additional_fields.raw_data
def request_params(
self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None
) -> MutableMapping[str, Any]:
params = super().request_params(stream_state, stream_slice, ... | RawDataMixin |
python | skorch-dev__skorch | skorch/tests/test_setter.py | {
"start": 90,
"end": 2493
} | class ____:
@pytest.fixture
def net_dummy(self):
from skorch import NeuralNet
net = Mock(spec=NeuralNet)
net.lr = 0.01
return net
@pytest.fixture
def optimizer_dummy(self):
from torch.optim import Optimizer
optim = Mock(spec=Optimizer)
optim.para... | TestOptimizerSetter |
python | mahmoud__glom | glom/core.py | {
"start": 67649,
"end": 84137
} | class ____:
'''
responsible for registration of target types for iteration
and attribute walking
'''
def __init__(self, register_default_types=True):
self._op_type_map = {}
self._op_type_tree = {} # see _register_fuzzy_type for details
self._type_cache = {}
self._op... | TargetRegistry |
python | joblib__joblib | examples/parallel_generator.py | {
"start": 1596,
"end": 11033
} | class ____(Thread):
"""Monitor the memory usage in MB in a separate thread.
Note that this class is good enough to highlight the memory profile of
Parallel in this example, but is not a general purpose profiler fit for
all cases.
"""
def __init__(self):
super().__init__()
self.... | MemoryMonitor |
python | PrefectHQ__prefect | src/prefect/events/schemas/deployment_triggers.py | {
"start": 2626,
"end": 2842
} | class ____(BaseDeploymentTrigger, MetricTrigger):
"""
A trigger that fires based on the results of a metric query.
"""
trigger_type: ClassVar[Type[TriggerTypes]] = MetricTrigger
| DeploymentMetricTrigger |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 9154,
"end": 12652
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | BertCrossAttention |
python | astropy__astropy | astropy/coordinates/baseframe.py | {
"start": 91942,
"end": 93042
} | class ____(BaseCoordinateFrame):
"""
A frame object that can't store data but can hold any arbitrary frame
attributes. Mostly useful as a utility for the high-level class to store
intermediate frame attributes.
Parameters
----------
frame_attrs : dict
A dictionary of attributes to b... | GenericFrame |
python | arrow-py__arrow | tests/test_arrow.py | {
"start": 55282,
"end": 68624
} | class ____:
def test_span_attribute(self):
with pytest.raises(ValueError):
self.arrow.span("span")
def test_span_year(self):
floor, ceil = self.arrow.span("year")
assert floor == datetime(2013, 1, 1, tzinfo=tz.tzutc())
assert ceil == datetime(2013, 12, 31, 23, 59, 5... | TestArrowSpan |
python | numba__numba | numba/core/byteflow.py | {
"start": 69087,
"end": 78250
} | class ____(object):
"""State of the trace
"""
def __init__(self, bytecode, pc, nstack, blockstack, nullvals=()):
"""
Parameters
----------
bytecode : numba.bytecode.ByteCode
function bytecode
pc : int
program counter
nstack : int
... | _State |
python | kamyu104__LeetCode-Solutions | Python/number-of-pairs-satisfying-inequality.py | {
"start": 121,
"end": 586
} | class ____(object):
def numberOfPairs(self, nums1, nums2, diff):
"""
:type nums1: List[int]
:type nums2: List[int]
:type diff: int
:rtype: int
"""
sl = SortedList()
result = 0
for x, y in itertools.izip(nums1, nums2):
result += sl.b... | Solution |
python | getsentry__responses | responses/__init__.py | {
"start": 10650,
"end": 17166
} | class ____:
passthrough: bool = False
content_type: Optional[str] = None
headers: Optional[Mapping[str, str]] = None
stream: Optional[bool] = False
def __init__(
self,
method: str,
url: "_URLPatternType",
match_querystring: Union[bool, object] = None,
match: ... | BaseResponse |
python | dask__distributed | distributed/worker.py | {
"start": 4887,
"end": 4947
} | class ____(TypedDict):
status: Literal["busy"]
| GetDataBusy |
python | scrapy__scrapy | tests/test_contracts.py | {
"start": 16782,
"end": 16955
} | class ____(Contract):
name = "test_contract"
def post_process(self, response):
raise KeyboardInterrupt("Post-process exception")
| CustomFailContractPostProcess |
python | anthropics__anthropic-sdk-python | src/anthropic/types/tool_use_block_param.py | {
"start": 322,
"end": 623
} | class ____(TypedDict, total=False):
id: Required[str]
input: Required[Dict[str, object]]
name: Required[str]
type: Required[Literal["tool_use"]]
cache_control: Optional[CacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
| ToolUseBlockParam |
python | getsentry__sentry | src/sentry/flags/providers.py | {
"start": 2159,
"end": 2851
} | class ____(Exception):
"""An unsupported provider type was specified."""
...
def get_provider(
organization_id: int, provider_name: str, headers: HttpHeaders
) -> ProviderProtocol[dict[str, Any]] | None:
match provider_name:
case "launchdarkly":
return LaunchDarklyProvider(organiz... | InvalidProvider |
python | donnemartin__interactive-coding-challenges | graphs_trees/graph/graph.py | {
"start": 139,
"end": 1148
} | class ____:
def __init__(self, key):
self.key = key
self.visit_state = State.unvisited
self.incoming_edges = 0
self.adj_nodes = {} # Key = key, val = Node
self.adj_weights = {} # Key = key, val = weight
def __repr__(self):
return str(self.key)
def __lt__(... | Node |
python | django__django | tests/servers/test_basehttp.py | {
"start": 8044,
"end": 9217
} | class ____(SimpleTestCase):
request_factory = RequestFactory()
def test_broken_pipe_errors(self):
"""WSGIServer handles broken pipe errors."""
request = WSGIRequest(self.request_factory.get("/").environ)
client_address = ("192.168.2.0", 8080)
msg = f"- Broken pipe from {client_a... | WSGIServerTestCase |
python | scipy__scipy | scipy/stats/tests/test_resampling.py | {
"start": 92213,
"end": 92510
} | class ____:
def test_rvs_and_random_state(self):
message = "Use of `rvs` and `rng` are mutually exclusive."
rng = np.random.default_rng(34982345)
with pytest.raises(ValueError, match=message):
stats.MonteCarloMethod(rvs=rng.random, rng=rng)
| TestMonteCarloMethod |
python | patrys__httmock | tests.py | {
"start": 4497,
"end": 4918
} | class ____(unittest.TestCase):
@with_httmock(any_mock)
def test_decorator(self):
r = requests.get('http://example.com/')
self.assertEqual(r.content, b'Hello from example.com')
@with_httmock(any_mock)
def test_iter_lines(self):
r = requests.get('http://example.com/')
sel... | DecoratorTest |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_compat.py | {
"start": 3772,
"end": 3915
} | class ____:
msg: str
def test_add_note_fails_gracefully_on_frozen_instance():
add_note(ImmutableError("msg"), "some note")
| ImmutableError |
python | kamyu104__LeetCode-Solutions | Python/reverse-words-in-a-string-ii.py | {
"start": 27,
"end": 532
} | class ____(object):
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
def reverse(s, begin, end):
for i in xrange((end - begin) / 2):
s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]
... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_build.py | {
"start": 12163,
"end": 16022
} | class ____(GoogleCloudBaseOperator):
"""
Creates a new BuildTrigger.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudBuildCreateBuildTriggerOperator`
:param trigger: The BuildTrigger to create. If a dict is provided, it... | CloudBuildCreateBuildTriggerOperator |
python | django__django | tests/middleware_exceptions/middleware.py | {
"start": 2307,
"end": 2534
} | class ____(BaseMiddleware):
def process_template_response(self, request, response):
response.context_data["mw"].append(self.__class__.__name__)
return response
@async_only_middleware
| TemplateResponseMiddleware |
python | fluentpython__example-code-2e | 02-array-seq/lispy/py3.10/lis.py | {
"start": 5557,
"end": 6576
} | class ____:
"A user-defined Scheme procedure."
def __init__( # <1>
self, parms: list[Symbol], body: list[Expression], env: Environment
):
self.parms = parms # <2>
self.body = body
self.env = env
def __call__(self, *args: Expression) -> Any: # <3>
local_env = ... | Procedure |
python | scrapy__scrapy | tests/test_contracts.py | {
"start": 1154,
"end": 1355
} | class ____(Contract):
name = "custom_form"
request_cls = FormRequest
def adjust_request_args(self, args):
args["formdata"] = {"name": "scrapy"}
return args
| CustomFormContract |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 3531,
"end": 3600
} | class ____(PydanticErrorMixin, ValueError):
pass
| PydanticValueError |
python | wireservice__csvkit | csvkit/utilities/csvgrep.py | {
"start": 171,
"end": 3554
} | class ____(CSVKitUtility):
description = 'Search CSV files. Like the Unix "grep" command, but for tabular data.'
override_flags = ['L', 'I']
def add_arguments(self):
self.argparser.add_argument(
'-n', '--names', dest='names_only', action='store_true',
help='Display column na... | CSVGrep |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format04.py | {
"start": 345,
"end": 2938
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | python__mypy | mypy/plugin.py | {
"start": 8476,
"end": 8717
} | class ____(NamedTuple):
type: UnboundType # Type to analyze
context: Context # Relevant location context (e.g. for error messages)
api: TypeAnalyzerPluginInterface
@mypyc_attr(allow_interpreted_subclasses=True)
| AnalyzeTypeContext |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_trace_metrics.py | {
"start": 192,
"end": 15431
} | class ____(OrganizationEventsEndpointTestBase):
dataset = "tracemetrics"
def test_simple_with_explicit_filter(self) -> None:
trace_metrics = [
self.create_trace_metric("foo", 1, "counter"),
self.create_trace_metric("bar", 2, "counter"),
]
self.store_trace_metrics... | OrganizationEventsTraceMetricsEndpointTest |
python | pytorch__pytorch | test/test_functional_optim.py | {
"start": 2581,
"end": 6358
} | class ____(TestCase):
def _validate_parameters(self, params_1, params_2):
for p1, p2 in zip(params_1, params_2):
self.assertEqual(p1, p2)
# Dynamo fails at compiling this for python 3.8/3.11
# Since it passes while compiling the actual code under test
# we disable dynamo here.
@... | TestFunctionalOptimParity |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 74779,
"end": 75057
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('value', c_uint),
]
def __init__(self):
super(c_nvmlDeviceAddressingMode_t, self).__init__(version=nvmlDeviceAddressingMode_v1)
## Event structures
| c_nvmlDeviceAddressingMode_t |
python | walkccc__LeetCode | solutions/663. Equal Tree Partition/663.py | {
"start": 0,
"end": 409
} | class ____:
def checkEqualTree(self, root: TreeNode | None) -> bool:
if not root:
return False
seen = set()
def dfs(root: TreeNode | None) -> int:
if not root:
return 0
summ = root.val + dfs(root.left) + dfs(root.right)
seen.add(summ)
return summ
summ = root.v... | Solution |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 187636,
"end": 192894
} | class ____(SocketConnectedTest):
"""Unit tests for the object returned by socket.makefile()
self.read_file is the io object returned by makefile() on
the client connection. You can read from this file to
get output from the server.
self.write_file is the io object returned by makefile() on the
... | FileObjectClassTestCase |
python | davidhalter__jedi | jedi/api/classes.py | {
"start": 27437,
"end": 28585
} | class ____(BaseSignature):
"""
A full signature object is the return value of
:meth:`.Script.get_signatures`.
"""
def __init__(self, inference_state, signature, call_details):
super().__init__(inference_state, signature)
self._call_details = call_details
self._signature = sig... | Signature |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass2.py | {
"start": 234,
"end": 313
} | class ____(InterfaceA):
def a(self) -> None:
print("MixinA.a")
| MixinA |
python | numpy__numpy | numpy/tests/test_configtool.py | {
"start": 559,
"end": 1812
} | class ____:
def check_numpyconfig(self, arg):
p = subprocess.run(['numpy-config', arg], capture_output=True, text=True)
p.check_returncode()
return p.stdout.strip()
def test_configtool_version(self):
stdout = self.check_numpyconfig('--version')
assert stdout == np.__vers... | TestNumpyConfig |
python | ansible__ansible | lib/ansible/modules/package_facts.py | {
"start": 12714,
"end": 13350
} | class ____(CLIMgr):
CLI = 'apk'
def list_installed(self):
rc, out, err = module.run_command([self._cli, 'info', '-v'])
if rc != 0:
raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
return out.splitlines()
def get_package_details(self, package):
... | APK |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 5875,
"end": 7032
} | class ____(Action):
"""Base class for Actions that operate on Work Queues and need to infer them from
events"""
source: Literal["selected", "inferred"] = Field(
"selected",
description=(
"Whether this Action applies to a specific selected "
"work queue (given by `wor... | WorkQueueAction |
python | numba__numba | numba/tests/test_typingerror.py | {
"start": 6666,
"end": 7235
} | class ____(unittest.TestCase):
def test_readonly_array(self):
@jit("(f8[:],)", nopython=True)
def inner(x):
return x
@jit(nopython=True)
def outer():
return inner(gvalues)
gvalues = np.ones(10, dtype=np.float64)
with self.assertRaises(Typing... | TestCallError |
python | pytest-dev__pytest-rerunfailures | src/pytest_rerunfailures.py | {
"start": 14183,
"end": 15466
} | class ____(SocketDB):
def __init__(self):
super().__init__()
self.sock.bind(("127.0.0.1", 0))
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.rerunfailures_db = {}
t = threading.Thread(target=self.run_server, daemon=True)
t.start()
@property... | ServerStatusDB |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 36231,
"end": 43361
} | class ____(T5PreTrainedModel):
_keys_to_ignore_on_load_unexpected = [
"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
]
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __in... | T5Model |
python | bottlepy__bottle | bottle.py | {
"start": 8465,
"end": 17214
} | class ____:
""" A Router is an ordered collection of route->target pairs. It is used to
efficiently match WSGI requests against a number of routes and return
the first target that satisfies the request. The target may be anything,
usually a string, ID or callable object. A route consists of ... | Router |
python | spack__spack | lib/spack/spack/stage.py | {
"start": 48244,
"end": 48352
} | class ____(spack.error.SpackError):
"""Superclass for all errors encountered during staging."""
| StageError |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 12492,
"end": 15025
} | class ____(CheckTestCase):
def test_not_iterable(self):
class TestModelAdmin(ModelAdmin):
filter_horizontal = 10
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'filter_horizontal' must be a list or tuple.",
"admin... | FilterHorizontalCheckTests |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py | {
"start": 23913,
"end": 36419
} | class ____:
@pytest.fixture(autouse=True)
def setup_attrs(self) -> None:
self.default_time = DEFAULT_DATETIME_1
self.ti_init = {
"logical_date": self.default_time,
"state": State.RUNNING,
}
self.ti_extras = {
"start_date": self.default_time + d... | TestGetMappedTaskInstances |
python | pandas-dev__pandas | pandas/core/arrays/datetimes.py | {
"start": 4051,
"end": 100299
} | class ____(dtl.TimelikeOps, dtl.DatelikeOps):
"""
Pandas ExtensionArray for tz-naive or tz-aware datetime data.
.. warning::
DatetimeArray is currently experimental, and its API may change
without warning. In particular, :attr:`DatetimeArray.dtype` is
expected to change to always be a... | DatetimeArray |
python | catalyst-team__catalyst | catalyst/settings.py | {
"start": 3501,
"end": 10370
} | class ____(FrozenClass):
"""Catalyst settings."""
def __init__( # noqa: D107
self,
# [subpackages]
cv_required: Optional[bool] = None,
ml_required: Optional[bool] = None,
# [integrations]
optuna_required: Optional[bool] = None,
# [dl-extras]
onnx... | Settings |
python | ipython__ipython | IPython/lib/pretty.py | {
"start": 17415,
"end": 18664
} | class ____:
""" Object which emits a line-wrapped call expression in the form `__name(*args, **kwargs)` """
def __init__(__self, __name, *args, **kwargs):
# dunders are to avoid clashes with kwargs, as python's name managing
# will kick in.
self = __self
self.name = __name
... | CallExpression |
python | pandas-dev__pandas | asv_bench/benchmarks/reshape.py | {
"start": 1120,
"end": 1514
} | class ____:
def setup(self):
arrays = [np.arange(100).repeat(100), np.roll(np.tile(np.arange(100), 100), 25)]
index = MultiIndex.from_arrays(arrays)
self.df = DataFrame(np.random.randn(10000, 4), index=index)
self.udf = self.df.unstack(1)
def time_stack(self):
self.udf.s... | SimpleReshape |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/looker/customize_upstream_dependencies.py | {
"start": 409,
"end": 1292
} | class ____(DagsterLookerApiTranslator):
def get_asset_spec(
self, looker_structure: LookerApiTranslatorStructureData
) -> dg.AssetSpec:
# We create the default asset spec using super()
default_spec = super().get_asset_spec(looker_structure)
# We customize upstream dependencies fo... | CustomDagsterLookerApiTranslator |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/registry.py | {
"start": 1393,
"end": 14730
} | class ____(json.JSONDecoder):
"""A JSON decoder that converts "null" strings to None."""
def __init__(self, *args, **kwargs):
super().__init__(object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
return {k: (None if v == "null" else v) for k, v in obj.items()}
def _... | StringNullJsonDecoder |
python | spack__spack | share/spack/qa/flake8_formatter.py | {
"start": 1439,
"end": 4173
} | class ____(Pylint):
def __init__(self, options):
self.spack_errors = {}
self.error_seen = False
super().__init__(options)
def after_init(self) -> None:
"""Overriding to keep format string from being unset in Default"""
pass
def beginning(self, filename):
sel... | SpackFormatter |
python | huggingface__transformers | tests/models/hiera/test_modeling_hiera.py | {
"start": 26112,
"end": 26354
} | class ____(unittest.TestCase, BackboneTesterMixin):
all_model_classes = (HieraBackbone,) if is_torch_available() else ()
config_class = HieraConfig
def setUp(self):
self.model_tester = HieraModelTester(self)
| HieraBackboneTest |
python | TheAlgorithms__Python | ciphers/onepad_cipher.py | {
"start": 16,
"end": 1855
} | class ____:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
"""
Function to encrypt text using pseudo-random numbers
>>> Onepad().encrypt("")
([], [])
>>> Onepad().encrypt([])
([], [])
>>> random.seed(1)
>>> Onepad().encrypt(" ... | Onepad |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1229876,
"end": 1230141
} | class ____(sgqlc.types.Type, Node, AuditEntry, EnterpriseAuditEntryData, OrganizationAuditEntryData):
"""Audit log entry for a members_can_delete_repos.enable event."""
__schema__ = github_schema
__field_names__ = ()
| MembersCanDeleteReposEnableAuditEntry |
python | ray-project__ray | python/ray/train/v2/_internal/exceptions.py | {
"start": 3294,
"end": 3773
} | class ____(RayTrainError):
"""Exception raised when the checkpoint manager fails to initialize from a snapshot.
Example scenarios:
1. The checkpoint manager snapshot version is old and
incompatible with the current version of Ray Train.
2. The checkpoint manager snapshot JSON file is corrupted.... | CheckpointManagerInitializationError |
python | pandas-dev__pandas | asv_bench/benchmarks/array.py | {
"start": 1331,
"end": 1537
} | class ____:
def setup(self):
N = 10_000
self.tuples = [(i, i + 1) for i in range(N)]
def time_from_tuples(self):
pd.arrays.IntervalArray.from_tuples(self.tuples)
| IntervalArray |
python | tensorflow__tensorflow | tensorflow/lite/tools/flatbuffer_utils_test.py | {
"start": 3233,
"end": 5407
} | class ____(test_util.TensorFlowTestCase):
def testStripStrings(self):
# 1. SETUP
# Define the initial model
initial_model = test_utils.build_mock_model()
final_model = copy.deepcopy(initial_model)
# 2. INVOKE
# Invoke the strip_strings function
flatbuffer_utils.strip_strings(final_model)... | StripStringsTest |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_object/query/async_.py | {
"start": 312,
"end": 461
} | class ____(
Generic[Properties, References],
_NearObjectQueryExecutor[ConnectionAsync, Properties, References],
):
pass
| _NearObjectQueryAsync |
python | ray-project__ray | doc/source/ray-overview/examples/e2e-multimodal-ai-workloads/doggos/doggos/embed.py | {
"start": 265,
"end": 3427
} | class ____(object):
def __init__(self, model_id, device):
# Load CLIP model and processor
self.processor = CLIPProcessor.from_pretrained(model_id)
self.model = CLIPModel.from_pretrained(model_id)
self.model.to(device)
self.device = device
def __call__(self, batch):
... | EmbedImages |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 87208,
"end": 88074
} | class ____(Response):
"""
Response of tasks.clone endpoint.
:param id: ID of the new task
:type id: str
"""
_service = "tasks"
_action = "clone"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"id": {"description": "ID of the new task", "type": ["stri... | CloneResponse |
python | automl__auto-sklearn | test/test_pipeline/components/feature_preprocessing/test_NoPreprocessing.py | {
"start": 211,
"end": 1025
} | class ____(PreprocessingTestCase):
def test_default_configuration(self):
transformation, original = _test_preprocessing(NoPreprocessing)
self.assertEqual(transformation.shape[0], original.shape[0])
self.assertEqual(transformation.shape[1], original.shape[1])
self.assertFalse((transfo... | NoneComponentTest |
python | django__django | tests/model_fields/models.py | {
"start": 1985,
"end": 2925
} | class ____(models.Model):
class Suit(models.IntegerChoices):
DIAMOND = 1, "Diamond"
SPADE = 2, "Spade"
HEART = 3, "Heart"
CLUB = 4, "Club"
def get_choices():
return [(i, str(i)) for i in range(3)]
no_choices = models.IntegerField(null=True)
empty_choices = model... | Choiceful |
python | django__django | tests/admin_views/admin.py | {
"start": 13270,
"end": 13334
} | class ____(admin.StackedInline):
model = Grommet
| GrommetInline |
python | wandb__wandb | wandb/vendor/pygments/lexers/trafficscript.py | {
"start": 430,
"end": 1546
} | class ____(RegexLexer):
"""
For `Riverbed Stingray Traffic Manager <http://www.riverbed.com/stingray>`_
.. versionadded:: 2.1
"""
name = 'TrafficScript'
aliases = ['rts','trafficscript']
filenames = ['*.rts']
tokens = {
'root' : [
(r"'(\\\\|\\[^\\]|[^'\\])*'", Strin... | RtsLexer |
python | numba__numba | numba/tests/cfunc_cache_usecases.py | {
"start": 715,
"end": 1608
} | class ____(TestCase):
"""
Tests for functionality of this module's cfuncs.
Note this does not define any "test_*" method, instead check_module()
should be called by hand.
"""
def check_module(self, mod):
f = mod.add_usecase
self.assertPreciseEqual(f.ctypes(2.0, 3.0), 6.0)
... | _TestModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1585542,
"end": 1585734
} | class ____(sgqlc.types.Union):
"""Types which can be actors for `BranchActorAllowance` objects."""
__schema__ = github_schema
__types__ = (App, Team, User)
| BranchActorAllowanceActor |
python | huggingface__transformers | src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py | {
"start": 64579,
"end": 72073
} | class ____(GraniteMoeHybridPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: GraniteMoeHybridConfig):
super().__init__(c... | GraniteMoeHybridForCausalLM |
python | MongoEngine__mongoengine | tests/fields/test_map_field.py | {
"start": 100,
"end": 4155
} | class ____(MongoDBTestCase):
def test_mapfield(self):
"""Ensure that the MapField handles the declared type."""
class Simple(Document):
mapping = MapField(IntField())
Simple.drop_collection()
e = Simple()
e.mapping["someint"] = 1
e.save()
with ... | TestMapField |
python | PyCQA__pylint | pylint/checkers/base/name_checker/naming_style.py | {
"start": 2896,
"end": 3318
} | class ____(NamingStyle):
"""Regex rules for UPPER_CASE naming style."""
CLASS_NAME_RGX = re.compile(r"[^\W\da-z][^\Wa-z]*$")
MOD_NAME_RGX = CLASS_NAME_RGX
CONST_NAME_RGX = re.compile(r"([^\W\da-z][^\Wa-z]*|__.*__)$")
COMP_VAR_RGX = CLASS_NAME_RGX
DEFAULT_NAME_RGX = re.compile(r"([^\W\da-z][^\Wa... | UpperCaseStyle |
python | pytorch__pytorch | test/onnx/exporter/test_verification.py | {
"start": 235,
"end": 3305
} | class ____(common_utils.TestCase):
def test_from_tensors(self):
# Test with tensors
expected = torch.tensor([1.0, 2.0, 3.0])
actual = torch.tensor([1.0, 2.0, 3.0])
verification_info = _verification.VerificationInfo.from_tensors(
"test_tensor", expected, actual
)
... | VerificationInfoTest |
python | mlflow__mlflow | examples/llama_index/workflow/workflow/events.py | {
"start": 573,
"end": 785
} | class ____(Event):
"""Event to send retrieval result from each retriever to the gather step."""
nodes: list[NodeWithScore]
retriever: Literal["vector_search", "bm25", "web_search"]
| RetrievalResultEvent |
python | pandas-dev__pandas | asv_bench/benchmarks/rolling.py | {
"start": 1055,
"end": 1631
} | class ____:
params = (
["DataFrame", "Series"],
[3, 300],
["int", "float"],
[sum, np.sum, lambda x: np.sum(x) + 5],
[True, False],
)
param_names = ["constructor", "window", "dtype", "function", "raw"]
def setup(self, constructor, window, dtype, function, raw):
... | Apply |
python | huggingface__transformers | src/transformers/models/blenderbot/modeling_blenderbot.py | {
"start": 10711,
"end": 13541
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: BlenderbotConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = BlenderbotAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
dropout=conf... | BlenderbotEncoderLayer |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 1262,
"end": 1433
} | class ____(AuthException):
"""Auth process was canceled by user."""
def __str__(self) -> str:
return gettext("Authentication process canceled")
| AuthCanceled |
python | kamyu104__LeetCode-Solutions | Python/check-if-one-string-swap-can-make-strings-equal.py | {
"start": 48,
"end": 492
} | class ____(object):
def areAlmostEqual(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
diff = []
for a, b in itertools.izip(s1, s2):
if a == b:
continue
if len(diff) == 2:
return False
... | Solution |
python | pandas-dev__pandas | pandas/tests/series/test_formats.py | {
"start": 8878,
"end": 17404
} | class ____:
def test_categorical_repr_unicode(self):
# see gh-21002
class County:
name = "San Sebastián"
state = "PR"
def __repr__(self) -> str:
return self.name + ", " + self.state
cat = Categorical([County() for _ in range(61)])
... | TestCategoricalRepr |
python | walkccc__LeetCode | solutions/250. Count Univalue Subtrees/250.py | {
"start": 0,
"end": 396
} | class ____:
def countUnivalSubtrees(self, root: TreeNode | None) -> int:
ans = 0
def isUnival(root: TreeNode | None, val: int) -> bool:
nonlocal ans
if not root:
return True
if isUnival(root.left, root.val) & isUnival(root.right, root.val):
ans += 1
return root.val ... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/bincount_ops_test.py | {
"start": 13785,
"end": 18895
} | class ____(test.TestCase, parameterized.TestCase):
def testSparseCountSparseOutputBadIndicesShape(self):
indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]]
values = [1, 1, 1, 10]
weights = [1, 2, 4, 6]
dense_shape = [2, 3]
with self.assertRaisesRegex(errors.InvalidArgumentError,
... | RawOpsTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_domains.py | {
"start": 417,
"end": 1255
} | class ____(TestCase):
def setUp(self):
self.project = get(Project, slug="kong")
def test_save_parsing(self):
domain = get(Domain, domain="google.com")
self.assertEqual(domain.domain, "google.com")
domain.domain = "google.com"
self.assertEqual(domain.domain, "google.com"... | ModelTests |
python | doocs__leetcode | solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/Solution.py | {
"start": 0,
"end": 481
} | class ____:
def minimumOperationsToMakeEqual(self, x: int, y: int) -> int:
@cache
def dfs(x: int) -> int:
if y >= x:
return y - x
ans = x - y
ans = min(ans, x % 5 + 1 + dfs(x // 5))
ans = min(ans, 5 - x % 5 + 1 + dfs(x // 5 + 1))
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/batch_norm_benchmark.py | {
"start": 4473,
"end": 10657
} | class ____(test.Benchmark):
"""Benchmark batch normalization."""
def _run_graph(self, device, input_shape, axes, num_layers, mode, scale,
train, num_iters):
"""Run the graph and print its execution time.
Args:
device: string, the device to run on.
input_shape: shape of the inp... | BatchNormBenchmark |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/launchers/multiprocessing.py | {
"start": 1829,
"end": 12575
} | class ____(_Launcher):
r"""Launches processes that run a given function in parallel, and joins them all at the end.
The main process in which this launcher is invoked creates N so-called worker processes (using
:func:`torch.multiprocessing.start_processes`) that run the given function.
Worker processes... | _MultiProcessingLauncher |
python | huggingface__transformers | tests/models/flava/test_modeling_flava.py | {
"start": 42001,
"end": 43184
} | class ____(FlavaModelTest):
all_model_classes = (FlavaForPreTraining,) if is_torch_available() else ()
class_for_tester = FlavaForPreTrainingTester
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull... | FlavaForPreTrainingTest |
python | pyca__cryptography | src/cryptography/hazmat/primitives/_asymmetric.py | {
"start": 335,
"end": 532
} | class ____(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def name(self) -> str:
"""
A string naming this padding (e.g. "PSS", "PKCS1").
"""
| AsymmetricPadding |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 538364,
"end": 538788
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""... | CreateIssuePayload |
python | falconry__falcon | tests/test_after_hooks.py | {
"start": 2590,
"end": 3011
} | class ____:
@falcon.after(serialize_body)
@falcon.after(validate_output)
def on_get(self, req, resp):
self.req = req
self.resp = resp
@falcon.after(serialize_body)
def on_put(self, req, resp):
self.req = req
self.resp = resp
resp.text = {'animal': 'falcon'}
... | WrappedRespondersResource |
python | numba__numba | numba/core/callconv.py | {
"start": 36072,
"end": 36473
} | class ____(object):
def __init__(self, call_conv):
self.call_conv = call_conv
def fp_zero_division(self, builder, exc_args=None, loc=None):
if self.raise_on_fp_zero_division:
self.call_conv.return_user_exc(builder, ZeroDivisionError, exc_args,
... | ErrorModel |
python | encode__django-rest-framework | rest_framework/utils/serializer_helpers.py | {
"start": 156,
"end": 1329
} | class ____(dict):
"""
Return object from `serializer.data` for the `Serializer` class.
Includes a backlink to the serializer instance for renderers
to use if they need richer field information.
"""
def __init__(self, *args, **kwargs):
self.serializer = kwargs.pop('serializer')
s... | ReturnDict |
python | Netflix__metaflow | metaflow/_vendor/importlib_metadata/__init__.py | {
"start": 9704,
"end": 10900
} | class ____:
"""
Compatibility add-in for mapping to indicate that
mapping behavior is deprecated.
>>> recwarn = getfixture('recwarn')
>>> class DeprecatedDict(Deprecated, dict): pass
>>> dd = DeprecatedDict(foo='bar')
>>> dd.get('baz', None)
>>> dd['foo']
'bar'
>>> list(dd)
... | Deprecated |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 23481,
"end": 24656
} | class ____(TestHttp11Base):
is_secure = True
tls_log_message = (
'SSL connection certificate: issuer "/C=IE/O=Scrapy/CN=localhost", '
'subject "/C=IE/O=Scrapy/CN=localhost"'
)
@deferred_f_from_coro_f
async def test_tls_logging(self, mockserver: MockServer) -> None:
crawler ... | TestHttps11Base |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 13716,
"end": 13848
} | class ____(nodes.Element):
"""Node for "only" directives (conditional inclusion based on tags)."""
# meta-information nodes
| only |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/aug_mix.py | {
"start": 846,
"end": 11221
} | class ____(BaseImagePreprocessingLayer):
"""Performs the AugMix data augmentation technique.
AugMix aims to produce images with variety while preserving the image
semantics and local statistics. During the augmentation process,
the same augmentation is applied across all images in the batch
in num_... | AugMix |
python | tiangolo__fastapi | docs_src/security/tutorial005_an.py | {
"start": 1541,
"end": 5498
} | class ____(User):
hashed_password: str
password_hash = PasswordHash.recommended()
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"me": "Read information about the current user.", "items": "Read items."},
)
app = FastAPI()
def verify_password(plain_password, hashed_password):
retur... | UserInDB |
python | PyCQA__pyflakes | pyflakes/test/test_imports.py | {
"start": 28250,
"end": 33939
} | class ____(TestCase):
"""
Tests for suppression of unused import warnings by C{__all__}.
"""
def test_ignoredInFunction(self):
"""
An C{__all__} definition does not suppress unused import warnings in a
function scope.
"""
self.flakes('''
def foo():
... | TestSpecialAll |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/jobs_with_config_mapping.py | {
"start": 291,
"end": 807
} | class ____(Config):
simplified_param: str
@config_mapping
def simplified_config(val: SimplifiedConfig) -> RunConfig:
return RunConfig(
ops={"do_something": DoSomethingConfig(config_param=val.simplified_param)}
)
@job(config=simplified_config)
def do_it_all_with_simplified_config():
do_someth... | SimplifiedConfig |
python | getsentry__sentry | src/sentry/core/endpoints/project_details.py | {
"start": 18469,
"end": 18822
} | class ____(ProjectPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin"],
"POST": ["project:write", "project:admin"],
# PUT checks for permissions based on fields
"PUT": ["project:read", "project:write", "project:admin"],
"DELETE": ["project:admi... | RelaxedProjectPermission |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 15190,
"end": 17742
} | class ____(unittest.TestCase):
src = "en"
tgt = "de"
src_text = [
"I am a small frog.",
"Now I can forget the 100 words of german that I know.",
"Tom asked his teacher for advice.",
"That's how I would do it.",
"Tom really admired Mary's courage.",
"Turn aroun... | MarianIntegrationTest |
python | mlflow__mlflow | mlflow/types/schema.py | {
"start": 25286,
"end": 26737
} | class ____(BaseType):
def __init__(self):
"""
AnyType can store any json-serializable data including None values.
For example:
.. code-block::python
from mlflow.types.schema import AnyType, Schema, ColSpec
schema = Schema([ColSpec(type=AnyType(), name="id")... | AnyType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.