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 | google__pytype | pytype/blocks/blocks.py | {
"start": 1185,
"end": 2536
} | class ____:
"""A block is a node in a directed graph.
It has incoming and outgoing edges (jumps). Incoming jumps always jump
to the first instruction of our bytecode, and outgoing jumps always jump
from the last instruction. There are no jump instructions in the middle of
a byte code block.
A block impleme... | Block |
python | py-pdf__pypdf | pypdf/_protocols.py | {
"start": 885,
"end": 945
} | class ____(PdfObjectProtocol):
pass
| XmpInformationProtocol |
python | pytorch__pytorch | torch/distributed/rpc/rref_proxy.py | {
"start": 2380,
"end": 2705
} | class ____:
def __init__(self, rref, rpc_api, timeout=UNSET_RPC_TIMEOUT):
self.rref = rref
self.rpc_api = rpc_api
self.rpc_timeout = timeout
def __getattr__(self, func_name):
return partial(
_invoke_rpc, self.rref, self.rpc_api, func_name, self.rpc_timeout
)
| RRefProxy |
python | realpython__materials | python-protocol/shapes_v1.py | {
"start": 216,
"end": 452
} | class ____(Shape):
def __init__(self, radius) -> None:
self.radius = radius
def get_area(self) -> float:
return pi * self.radius**2
def get_perimeter(self) -> float:
return 2 * pi * self.radius
| Circle |
python | openai__openai-python | src/openai/types/responses/tool.py | {
"start": 6227,
"end": 8222
} | class ____(BaseModel):
type: Literal["image_generation"]
"""The type of the image generation tool. Always `image_generation`."""
background: Optional[Literal["transparent", "opaque", "auto"]] = None
"""Background type for the generated image.
One of `transparent`, `opaque`, or `auto`. Default: `au... | ImageGeneration |
python | TheAlgorithms__Python | maths/matrix_exponentiation.py | {
"start": 301,
"end": 3250
} | class ____:
def __init__(self, arg):
if isinstance(arg, list): # Initializes a matrix identical to the one provided.
self.t = arg
self.n = len(arg)
else: # Initializes a square matrix of the given size and set values to zero.
self.n = arg
self.t = [[... | Matrix |
python | tiangolo__fastapi | scripts/contributors.py | {
"start": 1843,
"end": 1909
} | class ____(BaseModel):
repository: PRsRepository
| PRsResponseData |
python | walkccc__LeetCode | solutions/3216. Lexicographically Smallest String After a Swap/3216.py | {
"start": 0,
"end": 285
} | class ____:
def getSmallestString(self, s: str) -> str:
chars = list(s)
for i, (a, b) in enumerate(itertools.pairwise(chars)):
if ord(a) % 2 == ord(b) % 2 and a > b:
chars[i], chars[i + 1] = chars[i + 1], chars[i]
return ''.join(chars)
return s
| Solution |
python | facebookresearch__faiss | tests/test_partition.py | {
"start": 1086,
"end": 2444
} | class ____(unittest.TestCase, PartitionTests):
def do_partition(self, n, q, maxval=None, seed=None):
if seed is None:
for i in range(50):
self.do_partition(n, q, maxval, i + 1234)
rs = np.random.RandomState(seed)
if maxval is None:
vals = rs.rand(n).a... | TestPartitioningFloat |
python | scikit-learn__scikit-learn | sklearn/tests/test_base.py | {
"start": 26735,
"end": 34034
} | class ____(_Empty, BaseEstimator):
pass
@pytest.mark.parametrize("estimator", [BaseEstimator(), EmptyEstimator()])
def test_estimator_empty_instance_dict(estimator):
"""Check that ``__getstate__`` returns an empty ``dict`` with an empty
instance.
Python 3.11+ changed behaviour by returning ``None`` i... | EmptyEstimator |
python | openai__openai-python | src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py | {
"start": 1025,
"end": 1479
} | class ____(BaseModel):
index: int
"""The index of the tool call in the tool calls array."""
type: Literal["code_interpreter"]
"""The type of tool call.
This is always going to be `code_interpreter` for this type of tool call.
"""
id: Optional[str] = None
"""The ID of the tool call."""... | CodeInterpreterToolCallDelta |
python | modin-project__modin | modin/tests/core/storage_formats/pandas/test_internals.py | {
"start": 16902,
"end": 45185
} | class ____:
"""Test draining virtual partition call queues.
Test creating a virtual partition made of block partitions and/or one or
more layers of virtual partitions, draining the top-level partition's
call queue, and getting the result.
In all these test cases, the full_axis argument doesn't mat... | TestDrainVirtualPartitionCallQueue |
python | h5py__h5py | h5py/tests/common.py | {
"start": 983,
"end": 9278
} | class ____(ut.TestCase):
"""
Base class for unit tests.
"""
@classmethod
def setUpClass(cls):
cls.tempdir = tempfile.mkdtemp(prefix='h5py-test_')
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tempdir)
def mktemp(self, suffix='.hdf5', prefix='tmp', dir=Non... | TestCase |
python | django__django | django/db/models/fields/json.py | {
"start": 23465,
"end": 23551
} | class ____(KeyTransformTextLookupMixin, lookups.EndsWith):
pass
| KeyTransformEndsWith |
python | mlflow__mlflow | mlflow/server/jobs/__init__.py | {
"start": 679,
"end": 1010
} | class ____(RuntimeError):
"""
Raise `TransientError` in a job to trigger job retry
"""
def __init__(self, origin_error: Exception):
super().__init__()
self._origin_error = origin_error
@property
def origin_error(self) -> Exception:
return self._origin_error
@dataclass... | TransientError |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-robots-within-budget.py | {
"start": 93,
"end": 923
} | class ____(object):
def maximumRobots(self, chargeTimes, runningCosts, budget):
"""
:type chargeTimes: List[int]
:type runningCosts: List[int]
:type budget: int
:rtype: int
"""
result = left = curr = 0
dq = collections.deque()
for right in xran... | Solution |
python | docker__docker-py | tests/unit/utils_test.py | {
"start": 15338,
"end": 15925
} | class ____(unittest.TestCase):
def test_parse_bytes_valid(self):
assert parse_bytes("512MB") == 536870912
assert parse_bytes("512M") == 536870912
assert parse_bytes("512m") == 536870912
def test_parse_bytes_invalid(self):
with pytest.raises(DockerException):
parse_by... | ParseBytesTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 2334,
"end": 2855
} | class ____(RkiCovidStream):
"""Docs: https://api.corona-zahlen.org/germany/age-groups"""
primary_key = None
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
yield response.json().get("data")
def path(
self, stream_state: Mapping[str, Any] = None, s... | GermanyAgeGroups |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 854047,
"end": 854599
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("database_id", "issue", "pinned_by", "repository")
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
issue = sgqlc.types.Field(sgqlc.types.non_null(Issue),... | PinnedIssue |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 1375,
"end": 1589
} | class ____:
def setup(self):
N = 1000
self.sparse = scipy.sparse.rand(N, N, 0.005)
def time_from_scipy(self):
pd.DataFrame.sparse.from_spmatrix(self.sparse)
| SparseDataFrameConstructor |
python | django-guardian__django-guardian | example_project/posts/migrations/0001_initial.py | {
"start": 43,
"end": 869
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Post",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("title", models.CharField(max_leng... | Migration |
python | google__pytype | pytype/tools/traces/source_test.py | {
"start": 187,
"end": 267
} | class ____(source.AbstractTrace):
"""Fake trace class for testing."""
| _FakeTrace |
python | getsentry__sentry | tests/sentry/api/test_paginator.py | {
"start": 6555,
"end": 15591
} | class ____(TestCase):
def test_ascending(self) -> None:
joined = timezone.now()
# The DateTime pager only has accuracy up to 1000th of a second.
# Everything can't be added within less than 10 microseconds of each
# other. This is handled by the pager (see test_rounding_offset), but... | DateTimePaginatorTest |
python | conda__conda | conda/exceptions.py | {
"start": 40321,
"end": 40531
} | class ____(CondaEnvException):
def __init__(self, msg: str, *args, **kwargs):
msg = f"Provided environment.yaml is invalid: {msg}"
super().__init__(msg, *args, **kwargs)
| EnvironmentFileInvalid |
python | pyqtgraph__pyqtgraph | pyqtgraph/multiprocess/parallelizer.py | {
"start": 9714,
"end": 12444
} | class ____(object):
def __init__(self, parallelizer, process, tasks, kwds):
self.proc = process
self.par = parallelizer
self.tasks = tasks
for k, v in kwds.items():
setattr(self, k, v)
def __iter__(self):
## we could fix this up such that tasks are re... | Tasker |
python | python-attrs__attrs | tests/test_slots.py | {
"start": 448,
"end": 923
} | class ____:
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
def my_class(self):
return _... | C1 |
python | walkccc__LeetCode | solutions/483. Smallest Good Base/483.py | {
"start": 0,
"end": 237
} | class ____:
def smallestGoodBase(self, n: str) -> str:
n = int(n)
for m in range(int(math.log(n, 2)), 1, -1):
k = int(n**m**-1)
if (k**(m + 1) - 1) // (k - 1) == n:
return str(k)
return str(n - 1)
| Solution |
python | apache__airflow | providers/neo4j/tests/unit/neo4j/hooks/test_neo4j.py | {
"start": 961,
"end": 9795
} | class ____:
@pytest.mark.parametrize(
("conn_extra", "expected_uri"),
[
({}, "bolt://host:7687"),
({"neo4j_scheme": False}, "bolt://host:7687"),
({"certs_self_signed": True, "neo4j_scheme": False}, "bolt+ssc://host:7687"),
({"certs_trusted_ca": True, "... | TestNeo4jHookConn |
python | kamyu104__LeetCode-Solutions | Python/number-of-students-doing-homework-at-a-given-time.py | {
"start": 48,
"end": 358
} | class ____(object):
def busyStudent(self, startTime, endTime, queryTime):
"""
:type startTime: List[int]
:type endTime: List[int]
:type queryTime: int
:rtype: int
"""
return sum(s <= queryTime <= e for s, e in itertools.izip(startTime, endTime))
| Solution |
python | django__django | django/db/models/functions/text.py | {
"start": 11393,
"end": 11465
} | class ____(Transform):
function = "TRIM"
lookup_name = "trim"
| Trim |
python | django__django | tests/view_tests/tests/test_static.py | {
"start": 6724,
"end": 7805
} | class ____(StaticTests):
"""
Test case to make sure the static URL pattern helper works as expected
"""
def setUp(self):
super().setUp()
self._old_views_urlpatterns = urls.urlpatterns[:]
urls.urlpatterns += static("media/", document_root=media_dir)
def tearDown(self):
... | StaticHelperTest |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 11836,
"end": 13081
} | class ____:
def __init__(
self, access_method: ObjectIdentifier, access_location: GeneralName
) -> None:
if not isinstance(access_method, ObjectIdentifier):
raise TypeError("access_method must be an ObjectIdentifier")
if not isinstance(access_location, GeneralName):
... | AccessDescription |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 96991,
"end": 100179
} | class ____(Container):
"""
Container class that dynamically returns any Container.
:param get_container: Callable that returns a :class:`.Container` instance
or any widget with a ``__pt_container__`` method.
"""
def __init__(self, get_container: Callable[[], AnyContainer]) -> None:
... | DynamicContainer |
python | apache__thrift | lib/py/src/protocol/TJSONProtocol.py | {
"start": 16843,
"end": 18855
} | class ____(TJSONProtocolBase):
"""Simple, readable, write-only JSON protocol.
Useful for interacting with scripting languages.
"""
def readMessageBegin(self):
raise NotImplementedError()
def readMessageEnd(self):
raise NotImplementedError()
def readStructBegin(self):
... | TSimpleJSONProtocol |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 19245,
"end": 19387
} | class ____:
def __init__(self, nxt: typing.Optional["B"]):
self.nxt = nxt
def __repr__(self):
return f"A({self.nxt})"
| A |
python | astropy__astropy | astropy/time/formats.py | {
"start": 73721,
"end": 74394
} | class ____(TimeNumeric):
"""
Base class for support of Besselian and Julian epoch dates.
"""
_default_scale = "tt" # As of astropy 3.2, this is no longer 'utc'.
def set_jds(self, val1, val2):
self._check_scale(self._scale) # validate scale.
epoch_to_jd = getattr(erfa, self.epoch_... | TimeEpochDate |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_cache.py | {
"start": 703,
"end": 804
} | class ____:
def foo(self, x):
return 0
def bar(self, x):
return 1
@decorated
| X |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 41256,
"end": 46585
} | class ____:
"""Descriptor used to forward queries from Spec to Package"""
def __init__(
self,
attribute_name: str,
default_handler: Optional[Callable[["Spec"], Any]] = None,
_indirect: bool = False,
) -> None:
"""Create a new descriptor.
Parameters:
... | ForwardQueryToPackage |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 14775,
"end": 28087
} | class ____:
async def test_flow_retry_with_error_in_flow(self):
run_count = 0
@flow(retries=1)
async def foo():
nonlocal run_count
run_count += 1
if run_count == 1:
raise ValueError()
return "hello"
assert await foo() ... | TestFlowRetries |
python | kamyu104__LeetCode-Solutions | Python/count-elements-with-maximum-frequency.py | {
"start": 63,
"end": 337
} | class ____(object):
def maxFrequencyElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = collections.Counter(nums)
mx = max(cnt.itervalues())
return sum(v for v in cnt.itervalues() if v == mx)
| Solution |
python | django__django | django/db/migrations/operations/models.py | {
"start": 25815,
"end": 26142
} | class ____(AlterTogetherOptionOperation):
"""
Change the value of unique_together to the target one.
Input value of unique_together must be a set of tuples.
"""
option_name = "unique_together"
def __init__(self, name, unique_together):
super().__init__(name, unique_together)
| AlterUniqueTogether |
python | scikit-learn__scikit-learn | sklearn/tests/test_base.py | {
"start": 1901,
"end": 2066
} | class ____(NaNTag):
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.allow_nan = False
return tags
| OverrideTag |
python | kamyu104__LeetCode-Solutions | Python/flatten-a-multilevel-doubly-linked-list.py | {
"start": 199,
"end": 837
} | class ____(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
curr = head
while curr:
if curr.child:
curr_next = curr.next
curr.child.prev = curr
curr.next = curr.child
la... | Solution |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 75199,
"end": 75816
} | class ____(ConstantLikeVariable):
_error_prefix = "np.dtype[...]"
def as_proxy(self):
"""Similar to how numpy dtype descriptors (e.g. np.float32 ) are handled by NumpyVariable:
np.dtype() objects are serialized as strings, torch._numpy wrappers will normalize to the torch dtype.
This a... | NumpyDTypeVariable |
python | pydata__xarray | xarray/tests/test_strategies.py | {
"start": 9230,
"end": 10237
} | class ____:
"""
These tests are for checking that the examples given in the docs page on testing actually work.
"""
@given(st.data(), variables(dims=dimension_names(min_dims=1)))
def test_mean(self, data, var):
"""
Test that given a Variable of at least one dimension,
the me... | TestReduction |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py | {
"start": 6251,
"end": 7687
} | class ____(Benchmark):
r"""
HelicalValley objective function.
This class defines the HelicalValley [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{HelicalValley}}({x}) = 100{[z-10\Psi(x_1,x_2)]^2
+(\sqrt{x_1^2+x_2... | HelicalValley |
python | python__mypy | mypy/test/data.py | {
"start": 877,
"end": 1008
} | class ____(NamedTuple):
module: str
content: str
target_path: str
# File delete operation: delete module file.
| UpdateFile |
python | getsentry__sentry | src/sentry/feedback/lib/types.py | {
"start": 44,
"end": 593
} | class ____(TypedDict):
"""Use for weak type checking of user report data. Keys correspond to fields of the UserReport model."""
event_id: str
comments: str
name: NotRequired[str] # defaults to ""
email: NotRequired[str] # defaults to ""
# required for the model, but functions usually infer th... | UserReportDict |
python | django-extensions__django-extensions | tests/management/commands/shell_plus_tests/test_collision_resolver.py | {
"start": 911,
"end": 950
} | class ____(BaseCR):
pass
| CRNoFunction |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 27600,
"end": 30105
} | class ____:
def test_basic(self, xp):
_, h = freqs_zpk(
xp.asarray([1.0]), xp.asarray([1.0]), xp.asarray([1.0]), worN=8
)
assert_array_almost_equal(h, xp.ones(8))
def test_output(self, xp):
# 1st order low-pass filter: H(s) = 1 / (s + 1)
w = xp.asarray([0.1,... | TestFreqs_zpk |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py | {
"start": 2087,
"end": 2176
} | class ____(BaseVoiceAgentEvent):
session: ConversationSession
| ConversationSessionUpdate |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 4615,
"end": 5173
} | class ____:
"""Demo."""
@overload
def bar(self, x: int) -> int: ...
@overload
def bar(self, x: str) -> str: ...
def bar(self, x: int | str) -> int | str:
return x
# end
# no error
@overload
def foo(x: int) -> int: ...
@overload
def foo(x: str) -> str: ...
def foo(x: int | str) -> int ... | Foo |
python | django__django | tests/messages_tests/tests.py | {
"start": 406,
"end": 1844
} | class ____(SimpleTestCase):
def test_eq(self):
msg_1 = Message(constants.INFO, "Test message 1")
msg_2 = Message(constants.INFO, "Test message 2")
msg_3 = Message(constants.WARNING, "Test message 1")
self.assertEqual(msg_1, msg_1)
self.assertEqual(msg_1, mock.ANY)
sel... | MessageTests |
python | falconry__falcon | tests/asgi/_asgi_test_app.py | {
"start": 8913,
"end": 10562
} | class ____:
_SUPPORTED_KEYS = frozenset(
{'default_close_reasons', 'error_close_code', 'max_receive_queue'}
)
def __init__(self, ws_options):
self._ws_options = ws_options
async def on_get(self, req, resp):
resp.media = {
key: getattr(self._ws_options, key) for key ... | WSOptions |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 22268,
"end": 22729
} | class ____(JsProxy, Generic[T_co]):
"""A JsProxy of a JavaScript iterator.
An object is a :py:class:`JsAsyncIterator` if it has a :js:meth:`~Iterator.next` method and either has a
:js:data:`Symbol.iterator` or has no :js:data:`Symbol.asyncIterator`.
"""
_js_type_flags = ["IS_ITERATOR"]
def __... | JsIterator |
python | django__django | tests/model_fields/test_binaryfield.py | {
"start": 146,
"end": 2190
} | class ____(TestCase):
binary_data = b"\x00\x46\xfe"
def test_set_and_retrieve(self):
data_set = (
self.binary_data,
bytearray(self.binary_data),
memoryview(self.binary_data),
)
for bdata in data_set:
with self.subTest(data=repr(bdata)):
... | BinaryFieldTests |
python | kamyu104__LeetCode-Solutions | Python/the-k-strongest-values-in-an-array.py | {
"start": 33,
"end": 585
} | class ____(object):
def getStrongest(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
arr.sort()
m = arr[(len(arr)-1)//2]
result = []
left, right = 0, len(arr)-1
while len(result) < k:
if m-arr[left... | Solution |
python | OmkarPathak__pygorithm | pygorithm/math/matrix_operations.py | {
"start": 168,
"end": 7104
} | class ____(object):
'''
Matrix class for performing various transformations
Matrix operations can be performed on two matrices with any number of dimensions
'''
def __init__(self, matrix_one = None, matrix_two=None):
'''
:param matrix_one: matrix with nxn dimensions
... | Matrix |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 45131,
"end": 46235
} | class ____(NonStrictDataModel):
"""
:param rules: Rules list
:type rules: Sequence[MappingRule]
"""
_schema = {
"properties": {
"rules": {
"description": "Rules list",
"items": {"$ref": "#/definitions/mapping_rule"},
"type": ["arra... | Mapping |
python | Textualize__textual | tests/css/test_nested_css.py | {
"start": 306,
"end": 1267
} | class ____(App):
CSS = """
Screen {
& > #foo {
background: red;
#egg {
background: green;
}
.paul {
background: blue;
}
&.jessica {
color: magenta;
}
}
}
... | NestedApp |
python | ray-project__ray | python/ray/serve/config.py | {
"start": 1126,
"end": 6103
} | class ____:
"""Rich context provided to custom autoscaling policies.
This class provides comprehensive information about a deployment's current state,
metrics, and configuration that can be used by custom autoscaling policies to
make intelligent scaling decisions.
The context includes deployment m... | AutoscalingContext |
python | huggingface__transformers | src/transformers/models/plbart/modular_plbart.py | {
"start": 15364,
"end": 17240
} | class ____(BigBirdPegasusForSequenceClassification):
def forward(**super_kwargs):
r"""
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained usin... | PLBartForSequenceClassification |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/summary_ops/summary_ops_test.py | {
"start": 42214,
"end": 47535
} | class ____(test_util.TensorFlowTestCase):
def testWriter_savedAsModuleProperty_loadInEagerMode(self):
with context.eager_mode():
class Model(module.Module):
def __init__(self, model_dir):
self._writer = summary_ops.create_file_writer_v2(
model_dir, experimental_trackable=Tr... | SummaryWriterSavedModelTest |
python | realpython__materials | python-selenium/src/bandcamp/web/base.py | {
"start": 438,
"end": 696
} | class ____:
def __init__(self, driver: WebDriver) -> None:
self._driver = driver
self._driver.set_window_size(*DEFAULT_WINDOW_SIZE)
self._driver.implicitly_wait(5)
self._wait = WebDriverWait(driver, MAX_WAIT_SECONDS)
| WebPage |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/core.py | {
"start": 16188,
"end": 20181
} | class ____(Layer):
"""Layer that reshapes inputs into the given shape.
Input shape:
Arbitrary, although all dimensions in the input shape must be known/fixed.
Use the keyword argument `input_shape` (tuple of integers, does not include
the samples/batch size axis) when using this layer as the first laye... | Reshape |
python | huggingface__transformers | src/transformers/utils/quantization_config.py | {
"start": 87204,
"end": 89776
} | class ____(QuantizationConfigMixin):
"""
This is a wrapper class about `spqr` parameters. Refer to the original publication for more details.
Args:
bits (`int`, *optional*, defaults to 3):
Specifies the bit count for the weights and first order zero-points and scales.
Curren... | SpQRConfig |
python | pikepdf__pikepdf | src/pikepdf/form.py | {
"start": 6812,
"end": 10023
} | class ____(_FieldWrapper):
"""Represents an editable text field."""
@property
def is_multiline(self) -> bool:
"""Is this a multiline text field?
If True, text will be wrapped and newlines will be allowed. If False, text will
not be wrapped and newlines are stripped.
"""
... | TextField |
python | FactoryBoy__factory_boy | tests/test_declarations.py | {
"start": 6899,
"end": 8301
} | class ____(unittest.TestCase):
def test_invalid_path(self):
with self.assertRaises(ValueError):
declarations._FactoryWrapper('UnqualifiedSymbol')
with self.assertRaises(ValueError):
declarations._FactoryWrapper(42)
def test_class(self):
w = declarations._FactoryW... | FactoryWrapperTestCase |
python | mlflow__mlflow | tests/utils/test_async_logging_queue.py | {
"start": 8109,
"end": 14315
} | class ____:
def __init__(self) -> None:
self.metrics = []
self.tags = []
self.params = []
def consume_queue_data(self, run_id, metrics, tags, params):
time.sleep(0.5)
self.metrics.extend(metrics or [])
self.params.extend(params or [])
self.tags.extend(tag... | Consumer |
python | redis__redis-py | tests/test_maint_notifications_handling.py | {
"start": 21886,
"end": 93103
} | class ____(TestMaintenanceNotificationsBase):
"""Integration tests for maintenance notifications handling with real connection pool."""
def _validate_connection_handlers(self, conn, pool_handler, config):
"""Helper method to validate connection handlers are properly set."""
# Test that the node... | TestMaintenanceNotificationsHandlingSingleProxy |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 76200,
"end": 82798
} | class ____(Request):
"""
Return the debug image per metric and variant for the provided iteration
:param task: Task ID
:type task: str
:param metric: Metric name
:type metric: str
:param variant: Metric variant
:type variant: str
:param iteration: The iteration to bring debug image ... | GetDebugImageSampleRequest |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/grouping.py | {
"start": 2857,
"end": 4831
} | class ____(IterDataPipe):
r"""
Undos batching of data (functional name: ``unbatch``).
In other words, it flattens the data up to the specified level within a batched DataPipe.
Args:
datapipe: Iterable DataPipe being un-batched
unbatch_level: Defaults to ``1`` (only flattening the top l... | UnBatcherIterDataPipe |
python | scrapy__scrapy | tests/test_scheduler.py | {
"start": 1611,
"end": 2159
} | class ____:
def __init__(self):
self.slots = {}
def get_slot_key(self, request):
if Downloader.DOWNLOAD_SLOT in request.meta:
return request.meta[Downloader.DOWNLOAD_SLOT]
return urlparse_cached(request).hostname or ""
def increment(self, slot_key):
slot = self... | MockDownloader |
python | getsentry__sentry-python | tests/integrations/django/myapp/management/commands/mycrash.py | {
"start": 54,
"end": 187
} | class ____(BaseCommand):
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
1 / 0
| Command |
python | huggingface__transformers | tests/models/opt/test_modeling_opt.py | {
"start": 13707,
"end": 14632
} | class ____(unittest.TestCase):
@slow
def test_inference_no_head(self):
model = OPTModel.from_pretrained("facebook/opt-350m").to(torch_device)
input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
with torch.no_grad():
output = model(input_ids... | OPTModelIntegrationTests |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/solids.py | {
"start": 19923,
"end": 20095
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "SolidStepStatusUnavailableError"
| GrapheneSolidStepStatsUnavailableError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call10.py | {
"start": 496,
"end": 946
} | class ____(str): ...
def test_kwargs2(
a: Mapping[str, Any],
b: Mapping[Any, Hashable],
c: dict[StrSubclass, Hashable],
d: int,
e: Mapping[int, Hashable],
f: tuple[str, ...],
):
test_kwargs(**a)
test_kwargs(**b)
test_kwargs(**c)
# This should generate an error
test_kwargs(... | StrSubclass |
python | keras-team__keras | keras/src/layers/pooling/global_average_pooling_test.py | {
"start": 174,
"end": 2815
} | class ____(testing.TestCase):
@parameterized.parameters(
("channels_last", False, (3, 5, 4), (3, 4)),
("channels_last", True, (3, 5, 4), (3, 1, 4)),
("channels_first", False, (3, 5, 4), (3, 5)),
)
def test_global_average_pooling1d(
self,
data_format,
keepdims,... | GlobalAveragePoolingBasicTest |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/secretsmanager/resources.py | {
"start": 4758,
"end": 12745
} | class ____(ResourceWithBoto3Configuration):
"""Resource that provides a dict which maps selected SecretsManager secrets to
their string values. Also optionally sets chosen secrets as environment variables.
Example:
.. code-block:: python
import os
from dagster import build_... | SecretsManagerSecretsResource |
python | tensorflow__tensorflow | tensorflow/python/summary/tb_summary.py | {
"start": 918,
"end": 14995
} | class ____(Exception):
def __init__(self, summary_api):
self.error_message = f"{_TENSORBOARD_NOT_INSTALLED_ERROR} {summary_api}"
super().__init__(self.error_message)
@tf_export("summary.audio", v1=[])
def audio(
name,
data,
sample_rate,
step=None,
max_outputs=3,
encoding=None,
d... | TBNotInstalledError |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_installations.py | {
"start": 1323,
"end": 1503
} | class ____(serializers.Serializer):
slug = SentrySerializerSlugField(required=True, max_length=SENTRY_APP_SLUG_MAX_LENGTH)
@control_silo_endpoint
| SentryAppInstallationsSerializer |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_hex_color.py | {
"start": 490,
"end": 1603
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_hexcolor"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(c... | ColumnValuesToBeValidHexColor |
python | faif__python-patterns | patterns/behavioral/observer.py | {
"start": 1930,
"end": 2074
} | class ____:
def update(self, subject: Data) -> None:
print(f"HexViewer: Subject {subject.name} has data 0x{subject.data:x}")
| HexViewer |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/glue_job.py | {
"start": 247,
"end": 2199
} | class ____(BaseModel, JobRun):
"""Execute a Glue Job"""
job_name: str = Field(
...,
title="AWS Glue Job Name",
description="The name of the job definition to use.",
)
job_id: str = Field(
...,
title="AWS Glue Job ID",
description="The ID of the job run."... | GlueJobRun |
python | kamyu104__LeetCode-Solutions | Python/determine-the-minimum-sum-of-a-k-avoiding-array.py | {
"start": 61,
"end": 425
} | class ____(object):
def minimumSum(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def arithmetic_progression_sum(a, d, n):
return (a+(a+(n-1)*d))*n//2
a = min(k//2, n)
b = n-a
return arithmetic_progression_sum(1, 1,... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 456824,
"end": 457465
} | class ____(sgqlc.types.Interface):
"""Metadata for an audit entry with action team.*"""
__schema__ = github_schema
__field_names__ = ("team", "team_name", "team_resource_path", "team_url")
team = sgqlc.types.Field("Team", graphql_name="team")
"""The team associated with the action"""
team_name... | TeamAuditEntryData |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/activation.py | {
"start": 5885,
"end": 7293
} | class ____(torch.nn.Softmax):
r"""This is the quantized version of :class:`~torch.nn.Softmax`.
Args:
dim: A dimension along which Softmax will be computed (so every slice along dim will sum to 1).
scale: quantization scale of the output tensor
zero_point: quantization zero point of the ... | Softmax |
python | EpistasisLab__tpot | tpot/tpot_estimator/templates/tpottemplates.py | {
"start": 1863,
"end": 19046
} | class ____(TPOTEstimator):
def __init__( self,
search_space = "linear",
scorers=['neg_mean_squared_error'],
scorers_weights=[1],
cv = 10, #remove this and use a value based on dataset size?
... | TPOTRegressor |
python | pytorch__pytorch | test/dynamo/test_guard_serialization.py | {
"start": 9199,
"end": 14199
} | class ____(torch._inductor.test_case.TestCase):
def _tracefunc(self, frame, event, arg):
if event != "call":
return
if self._frame_state is not None:
return
self._frame_state = _FrameState(
f_locals=dict(frame.f_locals),
f_globals=frame.f_glo... | TestGuardSerializationBase |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/boring_classes.py | {
"start": 8374,
"end": 8913
} | class ____(BoringModel):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self) -> None:
super().__init__()
self.automatic_optimization = False
def training_step(self, batch: Any, batch_idx: int) -> STEP_OUTPUT:
opt = self.optimize... | ManualOptimBoringModel |
python | google__jax | jax/_src/effects.py | {
"start": 3587,
"end": 5041
} | class ____:
def __init__(self):
self._effect_types: set[type[Effect]] = set()
def __repr__(self):
return f"EffectTypeSet({self._effect_types})"
def add_type(self, effect_type: type[Effect]):
self._effect_types.add(effect_type)
def contains(self, eff: Effect) -> bool:
return any(isinstance(ef... | EffectTypeSet |
python | doocs__leetcode | solution/1000-1099/1018.Binary Prefix Divisible By 5/Solution.py | {
"start": 0,
"end": 214
} | class ____:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
ans = []
x = 0
for v in nums:
x = (x << 1 | v) % 5
ans.append(x == 0)
return ans
| Solution |
python | coleifer__peewee | peewee.py | {
"start": 68977,
"end": 71602
} | class ____(SelectBase):
def __init__(self, lhs, op, rhs):
super(CompoundSelectQuery, self).__init__()
self.lhs = lhs
self.op = op
self.rhs = rhs
@property
def _returning(self):
return self.lhs._returning
@database_required
def exists(self, database):
... | CompoundSelectQuery |
python | pytest-dev__pytest | doc/en/example/nonpython/conftest.py | {
"start": 1469,
"end": 1549
} | class ____(Exception):
"""Custom exception for error reporting."""
| YamlException |
python | faif__python-patterns | patterns/structural/proxy.py | {
"start": 1382,
"end": 2503
} | class ____(Subject):
def __init__(self) -> None:
self._real_subject = RealSubject()
def do_the_job(self, user: str) -> None:
"""
logging and controlling access are some examples of proxy usages.
"""
print(f"[log] Doing the job for {user} is requested.")
if user... | Proxy |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 10070,
"end": 10671
} | class ____(Processor):
"""
Processor that masks the input. (For passwords.)
:param char: (string) Character to be used. "*" by default.
"""
def __init__(self, char: str = "*") -> None:
self.char = char
def apply_transformation(self, ti: TransformationInput) -> Transformation:
... | PasswordProcessor |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/config_type.py | {
"start": 4092,
"end": 4468
} | class ____(ConfigType):
def __init__(
self,
key: str,
given_name: Optional[str],
scalar_kind: ConfigScalarKind,
**kwargs: typing.Any,
):
self.scalar_kind = check.inst_param(scalar_kind, "scalar_kind", ConfigScalarKind)
super().__init__(key, kind=ConfigType... | ConfigScalar |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_gtk3.py | {
"start": 15979,
"end": 18656
} | class ____(ToolContainerBase, Gtk.Box):
_icon_extension = '-symbolic.svg'
def __init__(self, toolmanager):
ToolContainerBase.__init__(self, toolmanager)
Gtk.Box.__init__(self)
self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
self._message = Gtk.Label()
self._... | ToolbarGTK3 |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 16427,
"end": 17163
} | class ____(nn.Module):
def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
super().__init__()
embed_dim = config.n_embd
self.fc_in = nn.Linear(embed_dim, intermediate_size)
self.fc_out = nn.Linear(intermediate_size, embed_dim)
self.act... | GPTJMLP |
python | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/core_models.py | {
"start": 9721,
"end": 10365
} | class ____(Resolvable):
"""Resolvable object representing only a configurable asset key."""
key: Optional[ResolvedAssetKey] = None
key_prefix: Annotated[
Optional[CoercibleToAssetKeyPrefix],
Resolver.default(description="Prefix the existing asset key with the provided value."),
] = None... | AssetSpecKeyUpdateKwargs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.