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
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis44.py
{ "start": 315, "end": 1790 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis44.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
PyCQA__pyflakes
pyflakes/test/test_api.py
{ "start": 673, "end": 837 }
class ____: """ Mock an AST node. """ def __init__(self, lineno, col_offset=0): self.lineno = lineno self.col_offset = col_offset
Node
python
huggingface__transformers
src/transformers/utils/hp_naming.py
{ "start": 631, "end": 4979 }
class ____: PREFIX = "hp" DEFAULTS = {} NAMING_INFO = None @classmethod def set_defaults(cls, prefix, defaults): cls.PREFIX = prefix cls.DEFAULTS = defaults cls.build_naming_info() @staticmethod def shortname_for_word(info, word): if len(word) == 0: ...
TrialShortNamer
python
google__pytype
pytype/blocks/block_serializer.py
{ "start": 821, "end": 877 }
class ____: blocks: list[SerializedBlock]
SerializedCode
python
kamyu104__LeetCode-Solutions
Python/longest-zigzag-path-in-a-binary-tree.py
{ "start": 191, "end": 663 }
class ____(object): def longestZigZag(self, root): """ :type root: TreeNode :rtype: int """ def dfs(node, result): if not node: return [-1, -1] left, right = dfs(node.left, result), dfs(node.right, result) result[0] = max(re...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 142004, "end": 142403 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(SponsorsTierOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc...
SponsorsTierOrder
python
PrefectHQ__prefect
src/prefect/server/models/flow_runs.py
{ "start": 11693, "end": 22347 }
class ____(PrefectBaseModel): id: UUID name: str upstream_dependencies: List[TaskRunResult] state: Optional[State] expected_start_time: Optional[datetime.datetime] start_time: Optional[datetime.datetime] end_time: Optional[datetime.datetime] total_run_time: Optional[datetime.timedelta] ...
DependencyResult
python
django__django
django/db/models/fields/__init__.py
{ "start": 67298, "end": 69040 }
class ____(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid form...
DurationField
python
kamyu104__LeetCode-Solutions
Python/fraction-addition-and-subtraction.py
{ "start": 71, "end": 617 }
class ____(object): def fractionAddition(self, expression): """ :type expression: str :rtype: str """ def gcd(a, b): while b: a, b = b, a%b return a ints = map(int, re.findall('[+-]?\d+', expression)) A, B = 0, 1 ...
Solution
python
python__mypy
mypyc/ir/ops.py
{ "start": 15572, "end": 16520 }
class ____(ControlOp): """Mark the end of basic block as unreachable. This is sometimes necessary when the end of a basic block is never reached. This can also be explicitly added to the end of non-None returning functions (in None-returning function we can just return None). Mypy statically g...
Unreachable
python
huggingface__transformers
tests/models/d_fine/test_modeling_d_fine.py
{ "start": 10980, "end": 27966 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (DFineModel, DFineForObjectDetection) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": DFineModel, "object-detection": DFineForObjectDetection} if is_torch_available()...
DFineModelTest
python
huggingface__transformers
src/transformers/models/poolformer/modeling_poolformer.py
{ "start": 9509, "end": 10167 }
class ____(PreTrainedModel): config: PoolFormerConfig base_model_prefix = "poolformer" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["PoolFormerLayer"] @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" super(...
PoolFormerPreTrainedModel
python
huggingface__transformers
tests/quantization/bnb/test_4bit.py
{ "start": 21181, "end": 23365 }
class ____(Base4bitTest): def setUp(self): super().setUp() def test_multi_accelerator_loading(self): r""" This tests that the model has been loaded and can be used correctly on a multi-accelerator setup. Let's just try to load a model on 2 accelerators and see if it works. The m...
Bnb4bitTestMultiAccelerator
python
falconry__falcon
falcon/errors.py
{ "start": 96817, "end": 99022 }
class ____(HTTPBadRequest): """400 Bad Request. A parameter is missing from the request. This error may refer to a parameter in a query string, form, or document that was submitted with the request. `param_name` is the only positional argument allowed, the other arguments are defined as keywor...
HTTPMissingParam
python
oauthlib__oauthlib
tests/openid/connect/core/grant_types/test_implicit.py
{ "start": 681, "end": 6762 }
class ____(TestCase): def setUp(self): self.request = Request('http://a.b/path') self.request.scopes = ('hello', 'openid') self.request.expires_in = 1800 self.request.client_id = 'abcdef' self.request.response_type = 'id_token token' self.request.redirect_uri = 'http...
OpenIDImplicitTest
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_sentinels.py
{ "start": 1018, "end": 1262 }
class ____(_Sentinel): """A special value for :*-members: that matches to any member.""" def __contains__(self, item: object) -> Literal[True]: return True def append(self, item: object) -> None: pass # nothing
_All
python
gevent__gevent
src/gevent/tests/test__monkey_queue.py
{ "start": 3423, "end": 8519 }
class ____(unittest.TestCase, BlockingTestMixin): type2test = Queue.Queue def setUp(self): self.cum = 0 self.cumlock = threading.Lock() def simple_queue_test(self, q): if not q.empty(): raise RuntimeError("Call this function with an empty queue") # I guess we be...
BaseQueueTest
python
huggingface__transformers
src/transformers/models/gemma3/modular_gemma3.py
{ "start": 37117, "end": 42037 }
class ____(PaliGemmaModel): # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch accepts_loss_kwargs = False def __init__(self, config: Gemma3Config): super().__init__(config) del self.text_config_dtype def get_image_features(self, pixel_valu...
Gemma3Model
python
pytorch__pytorch
torch/_inductor/remote_cache.py
{ "start": 2971, "end": 4219 }
class ____(RemoteCacheSerde[_T, _T]): def encode(self, data: _T) -> _T: return data def decode(self, data: _T) -> _T: return data # This class is the top of a RemoteCache. A RemoteCache is fundamentally made of # three parts: # # 1. The controller (this class). # 2. A serializer/deserializer ...
RemoteCachePassthroughSerde
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 20535, "end": 20708 }
class ____: def __init__(self, ml_name): self.ml_name = ml_name def __repr__(self): return "<built-in function %s>" % self.ml_name
BuiltInFunctionProxy
python
pytorch__pytorch
torch/ao/nn/quantized/reference/modules/conv.py
{ "start": 355, "end": 1703 }
class ____(torch.nn.modules.conv._ConvNd, ReferenceQuantizedModule): """A reference version of nn.quantized.Conv2d we will not pack the parameters in this module, since weight packing is an optimization for quantized backends supported in PyTorch (fbgemm/qnnpack), this is useful when user want to use th...
_ConvNd
python
tensorflow__tensorflow
tensorflow/python/ops/array_grad_test.py
{ "start": 1137, "end": 5840 }
class ____(test.TestCase): def _testGrad(self, f, x): max_error = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(f, [x])) self.assertLess(max_error, 1e-4) def test_gather_v2_simple(self): x = constant_op.constant([1., 2., 3., 4., 5.], dtype=dtypes.float64) def f(x): ...
ArrayGradTest
python
huggingface__transformers
src/transformers/models/groupvit/modeling_groupvit.py
{ "start": 43558, "end": 45401 }
class ____(GroupViTPreTrainedModel): config: GroupViTTextConfig input_modalities = ("text",) def __init__(self, config: GroupViTTextConfig): super().__init__(config) self.text_model = GroupViTTextTransformer(config) # Initialize weights and apply final processing self.post_i...
GroupViTTextModel
python
bottlepy__bottle
test/test_wsgi.py
{ "start": 14820, "end": 17544 }
class ____(ServerTestBase): ''' Tests Decorators ''' def test_view(self): """ WSGI: Test view-decorator (should override autojson) """ with chdir(__file__): @bottle.route('/tpl') @bottle.view('stpl_t2main') def test(): return dict(content='123...
TestDecorators
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 25241, "end": 25539 }
class ____(Float[_N]): """A type for double ``FLOAT`` floating point types. Typically generates a ``DOUBLE`` or ``DOUBLE_PRECISION`` in DDL, and otherwise acts like a normal :class:`.Float` on the Python side. .. versionadded:: 2.0 """ __visit_name__ = "double"
Double
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0024_status_code_choices.py
{ "start": 149, "end": 806 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0023_add_status_code"), ] operations = [ migrations.RemoveField( model_name="build", name="status_code", ), migrations.AddField( model_name="buil...
Migration
python
numba__numba
numba/cuda/tests/cudapy/test_gufunc.py
{ "start": 873, "end": 12471 }
class ____(CUDATestCase): def test_gufunc_small(self): gufunc = _get_matmulcore_gufunc() matrix_ct = 2 A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4) B = np.arange(matrix_ct * 4 * 5, dt...
TestCUDAGufunc
python
great-expectations__great_expectations
great_expectations/core/batch_spec.py
{ "start": 5615, "end": 6132 }
class ____(BatchSpec): _id_ignore_keys = set("batch_data") def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) if self.batch_data is None: raise InvalidBatchSpecError("RuntimeDataBatchSpec batch_data cannot be None") # noqa: TRY003 # FIXME CoP @prop...
RuntimeDataBatchSpec
python
facelessuser__pymdown-extensions
pymdownx/fancylists.py
{ "start": 1758, "end": 14462 }
class ____(BlockProcessor): """Process fancy ordered list blocks.""" TAG = 'ol' SIBLING_TAGS = ['ol'] OL_TYPES = { 'dot-decimal': '1', 'paren-decimal': '1', 'dot-roman': 'i', 'paren-roman': 'i', 'dot-ROMAN': 'I', 'paren-ROMAN': 'I', 'dot-alpha': '...
FancyOListProcessor
python
wandb__wandb
tools/local_wandb_server.py
{ "start": 9071, "end": 12841 }
class ____: base_port: int fixture_port: int def apply_ports(self, server: _ServerInfo) -> None: server.base_port = self.base_port server.fixture_port = self.fixture_port def _start_container(*, name: str) -> _WandbContainerPorts: """Start the local-testcontainer. This issues the...
_WandbContainerPorts
python
ray-project__ray
python/ray/_private/gc_collect_manager.py
{ "start": 132, "end": 1604 }
class ____(threading.Thread): """A background thread that triggers Python garbage collection. This thread waits for GC events from CoreWorker and triggers `gc.collect()` when when requested.""" def __init__(self, *, gc_collect_func: Optional[Callable] = None): logger.debug("Starting Python GC ...
PythonGCThread
python
run-llama__llama_index
llama-index-integrations/agent/llama-index-agent-azure/tests/test_azure_foundry_agent.py
{ "start": 745, "end": 18705 }
class ____: def __init__(self, items): self._items = items def __aiter__(self): self._iter = iter(self._items) return self async def __anext__(self): try: return next(self._iter) except StopIteration: raise StopAsyncIteration def test_azure...
DummyAsyncIterator
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_utf8_05.py
{ "start": 314, "end": 987 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("utf8_05.xlsx") self.ignore_files = [ "xl/calcChain.xml", "[Content_Types].xml", "xl/_rels/workbook.xml.rels...
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/api/serializers/models/group_stream.py
{ "start": 3088, "end": 3250 }
class ____(NamedTuple): stats_period: str | None stats_period_start: datetime | None = None stats_period_end: datetime | None = None
GroupStatsQueryArgs
python
apache__airflow
airflow-core/src/airflow/models/dagrun.py
{ "start": 5297, "end": 90158 }
class ____(Base, LoggingMixin): """ Invocation instance of a DAG. A DAG run can be created by the scheduler (i.e. scheduled runs), or by an external trigger (i.e. manual runs). """ active_spans = ThreadSafeDict() __tablename__ = "dag_run" id: Mapped[int] = mapped_column(Integer, prim...
DagRun
python
readthedocs__readthedocs.org
readthedocs/organizations/views/public.py
{ "start": 4273, "end": 4538 }
class ____(CheckOrganizationsEnabled, GenericView): """Redirect invitation links to the new view.""" def get(self, request, *args, **kwargs): return HttpResponseRedirect(reverse("invitations_redeem", args=[kwargs["hash"]]))
RedirectRedeemTeamInvitation
python
pennersr__django-allauth
allauth/account/forms.py
{ "start": 24887, "end": 25417 }
class ____(PasswordVerificationMixin, forms.Form): password1 = SetPasswordField(label=_("New Password")) password2 = PasswordField(label=_("New Password (again)")) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) self.temp_key = kwargs.pop("temp_key", None) ...
ResetPasswordKeyForm
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_quantize.py
{ "start": 4446, "end": 5307 }
class ____(torch.nn.Module): __constants__ = ["in_features", "out_features"] in_features: int out_features: int weight: torch.Tensor def __init__( self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None, target_dt...
WeightOnlyInt8Linear
python
doocs__leetcode
solution/2200-2299/2299.Strong Password Checker II/Solution.py
{ "start": 0, "end": 499 }
class ____: def strongPasswordCheckerII(self, password: str) -> bool: if len(password) < 8: return False mask = 0 for i, c in enumerate(password): if i and c == password[i - 1]: return False if c.islower(): mask |= 1 ...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/isinstance3.py
{ "start": 1805, "end": 2366 }
class ____(TypedDict): a: int # This should generate an error because TypedDict classes can't # be used in an isinstance call. if isinstance(a, TD1): pass TA1 = Annotated[int, ""] # This should generate two errors because Annotated can't be used # in an isinstance call. if isinstance(1, TA1): pass # T...
TD1
python
davidhalter__jedi
jedi/api/completion.py
{ "start": 4385, "end": 28417 }
class ____: def __init__(self, inference_state, module_context, code_lines, position, signatures_callback, fuzzy=False): self._inference_state = inference_state self._module_context = module_context self._module_node = module_context.tree_node self._code_lines = code...
Completion
python
kamyu104__LeetCode-Solutions
Python/find-kth-character-in-expanded-string.py
{ "start": 38, "end": 430 }
class ____(object): def kthCharacter(self, s, k): """ :type s: str :type k: int :rtype: str """ l = 0 for i in xrange(len(s)): if s[i] == ' ': l = 0 k -= 1 else: l += 1 k -...
Solution
python
getsentry__sentry
tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py
{ "start": 20883, "end": 21228 }
class ____(TestTicketingIssueAlertHandlerBase): def setUp(self) -> None: super().setUp() self.handler = JiraIssueAlertHandler() def test_build_rule_action_blob(self) -> None: for expected in JIRA_ACTION_DATA_BLOBS: self._test_build_rule_action_blob(expected, Action.Type.JIRA...
TestJiraIssueAlertHandler
python
scikit-learn__scikit-learn
sklearn/ensemble/_bagging.py
{ "start": 42617, "end": 53263 }
class ____(RegressorMixin, BaseBagging): """A Bagging regressor. A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. ...
BaggingRegressor
python
plotly__plotly.py
plotly/graph_objs/choroplethmapbox/unselected/_marker.py
{ "start": 233, "end": 2399 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "choroplethmapbox.unselected" _path_str = "choroplethmapbox.unselected.marker" _valid_props = {"opacity"} @property def opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exis...
Marker
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
{ "start": 57342, "end": 57558 }
class ____(graphene.ObjectType): class Meta: name = "CodeLocation" repositoryName = graphene.NonNull(graphene.String) repositoryLocationName = graphene.NonNull(graphene.String)
GrapheneCodeLocation
python
apache__airflow
airflow-core/tests/unit/models/test_serialized_dag.py
{ "start": 2813, "end": 28165 }
class ____: """Unit tests for SerializedDagModel.""" @pytest.fixture( autouse=True, params=[ pytest.param(False, id="raw-serialized_dags"), pytest.param(True, id="compress-serialized_dags"), ], ) def setup_test_cases(self, request, monkeypatch): d...
TestSerializedDagModel
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/rpc_utils.py
{ "start": 2521, "end": 16457 }
class ____: """ Simple file-like class that wraps a bytes, and allows moving its "start" position in the bytes. This is only used for reading concatenated PNGs, because Pillow always calls seek(0) at the start of reading. """ __slots__ = ["fp", "offset"] def __init__(self, data: bytes): ...
OffsetBytesIO
python
cherrypy__cherrypy
cherrypy/test/test_conn.py
{ "start": 30557, "end": 31261 }
class ____(helper.CPWebCase): setup_server = staticmethod(setup_server) def test_No_CRLF(self): self.persistent = True conn = self.HTTP_CONN conn.send(b'GET /hello HTTP/1.1\n\n') response = conn.response_class(conn.sock, method='GET') response.begin() self.body ...
BadRequestTests
python
sqlalchemy__sqlalchemy
test/engine/test_execute.py
{ "start": 13609, "end": 30371 }
class ____(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column("user_id", INT, primary_key=True, autoincrement=False), Column("user_name", VARCHAR(20)), ) Table( ...
ExecuteDriverTest
python
fluentpython__example-code
attic/descriptors/doc_descriptor.py
{ "start": 1378, "end": 1512 }
class ____: """The "Foo" class""" bar = DocDescriptor('The "bar" attribute') bazz = DocDescriptor('The "bazz" attribute')
Foo
python
walkccc__LeetCode
solutions/634. Find the Derangement of An Array/634-2.py
{ "start": 0, "end": 210 }
class ____: def findDerangement(self, n: int) -> int: MOD = 1_000_000_007 dp = [1] + [0] * n for i in range(2, n + 1): dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % MOD return dp[n]
Solution
python
kamyu104__LeetCode-Solutions
Python/find-all-the-lonely-nodes.py
{ "start": 221, "end": 803 }
class ____(object): def getLonelyNodes(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] stk = [root] while stk: node = stk.pop() if not node: continue if node.left and not node.right: ...
Solution
python
modin-project__modin
modin/tests/pandas/extensions/test_base_extensions.py
{ "start": 3190, "end": 4836 }
class ____: def test_add_simple_method(self, backend, data_class): expected_string_val = "Some string value" method_name = "new_method" @register_base_accessor(name=method_name) def my_method_implementation(self): return expected_string_val modin_object = data_c...
TestOverrideMethodForAllBackends
python
doocs__leetcode
solution/0400-0499/0401.Binary Watch/Solution2.py
{ "start": 0, "end": 303 }
class ____: def readBinaryWatch(self, turnedOn: int) -> List[str]: ans = [] for i in range(1 << 10): h, m = i >> 6, i & 0b111111 if h < 12 and m < 60 and i.bit_count() == turnedOn: ans.append('{:d}:{:02d}'.format(h, m)) return ans
Solution
python
eventlet__eventlet
tests/pools_test.py
{ "start": 5446, "end": 5712 }
class ____(TestCase): mode = 'static' def test_abstract(self): # Going for 100% coverage here # A Pool cannot be used without overriding create() pool = pools.Pool() self.assertRaises(NotImplementedError, pool.get)
TestAbstract
python
chroma-core__chroma
chromadb/test/test_config.py
{ "start": 1289, "end": 3353 }
class ____(Component): def __init__(self, system: System): data.inits += "D" super().__init__(system) @overrides def start(self) -> None: data.starts += "D" @overrides def stop(self) -> None: data.stops += "D" # Dependency Graph for tests: # ┌───┐ # │ A │ # └┬─┬┘ ...
ComponentD
python
streamlit__streamlit
lib/tests/streamlit/runtime/state/widgets_test.py
{ "start": 24989, "end": 26135 }
class ____(DeltaGeneratorTestCase): def test_get_widget_user_key(self): state = get_script_run_ctx().session_state._state st.checkbox("checkbox", key="c") k = next(iter(state._keys())) assert user_key_from_element_id(k) == "c" def test_get_widget_user_key_none(self): st...
WidgetUserKeyTests
python
django__django
tests/template_tests/filter_tests/test_linenumbers.py
{ "start": 1243, "end": 2043 }
class ____(SimpleTestCase): def test_linenumbers(self): self.assertEqual(linenumbers("line 1\nline 2"), "1. line 1\n2. line 2") def test_linenumbers2(self): self.assertEqual( linenumbers("\n".join(["x"] * 10)), "01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09....
FunctionTests
python
kamyu104__LeetCode-Solutions
Python/number-of-common-factors.py
{ "start": 61, "end": 530 }
class ____(object): def commonFactors(self, a, b): """ :type a: int :type b: int :rtype: int """ def gcd(a, b): # Time: O(log(min(a, b))) while b: a, b = b, a%b return a g = gcd(a, b) result = 0 ...
Solution
python
huggingface__transformers
src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py
{ "start": 15086, "end": 17511 }
class ____(nn.Module): """ The neural network from the paper "Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation" https://huggingface.co/papers/1802.02611 """ def __init__(self, config: MobileNetV2Config) -> None: super().__init__() self.avg_pool = nn...
MobileNetV2DeepLabV3Plus
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_raise.py
{ "start": 10183, "end": 15679 }
class ____(__TestCase): def test_instance_context_instance_raise(self): context = IndexError() try: try: raise context except: raise OSError() except OSError as e: self.assertIs(e.__context__, context) else: ...
TestContext
python
apache__avro
lang/py/avro/test/test_protocol.py
{ "start": 13749, "end": 14974 }
class ____(unittest.TestCase): """Enable generating parse test cases over all the valid and invalid example protocols.""" def __init__(self, test_proto): """Ignore the normal signature for unittest.TestCase because we are generating many test cases from this one class. This is safe as long as t...
ProtocolParseTestCase
python
scipy__scipy
scipy/spatial/tests/test_distance.py
{ "start": 61090, "end": 63231 }
class ____: checked_dtypes = [np.float64, np.float32, np.int32, np.int8, bool] def test_squareform_matrix(self): for dtype in self.checked_dtypes: self.check_squareform_matrix(dtype) def test_squareform_vector(self): for dtype in self.checked_dtypes: self.check_squa...
TestSquareForm
python
Delgan__loguru
tests/exceptions/source/diagnose/attributes.py
{ "start": 149, "end": 430 }
class ____: @property def forbidden(self): raise RuntimeError a = Obj() a.b = "123" def foo(): x = None ... + 1 + bar(a).b + a.forbidden + a.nope.a + x.__bool__ or a. b . isdigit() and .3 + ... try: foo() except TypeError: logger.exception("")
Obj
python
conda__conda
conda/exceptions.py
{ "start": 15585, "end": 15802 }
class ____(CondaIOError): def __init__(self, filepath: PathType, message: str, *args): self.filepath = filepath msg = f"'{filepath}'. {message}" super().__init__(msg, *args)
CondaFileIOError
python
google__pytype
pytype/tools/traces/traces_test.py
{ "start": 5763, "end": 6543 }
class ____(MatchAstTestCase): """Tests for traces.MatchAstVisitor.match_Name.""" def test_basic(self): matches = self._get_traces("x = 42", ast.Name) self.assertTracesEqual(matches, [((1, 0), "STORE_NAME", "x", ("int",))]) def test_multiline(self): matches = self._get_traces(""" x = (1 + ...
MatchNameTest
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py
{ "start": 99, "end": 1002 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": ...
Hero
python
getsentry__sentry
src/sentry/sentry_apps/api/bases/sentryapps.py
{ "start": 10045, "end": 10763 }
class ____(IntegrationPlatformEndpoint): permission_classes: tuple[type[BasePermission], ...] = (SentryAppPermission,) def convert_args( self, request: Request, sentry_app_id_or_slug: int | str, *args: Any, **kwargs: Any ): try: sentry_app = SentryApp.objects.get(slug__id_or_slu...
SentryAppBaseEndpoint
python
dagster-io__dagster
python_modules/dagster/dagster/_config/config_type.py
{ "start": 1768, "end": 3921 }
class ____: """The class backing DagsterTypes as they are used processing configuration data.""" def __init__( self, key: str, kind: ConfigTypeKind, given_name: Optional[str] = None, description: Optional[str] = None, type_params: Optional[Sequence["ConfigType"]]...
ConfigType
python
doocs__leetcode
solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution2.py
{ "start": 0, "end": 641 }
class ____: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: banned.extend([0, n + 1]) ban = sorted(x for x in set(banned) if x < n + 2) ans = 0 for i, j in pairwise(ban): left, right = 0, j - i - 1 while left < right: mid = (...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 60085, "end": 60234 }
class ____(AnsiFunction[datetime.datetime]): """The localtime() SQL function.""" type = sqltypes.DateTime() inherit_cache = True
localtime
python
ipython__ipython
IPython/core/shellapp.py
{ "start": 4019, "end": 5150 }
class ____(CaselessStrEnum): """An enum of Matplotlib backend strings where the case should be ignored. Prior to Matplotlib 3.9.0 the list of valid backends is hardcoded in pylabtools.backends. After that, Matplotlib manages backends. The list of valid backends is determined when it is first needed to...
MatplotlibBackendCaselessStrEnum
python
pytorch__pytorch
torch/utils/module_tracker.py
{ "start": 460, "end": 5434 }
class ____: """ ``ModuleTracker`` is a context manager that tracks the nn.Module hierarchy during execution so that other system can query which Module is currently being executed (or its backward is being executed). You can access the ``parents`` attribute on this context manager to get the set of...
ModuleTracker
python
getsentry__sentry
src/sentry/api/endpoints/organization_ai_conversations.py
{ "start": 920, "end": 1770 }
class ____(serializers.Serializer): """Serializer for validating query parameters.""" sort = serializers.CharField(required=False, default="-timestamp") query = serializers.CharField(required=False, allow_blank=True) def validate_sort(self, value): allowed_sorts = { "timestamp", ...
OrganizationAIConversationsSerializer
python
google__jax
jax/experimental/source_mapper/generate_map.py
{ "start": 772, "end": 2129 }
class ____(Protocol): def __call__(self, *args, **kwargs) -> Sequence[common.SourceMapDump]: ... def generate_sourcemaps( f, passes: Sequence[common.Pass], **pass_kwargs ) -> SourceMapGeneratorFn: """Generates a SourceMapBundle for the specified compiler passes. Args: f: The function to com...
SourceMapGeneratorFn
python
walkccc__LeetCode
solutions/2816. Double a Number Represented as a Linked List/2816.py
{ "start": 0, "end": 345 }
class ____: def doubleIt(self, head: ListNode | None) -> ListNode | None: def getCarry(node: ListNode | None) -> ListNode | None: val = node.val * 2 if node.next: val += getCarry(node.next) node.val = val % 10 return val // 10 if getCarry(head) == 1: return ListNode(1, h...
Solution
python
pytorch__pytorch
torch/utils/serialization/config.py
{ "start": 487, "end": 654 }
class ____: compute_crc32: bool = True use_pinned_memory_for_d2h: bool = False storage_alignment: int = 64 _install_config_module(sys.modules[__name__])
save
python
huggingface__transformers
src/transformers/models/clipseg/modeling_clipseg.py
{ "start": 2181, "end": 4055 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): Contrastive loss for image-text similarity. logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`): The scaled dot product scores betwee...
CLIPSegOutput
python
jmcnamara__XlsxWriter
xlsxwriter/test/excel_comparison_test.py
{ "start": 328, "end": 3045 }
class ____(unittest.TestCase): """ Test class for comparing a file created by XlsxWriter against a file created by Excel. """ def __init__(self, *args: Any) -> None: """ Initialize the ExcelComparisonTest instance. Args: *args: Variable arguments passed to unit...
ExcelComparisonTest
python
tornadoweb__tornado
tornado/simple_httpclient.py
{ "start": 1363, "end": 1934 }
class ____(HTTPError): """Error raised by SimpleAsyncHTTPClient when the underlying stream is closed. When a more specific exception is available (such as `ConnectionResetError`), it may be raised instead of this one. For historical reasons, this is a subclass of `.HTTPClientError` which simulates...
HTTPStreamClosedError
python
google__jax
tests/core_test.py
{ "start": 4780, "end": 12794 }
class ____(jtu.JaxTestCase): def test_tree_map(self): xs = ({'a': 1}, [2, 3]) ys = ({'a': 10}, [20, 30]) ys_bad = ({'a': 10, 'b': 10}, [20, 30]) zs = ({'a': 11}, [22, 33]) f = lambda x, y: x + y assert jax.tree.map(f, xs, ys) == zs try: jax.tree.map(f, xs, ys_bad) assert Fals...
CoreTest
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 14415, "end": 14643 }
class ____(serializers.ModelSerializer): children = serializers.PrimaryKeyRelatedField( many=True, queryset=ClassB.objects.all() ) class Meta: model = ClassA fields = '__all__'
ClassASerializer
python
psf__requests
src/requests/models.py
{ "start": 9458, "end": 20950 }
class ____(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request <Request>` object, and should not be instantiated manually; doing so ma...
PreparedRequest
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 14014, "end": 14237 }
class ____(models.Model): field_to_update = models.BooleanField(default=True) custom_modified = ModificationDateTimeField() class Meta: app_label = "django_extensions"
CustomModelModificationDateTimeField
python
kamyu104__LeetCode-Solutions
Python/height-of-binary-tree-after-subtree-removal-queries.py
{ "start": 159, "end": 1504 }
class ____(object): def treeQueries(self, root, queries): """ :type root: Optional[TreeNode] :type queries: List[int] :rtype: List[int] """ def iter_dfs(root): top = collections.defaultdict(lambda: [0]*2) depth, height = {}, {} stk ...
Solution
python
TheAlgorithms__Python
hashes/sha256.py
{ "start": 574, "end": 5730 }
class ____: """ Class to contain the entire pipeline for SHA1 Hashing Algorithm >>> SHA256(b'Python').hash '18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db' >>> SHA256(b'hello world').hash 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9' """ def __in...
SHA256
python
catalyst-team__catalyst
examples/reinforcement_learning/dqn.py
{ "start": 1539, "end": 4481 }
class ____(IterableDataset): def __init__(self, buffer: ReplayBuffer, epoch_size: int = int(1e3)): self.buffer = buffer self.epoch_size = epoch_size def __iter__(self) -> Iterator[Sequence[np.array]]: states, actions, rewards, dones, next_states = self.buffer.sample( self.ep...
ReplayDataset
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 8539, "end": 9202 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws assert len(args) == 2 error_msg = "DatetimeMinMax requires both arguments to be NPDatetime type or both arguments to be NPTimedelta types" assert isinstance(args[0], (types.NPDatetime, types.NPTimedelta)), err...
DatetimeMinMax
python
huggingface__transformers
examples/modular-transformers/modeling_dummy_bert.py
{ "start": 20536, "end": 21103 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden stat...
DummyBertPooler
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/posts_response_builder.py
{ "start": 357, "end": 758 }
class ____(HttpResponseBuilder): @classmethod def posts_response(cls, request_without_cursor_for_pagination: Optional[HttpRequest] = None) -> "PostsResponseBuilder": return cls( find_template("posts", __file__), FieldPath("posts"), CursorBasedPaginationStrategy(http_r...
PostsResponseBuilder
python
sqlalchemy__sqlalchemy
test/orm/test_events.py
{ "start": 62212, "end": 72031 }
class ____(RemoveORMEventsGlobally, _fixtures.FixtureTest): """test event listeners against unmapped classes. This incurs special logic. Note if we ever do the "remove" case, it has to get all of these, too. """ run_inserts = None def test_deferred_map_event(self): """ 1. ma...
DeferredMapperEventsTest
python
Textualize__textual
src/textual/widgets/_pretty.py
{ "start": 227, "end": 1379 }
class ____(Widget): """A pretty-printing widget. Used to pretty-print any object. """ DEFAULT_CSS = """ Pretty { height: auto; } """ def __init__( self, object: Any, *, name: str | None = None, id: str | None = None, classes: str...
Pretty
python
SmileyChris__easy-thumbnails
easy_thumbnails/processors.py
{ "start": 1097, "end": 14137 }
class ____: def __new__(cls, im): if getattr(im, "n_frames", 1) > 1: return super().__new__(cls) return im def __init__(self, im): self.im = im def apply_to_frames(self, method, *args, **kwargs): new_frames = [] for i in range(self.im.n_frames): ...
FrameAware
python
django__django
tests/backends/models.py
{ "start": 582, "end": 711 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().exclude(year=1000)
SchoolClassManager
python
neetcode-gh__leetcode
python/2306-naming-a-company.py
{ "start": 0, "end": 927 }
class ____(object): def distinctNames(self, ideas): suffixes = dict() for idea in ideas: if idea[0] not in suffixes: suffixes[idea[0]] = set() suffixes[idea[0]].add(idea[1:]) if len(suffixes) < 2: return 0 num_distinct_names = 0...
Solution
python
ray-project__ray
python/ray/exceptions.py
{ "start": 27322, "end": 27449 }
class ____(RayError, TimeoutError): """Indicates that a call to the worker timed out.""" pass @PublicAPI
GetTimeoutError
python
google__jax
jax/_src/interpreters/mlir.py
{ "start": 8340, "end": 21064 }
class ____(Protocol): def __call__(self, val: Any, aval: core.AbstractValue | None) -> IrValues: """Builds an IR representation for a constant `val`. A JAX value is represented by zero or more IR values.""" _constant_handlers : dict[type, ConstantHandler] = {} def register_constant_handler(type_: type, han...
ConstantHandler
python
numpy__numpy
numpy/_core/tests/test_indexing.py
{ "start": 53063, "end": 53401 }
class ____: """An index can only have a single ellipsis. """ def test_basic(self): a = np.arange(10) assert_raises(IndexError, lambda: a[..., ...]) assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 2,)) assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))
TestMultipleEllipsisError
python
google__jax
jax/_src/pallas/mosaic_gpu/core.py
{ "start": 46599, "end": 48117 }
class ____: """Represents a mesh over individual warps within a warpgroup. When used in conjunction with `core_map`, the warp ID will be visible within the body of the wrapped scope by querying `lax.axis_index` with the specified axis name. """ _NUM_WARPS_PER_WARPGROUP: ClassVar[int] = 4 axis_name: str ...
WarpMesh