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
doocs__leetcode
solution/3300-3399/3385.Minimum Time to Break Locks II/Solution.py
{ "start": 0, "end": 3884 }
class ____: class Edge(NamedTuple): src: int dst: int cap: int flow: int cost: int class _Edge: def __init__(self, dst: int, cap: int, cost: int) -> None: self.dst = dst self.cap = cap self.cost = cost self.rev: Opt...
MCFGraph
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 14453, "end": 21087 }
class ____(test_util.TensorFlowTestCase): def testReverse0DimAuto(self): x_np = 4 for use_gpu in [False, True]: with self.subTest(use_gpu=use_gpu): with self.cached_session(use_gpu=use_gpu): x_tf = self.evaluate(array_ops.reverse_v2(x_np, [])) self.assertAllEqual(x_tf, x_np)...
ReverseV2Test
python
falconry__falcon
falcon/asgi/stream.py
{ "start": 877, "end": 17942 }
class ____: """File-like input object for reading the body of the request, if any. This class implements coroutine functions for asynchronous reading or iteration, but otherwise provides an interface similar to that defined by :class:`io.IOBase`. If the request includes a Content-Length header, th...
BoundedStream
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/core.py
{ "start": 4537, "end": 4765 }
class ____: args: Any kwargs: Any # Plus two optional arguments for .xfail() raises: Any = field(default=None) reason: Any = field(default=None) # TODO_DOCS link to not-yet-existent patch-dumping docs
Example
python
ray-project__ray
python/ray/serve/_private/version.py
{ "start": 486, "end": 9283 }
class ____: def __init__( self, code_version: Optional[str], deployment_config: DeploymentConfig, ray_actor_options: Optional[Dict], placement_group_bundles: Optional[List[Dict[str, float]]] = None, placement_group_strategy: Optional[str] = None, max_replicas_...
DeploymentVersion
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/struct_store/sql.py
{ "start": 928, "end": 991 }
class ____(str, Enum): SQL = "sql" NL = "nl"
SQLQueryMode
python
walkccc__LeetCode
solutions/36. Valid Sudoku/36.py
{ "start": 0, "end": 535 }
class ____: def isValidSudoku(self, board: list[list[str]]) -> bool: seen = set() for i in range(9): for j in range(9): c = board[i][j] if c == '.': continue if (c + '@row ' + str(i) in seen or c + '@col ' + str(j) in seen or c + '@box ' + s...
Solution
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 44280, "end": 44532 }
class ____: """ Entry type for a negative cache entry. """ reason: str if TYPE_CHECKING: _DispatchCacheEntry = Union[_DispatchCacheValidEntry, _DispatchCacheBypassEntry] @dataclass(frozen=True, slots=True)
_DispatchCacheBypassEntry
python
doocs__leetcode
solution/1500-1599/1584.Min Cost to Connect All Points/Solution.py
{ "start": 0, "end": 795 }
class ____: def minCostConnectPoints(self, points: List[List[int]]) -> int: n = len(points) g = [[0] * n for _ in range(n)] dist = [inf] * n vis = [False] * n for i, (x1, y1) in enumerate(points): for j in range(i + 1, n): x2, y2 = points[j] ...
Solution
python
django__django
tests/fixtures_regress/models.py
{ "start": 615, "end": 847 }
class ____(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, models.SET_NULL, null=True) def __str__(self): return self.name + " is owned by " + str(self.owner)
Stuff
python
plotly__plotly.py
plotly/graph_objs/cone/colorbar/_tickfont.py
{ "start": 233, "end": 9903 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "cone.colorbar" _path_str = "cone.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @pro...
Tickfont
python
ijl__orjson
test/test_fragment.py
{ "start": 209, "end": 3001 }
class ____: def test_fragment_fragment_eq(self): assert orjson.Fragment(b"{}") != orjson.Fragment(b"{}") def test_fragment_fragment_not_mut(self): fragment = orjson.Fragment(b"{}") with pytest.raises(AttributeError): fragment.contents = b"[]" assert orjson.dumps(frag...
TestFragment
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/formatters/other.py
{ "start": 3983, "end": 5034 }
class ____(Formatter): """ Format tokens as appropriate for a new testcase. .. versionadded:: 2.0 """ name = 'Testcase' aliases = ['testcase'] def __init__(self, **options): Formatter.__init__(self, **options) if self.encoding is not None and self.encoding != 'utf-8': ...
TestcaseFormatter
python
ashishps1__awesome-system-design-resources
implementations/python/load_balancing_algorithms/ip_hash.py
{ "start": 16, "end": 569 }
class ____(): def __init__(self, servers): self.servers = servers def get_next_server(self, client_ip): hash_value = hashlib.md5(client_ip.encode()).hexdigest() index = int(hash_value, 16) % len(self.servers) return self.servers[index] # Example usage servers = ["Server1", "Ser...
IPHash
python
huggingface__transformers
tests/cli/test_serve.py
{ "start": 35381, "end": 35977 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.port = 8042 thread = Thread(target=Serve, kwargs={"port": cls.port}) thread.daemon = True thread.start() def test_healthcheck(self): """Tests that the healthcheck endpoint works.""" response...
ServeInfrastructureTest
python
ansible__ansible
lib/ansible/plugins/shell/__init__.py
{ "start": 1148, "end": 1351 }
class ____: """Internal type returned by shell subsystems that may require both an execution payload and a command (eg powershell).""" command: str input_data: bytes | None = None
_ShellCommand
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_trace.py
{ "start": 28170, "end": 35424 }
class ____(OrganizationEventsV2EndpointBase): publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get_projects( self, request: HttpRequest, organization: Organization | RpcOrganization, force_global_perms: bool = False, include_all_accessible: bool = Fa...
OrganizationEventsTraceEndpointBase
python
celery__celery
t/unit/app/test_app.py
{ "start": 60243, "end": 60541 }
class ____: def test_strtobool(self): for s in ('false', 'no', '0'): assert not defaults.strtobool(s) for s in ('true', 'yes', '1'): assert defaults.strtobool(s) with pytest.raises(TypeError): defaults.strtobool('unsure')
test_defaults
python
pandas-dev__pandas
asv_bench/benchmarks/algos/isin.py
{ "start": 3130, "end": 3809 }
class ____: params = [ [np.float64, np.object_], [ 1_300, 2_000, 7_000, 8_000, 70_000, 80_000, 750_000, 900_000, ], ["inside", "outside"], ] param_names = ["dtype", "size", "title"...
IsinWithRandomFloat
python
pandas-dev__pandas
pandas/core/indexes/datetimelike.py
{ "start": 13038, "end": 29219 }
class ____(DatetimeIndexOpsMixin, ABC): """ Mixin class for methods shared by DatetimeIndex and TimedeltaIndex, but not PeriodIndex """ _data: DatetimeArray | TimedeltaArray _comparables = ["name", "freq"] _attributes = ["name", "freq"] # Compat for frequency inference, see GH#23789 ...
DatetimeTimedeltaMixin
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_base_aws.py
{ "start": 2315, "end": 5435 }
class ____: def test_default_parameters(self): op = FakeDynamoDBSensor(task_id="fake_task_id") msg = "Attention! Changes in default parameters might produce breaking changes in multiple sensors" assert op.aws_conn_id == "aws_default", msg assert op.region_name is None, msg as...
TestAwsBaseSensor
python
apache__airflow
providers/google/tests/integration/google/cloud/transfers/test_mssql_to_gcs.py
{ "start": 1468, "end": 3419 }
class ____: def setup_method(self): os.environ["AIRFLOW_CONN_MSSQL_DEFAULT"] = AIRFLOW_CONN_MSSQL_DEFAULT hook = MsSqlHook() conn = hook.get_conn() hook.set_autocommit(conn, True) self.cursor = conn.cursor() self.cursor.execute(f"""CREATE TABLE {TEST_TABLE_ID} ( ...
TestMsSqlToGoogleCloudStorageOperator
python
realpython__materials
dwitter-part-1/source_code_final/dwitter/apps.py
{ "start": 36, "end": 146 }
class ____(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "dwitter"
DwitterConfig
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/dynamic_partitions_request.py
{ "start": 227, "end": 939 }
class ____( NamedTuple( "_AddDynamicPartitionsRequest", [ ("partitions_def_name", str), ("partition_keys", Sequence[str]), ], ) ): """A request to add partitions to a dynamic partitions definition, to be evaluated by a sensor or schedule.""" def __new__( ...
AddDynamicPartitionsRequest
python
fastai__fastai
fastai/medical/imaging.py
{ "start": 1475, "end": 1670 }
class ____(TensorImage): "Inherits from `TensorImage` and converts the `pixel_array` into a `TensorDicom`" _show_args = {'cmap':'gray'} # %% ../../nbs/60_medical.imaging.ipynb 15
TensorDicom
python
walkccc__LeetCode
solutions/411. Minimum Unique Word Abbreviation/411.py
{ "start": 0, "end": 1704 }
class ____: def minAbbreviation(self, target: str, dictionary: list[str]) -> str: m = len(target) def getMask(word: str) -> int: # mask[i] = 0 := target[i] == word[i] # mask[i] = 1 := target[i] != word[i] # e.g. target = "apple" # word = "blade" # mask = 11110 ...
Solution
python
django__django
tests/test_runner/tests.py
{ "start": 27882, "end": 28367 }
class ____(unittest.TestCase): def test_setup_databases(self): """ setup_databases() doesn't fail with dummy database backend. """ tested_connections = db.ConnectionHandler({}) with mock.patch("django.test.utils.connections", new=tested_connections): runner_instan...
DummyBackendTest
python
ray-project__ray
python/ray/air/util/object_extensions/pandas.py
{ "start": 414, "end": 3461 }
class ____(pd.api.extensions.ExtensionArray): """Implements the Pandas extension array interface for the Arrow object array""" def __init__(self, values: collections.abc.Iterable[typing.Any]): vals = list(values) self.values = np.empty(len(vals), dtype=object) self.values[:] = vals ...
PythonObjectArray
python
PrefectHQ__prefect
src/prefect/blocks/abstract.py
{ "start": 3877, "end": 4917 }
class ____(ABC, Generic[T]): # not a block """ Represents a job run in an external system. Allows waiting for the job run's completion and fetching its results. """ @property def logger(self) -> LoggerOrAdapter: """ Returns a logger based on whether the JobRun is called...
JobRun
python
ApeWorX__ape
src/ape_console/plugin.py
{ "start": 545, "end": 3205 }
class ____(Magics): @cached_property def ipython(self): if ipython := get_ipython(): return ipython raise ValueError("Must be called from an IPython session.") @line_magic def ape(self, line: str = ""): """ Run Ape CLI commands within an ``ape console`` sess...
ApeConsoleMagics
python
catalyst-team__catalyst
catalyst/callbacks/control_flow.py
{ "start": 1435, "end": 3628 }
class ____: def __init__(self, loaders: LOADERS, reverse_condition: bool): if isinstance(loaders, str): loaders = [loaders] if not isinstance(loaders, (list, tuple, dict, OrderedDict)): raise ValueError( "'loaders' type should be one of - str, " ...
_LoaderFilterFn
python
django__django
tests/migrations/test_writer.py
{ "start": 1745, "end": 1826 }
class ____(enum.Enum): A = _("a-value") B = _("value-b")
TextTranslatedEnum
python
numba__numba
numba/typed/dictobject.py
{ "start": 2215, "end": 2638 }
class ____(models.StructModel): def __init__(self, dmm, fe_type): members = [ ('meminfo', _meminfo_dictptr), ('data', types.voidptr), # ptr to the C dict ] super(DictModel, self).__init__(dmm, fe_type, members) @register_model(DictItemsIterableType) @register_mode...
DictModel
python
django__django
tests/serializers/models/base.py
{ "start": 3814, "end": 3887 }
class ____(models.Model): parent_data = models.IntegerField()
BaseModel
python
django__django
tests/admin_views/admin.py
{ "start": 12755, "end": 12804 }
class ____(admin.ModelAdmin): pass
PictureAdmin
python
pyodide__pyodide
tools/backport.py
{ "start": 8441, "end": 11639 }
class ____: """The changelog information for a particular release of Pyodide. Introduced by ##. Ends when there is a ##. header: Other than the unreleased section we don't actually bother parsing out the changelog. So for the "prelude" and "rest" sections, this is actually all the ...
ChangelogVersion
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec20.py
{ "start": 746, "end": 1031 }
class ____(Generic[P2]): def __init__(self, cb: Callable[P2, Any]) -> None: ... def m1(self) -> X[int, Concatenate[float, P2]]: ... y1 = Y(x4) reveal_type(y1, expected_text="Y[(x: X[int, ...])]") y2 = y1.m1() reveal_type(y2, expected_text="X[int, (float, x: X[int, ...])]")
Y
python
realpython__materials
python-unittest/test_even.py
{ "start": 384, "end": 843 }
class ____(unittest.TestCase): def test_even_number(self): for number in [2, 4, 6, -8, -10, -12]: with self.subTest(number=number): self.assertEqual(is_even(number), True) def test_odd_number(self): for number in [1, 3, 5, -7, -9, -11]: with self.subTest(...
TestIsEven
python
Pylons__pyramid
src/pyramid/authorization.py
{ "start": 1016, "end": 1058 }
class ____(_ACLAllowed): pass
ACLAllowed
python
kamyu104__LeetCode-Solutions
Python/design-log-storage-system.py
{ "start": 169, "end": 905 }
class ____(object): def __init__(self): self.__logs = [] self.__granularity = {'Year': 4, 'Month': 7, 'Day': 10, \ 'Hour': 13, 'Minute': 16, 'Second': 19} def put(self, id, timestamp): """ :type id: int :type timestamp: str :rtype:...
LogSystem
python
google__pytype
pytype/pyi/parser_test.py
{ "start": 66972, "end": 68102 }
class ____(parser_test_base.ParserTestBase): def test_import(self): self.check( """ import mod # type: ignore def f(x: mod.attr) -> None: ... """, """ import mod def f(x: mod.attr) -> None: ...""", ) def test_from_import(self): src = textwrap.dedent(""" ...
ImportTypeIgnoreTest
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 58985, "end": 68710 }
class ____(PatchTSMixerPreTrainedModel): r""" `PatchTSMixer` for forecasting application. Args: config (`PatchTSMixerConfig`): Configuration. Returns: `None`. """ def __init__(self, config: PatchTSMixerConfig): super().__init__(config) self.loss = c...
PatchTSMixerForPrediction
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_basic.py
{ "start": 4640, "end": 5893 }
class ____(fixtures.DeclarativeMappedTest): __sparse_driver_backend__ = True @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(Base): __tablename__ = "a" id = Column( Integer, primary_key=True, test_needs_autoincrement=True ...
ColExpressionsTest
python
numpy__numpy
numpy/_core/_ufunc_config.py
{ "start": 10716, "end": 15130 }
class ____: """ errstate(**kwargs) Context manager for floating-point error handling. Using an instance of `errstate` as a context manager allows statements in that context to execute with a known error handling behavior. Upon entering the context the error handling is set with `seterr` and `s...
errstate
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/angle_helper.py
{ "start": 8798, "end": 9446 }
class ____(FormatterDMS): deg_mark = r"^\mathrm{h}" min_mark = r"^\mathrm{m}" sec_mark = r"^\mathrm{s}" fmt_d = "$%d" + deg_mark + "$" fmt_ds = r"$%d.%s" + deg_mark + "$" # %s for sign fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark+"$" fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s...
FormatterHMS
python
TheAlgorithms__Python
data_structures/binary_tree/is_sum_tree.py
{ "start": 332, "end": 1726 }
class ____: data: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: """ >>> root = Node(2) >>> list(root) [2] >>> root.left = Node(1) >>> tuple(root) (1, 2) """ if self.left: yi...
Node
python
doocs__leetcode
lcof/面试题24. 反转链表/Solution.py
{ "start": 136, "end": 418 }
class ____: def reverseList(self, head: ListNode) -> ListNode: dummy = ListNode() curr = head while curr: next = curr.next curr.next = dummy.next dummy.next = curr curr = next return dummy.next
Solution
python
openai__openai-python
src/openai/resources/chat/chat.py
{ "start": 1382, "end": 2314 }
class ____(AsyncAPIResource): @cached_property def completions(self) -> AsyncCompletions: return AsyncCompletions(self._client) @cached_property def with_raw_response(self) -> AsyncChatWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return ...
AsyncChat
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 13346, "end": 24071 }
class ____(torch.nn.Module): def forward(self, getitem_12: "f32[8]", getitem_11: "f32[8]", getitem_10: "f32[8]", getitem_15: "f32[8]", getitem_14: "f32[8]", getitem_13: "f32[8]", tangents_1: "f32[8]"): partitioned_bw_subgraph_0_1 = self.partitioned_bw_subgraph_0_0 invoke_subgraph_7 = torch.ops.highe...
GraphModule
python
facelessuser__pymdown-extensions
pymdownx/util.py
{ "start": 5050, "end": 11220 }
class ____(InlineProcessor): """Processor for handling complex nested patterns such as strong and em matches.""" PATTERNS = [] # type: list[PatSeqItem] def build_single(self, m: re.Match[str], tag: str, full_recursion: bool, idx: int) -> etree.Element: """Return single tag.""" el1 = etree...
PatternSequenceProcessor
python
pytorch__pytorch
test/distributed/checkpoint/test_checkpoint.py
{ "start": 1533, "end": 2298 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.sharded: ShardedTensor = sharded_tensor.zeros(self.spec(), 4, 4) self.regular = torch.nn.Parameter(torch.ones(4, 4)) self.extra_sharded: Optional[ShardedTensor] = None self.extra_param: Optional[...
TestModule
python
pydata__xarray
xarray/tests/test_indexing.py
{ "start": 18855, "end": 19719 }
class ____: def test_setitem(self) -> None: original = np.arange(10) wrapped = indexing.CopyOnWriteArray(original) wrapped[B[:]] = 0 assert_array_equal(original, np.arange(10)) assert_array_equal(wrapped, np.zeros(10)) def test_sub_array(self) -> None: original =...
TestCopyOnWriteArray
python
google__jax
docs/autodidax2_part1.py
{ "start": 7205, "end": 8572 }
class ____: primal : float tangent : float def add_dual(x : DualNumber, y: DualNumber) -> DualNumber: return DualNumber(x.primal + y.primal, x.tangent + y.tangent) def mul_dual(x : DualNumber, y: DualNumber) -> DualNumber: return DualNumber(x.primal * y.primal, x.primal * y.tangent + x.tangent * y.primal) d...
DualNumber
python
Pylons__pyramid
tests/test_traversal.py
{ "start": 19182, "end": 20595 }
class ____(unittest.TestCase): def _callFUT(self, context, iface): from pyramid.traversal import find_interface return find_interface(context, iface) def test_it_interface(self): baz = DummyContext() bar = DummyContext(baz) foo = DummyContext(bar) root = DummyCo...
FindInterfaceTests
python
cookiecutter__cookiecutter
cookiecutter/extensions.py
{ "start": 447, "end": 883 }
class ____(Extension): """Jinja2 extension to convert a Python object to JSON.""" def __init__(self, environment: Environment) -> None: """Initialize the extension with the given environment.""" super().__init__(environment) def jsonify(obj: Any, indent: int = 4) -> str: re...
JsonifyExtension
python
ipython__ipython
IPython/core/magics/execution.py
{ "start": 1733, "end": 3632 }
class ____: """ Object returned by the timeit magic with info about the run. Contains the following attributes: loops: int number of loops done per measurement repeat: int number of times the measurement was repeated best: float best execution time / number all_runs : ...
TimeitResult
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 139494, "end": 154106 }
class ____(FieldChannelMixin, core.FieldDefWithoutScale): r""" Detail schema wrapper. Definition object for a data field, its type and transformation of an encoding channel. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, a...
Detail
python
dagster-io__dagster
examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_airbyte_utils.py
{ "start": 2735, "end": 3026 }
class ____(AirbyteWorkspaceComponent): workspace: Annotated[ MockAirbyteWorkspace, dg.Resolver( lambda context, model: MockAirbyteWorkspace( **resolve_fields(model, MockAirbyteWorkspace, context) ) ), ]
MockAirbyteComponent
python
python-attrs__attrs
tests/test_functional.py
{ "start": 1280, "end": 1317 }
class ____(type): pass @attr.s
Meta
python
pyqtgraph__pyqtgraph
pyqtgraph/flowchart/library/Operators.py
{ "start": 438, "end": 2032 }
class ____(CtrlNode): """Generic node for performing any operation like A.fn(B)""" _dtypes = [ 'float64', 'float32', 'float16', 'int64', 'int32', 'int16', 'int8', 'uint64', 'uint32', 'uint16', 'uint8' ] uiTemplate = [ ('outputType', 'combo', {'values': ['no change', 'in...
BinOpNode
python
pypa__pip
tests/unit/test_base_command.py
{ "start": 1613, "end": 1919 }
class ____(FakeCommand): _name = "fake_unicode" def run(self, options: Values, args: list[str]) -> int: logging.getLogger("pip.tests").info(b"bytes here \xe9") logging.getLogger("pip.tests").info(b"unicode here \xc3\xa9".decode("utf-8")) return SUCCESS
FakeCommandWithUnicode
python
numba__numba
numba/cuda/codegen.py
{ "start": 11350, "end": 12174 }
class ____(Codegen): """ This codegen implementation for CUDA only generates optimized LLVM IR. Generation of PTX code is done separately (see numba.cuda.compiler). """ _library_class = CUDACodeLibrary def __init__(self, module_name): pass def _create_empty_module(self, name): ...
JITCUDACodegen
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_data_bar01.py
{ "start": 345, "end": 2077 }
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
zarr-developers__zarr-python
tests/test_dtype/test_npy/test_float.py
{ "start": 3383, "end": 6346 }
class ____(_BaseTestFloat): test_cls = Float64 valid_dtype = (np.dtype(">f8"), np.dtype("<f8")) invalid_dtype = ( np.dtype(np.int8), np.dtype(np.uint16), np.dtype(np.float32), ) valid_json_v2 = ( {"name": ">f8", "object_codec_id": None}, {"name": "<f8", "objec...
TestFloat64
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 143480, "end": 143963 }
class ____(sgqlc.types.Input): """Autogenerated input type of ApproveVerifiableDomain""" __schema__ = github_schema __field_names__ = ("id", "client_mutation_id") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") """The ID of the verifiable domain to approve.""" client_mutati...
ApproveVerifiableDomainInput
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/sensors.py
{ "start": 7996, "end": 8684 }
class ____(graphene.Mutation): """Enable a sensor to launch runs for a job based on external state change.""" Output = graphene.NonNull(GrapheneSensorOrError) class Arguments: sensor_selector = graphene.NonNull(GrapheneSensorSelector) class Meta: name = "StartSensorMutation" @cap...
GrapheneStartSensorMutation
python
realpython__materials
python-enum/comparison.py
{ "start": 149, "end": 592 }
class ____(Enum): RED = 1 YELLOW = 2 GREEN = 3 PEDESTRIAN_RED = 1 PEDESTRIAN_GREEN = 3 red = AtlanticAveSemaphore.RED print(f"{red is AtlanticAveSemaphore.RED = }") print(f"{red is not AtlanticAveSemaphore.RED = }") yellow = AtlanticAveSemaphore.YELLOW print(f"{yellow is red = }") print(f"{yellow...
EighthAveSemaphore
python
walkccc__LeetCode
solutions/1406. Stone Game III/1406.py
{ "start": 0, "end": 586 }
class ____: def stoneGameIII(self, stoneValue: list[int]) -> str: @functools.lru_cache(None) def dp(i: int) -> int: """ Returns the maximum relative score Alice can make with stoneValue[i..n). """ if i == len(stoneValue): return 0 res = -math.inf summ = 0 fo...
Solution
python
django__django
tests/view_tests/views.py
{ "start": 10391, "end": 10837 }
class ____(ExceptionReporter): html_template_path = TEMPLATES_PATH / "my_technical_500.html" text_template_path = TEMPLATES_PATH / "my_technical_500.txt" def custom_reporter_class_view(request): request.exception_reporter_class = CustomExceptionReporter try: raise Exception except Exceptio...
TemplateOverrideExceptionReporter
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/view_resolve_conflict_middle/package.py
{ "start": 228, "end": 682 }
class ____(Package): """See view-resolve-conflict-top""" has_code = False version("0.1.0") depends_on("view-file") def install(self, spec, prefix): bottom = spec["view-file"].prefix os.mkdir(os.path.join(prefix, "bin")) os.symlink(os.path.join(bottom, "bin", "x"), os.path....
ViewResolveConflictMiddle
python
apache__airflow
providers/databricks/tests/unit/databricks/hooks/test_databricks.py
{ "start": 56979, "end": 58426 }
class ____: def test_is_terminal_true(self): terminal_states = ["TERMINATING", "TERMINATED", "ERROR", "UNKNOWN"] for state in terminal_states: cluster_state = ClusterState(state, "") assert cluster_state.is_terminal def test_is_terminal_false(self): non_terminal_...
TestClusterState
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_type_lookup.py
{ "start": 12314, "end": 12674 }
class ____(AbstractFoo): def __init__(self, x: int): pass def qux(self): pass @given(st.from_type(AbstractFoo)) def test_gen_abstract(foo): # This requires that we correctly checked which of the subclasses # could be resolved, rather than unconditionally using all of them. assert ...
ConcreteFoo2
python
kamyu104__LeetCode-Solutions
Python/knight-dialer.py
{ "start": 51, "end": 1240 }
class ____(object): def knightDialer(self, N): """ :type N: int :rtype: int """ def matrix_expo(A, K): result = [[int(i==j) for j in xrange(len(A))] \ for i in xrange(len(A))] while K: if K % 2: ...
Solution
python
pytorch__pytorch
torch/optim/rmsprop.py
{ "start": 551, "end": 20612 }
class ____(Optimizer): # noqa: D101 def __init__( self, params: ParamsT, lr: Union[float, Tensor] = 1e-2, alpha: float = 0.99, eps: float = 1e-8, weight_decay: float = 0, momentum: float = 0, centered: bool = False, capturable: bool = False, ...
RMSprop
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/xcom.py
{ "start": 2545, "end": 2705 }
class ____(BaseModel): """XCom Collection serializer for responses.""" xcom_entries: Iterable[XComResponse] total_entries: int
XComCollectionResponse
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 11445, "end": 12236 }
class ____(OpError): """Raised when an entity that we attempted to create already exists. An API raises this this error to avoid overwriting an existing resource, value, etc. Calling a creation API multiple times with the same arguments could raise this error if the creation API is not idempotent. For examp...
AlreadyExistsError
python
explosion__spaCy
spacy/training/corpus.py
{ "start": 10169, "end": 11978 }
class ____: """Iterate Example objects from a file or directory of plain text UTF-8 files with one line per doc. path (Path): The directory or filename to read from. min_length (int): Minimum document length (in tokens). Shorter documents will be skipped. Defaults to 0, which indicates no limit...
PlainTextCorpus
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 67051, "end": 67395 }
class ____(sgqlc.types.Enum): """Properties by which pull_requests connections can be ordered. Enumeration Choices: * `CREATED_AT`: Order pull_requests by creation time * `UPDATED_AT`: Order pull_requests by update time """ __schema__ = github_schema __choices__ = ("CREATED_AT", "UPDATED_...
PullRequestOrderField
python
redis__redis-py
redis/connection.py
{ "start": 21483, "end": 43693 }
class ____(MaintNotificationsAbstractConnection, ConnectionInterface): "Manages communication to and from a Redis server" def __init__( self, db: int = 0, password: Optional[str] = None, socket_timeout: Optional[float] = None, socket_connect_timeout: Optional[float] = No...
AbstractConnection
python
readthedocs__readthedocs.org
readthedocs/search/tests/test_api.py
{ "start": 27237, "end": 27296 }
class ____(BaseTestDocumentSearch): pass
TestDocumentSearch
python
realpython__materials
syntactic-sugar-python/twice.py
{ "start": 0, "end": 254 }
class ____: def __init__(self, items): self.items = list(items) def __iter__(self): yield from self.items print("Halfway there!") yield from self.items for number in Twice([1, 2, 3]): print(f"-> {number}")
Twice
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 319845, "end": 320595 }
class ____: def test_edge_cases(self): with np.errstate(all='raise'): assert_equal(stats.triang.pdf(0, 0), 2.) assert_equal(stats.triang.pdf(0.5, 0), 1.) assert_equal(stats.triang.pdf(1, 0), 0.) assert_equal(stats.triang.pdf(0, 1), 0) assert_equal...
TestTriang
python
PrefectHQ__prefect
tests/server/orchestration/api/test_work_queues.py
{ "start": 20863, "end": 21478 }
class ____: async def test_read_work_queue(self, client, work_queue): response = await client.get(f"/work_queues/{work_queue.id}") assert response.status_code == status.HTTP_200_OK assert response.json()["id"] == str(work_queue.id) assert response.json()["name"] == work_queue.name ...
TestReadWorkQueue
python
coleifer__peewee
peewee.py
{ "start": 57080, "end": 59627 }
class ____(Node): def __init__(self, action=None, update=None, preserve=None, where=None, conflict_target=None, conflict_where=None, conflict_constraint=None): self._action = action self._update = update self._preserve = ensure_tuple(preserve) self._...
OnConflict
python
neetcode-gh__leetcode
python/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.py
{ "start": 56, "end": 450 }
class ____: def numSubseq(self, nums: List[int], target: int) -> int: nums.sort() res, mod = 0, (10**9 + 7) left, right = 0, len(nums) - 1 while left <= right: if (nums[left] + nums[right]) > target: right -= 1 else: res += 1...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster_tests/core_tests/test_data_time.py
{ "start": 7137, "end": 16809 }
class ____(NamedTuple): before_partitions: list[str] after_partitions: list[str] expected_time: Optional[datetime.datetime] scenarios = { "empty": PartitionedDataTimeScenario( before_partitions=[], after_partitions=[], expected_time=None, ), "first_missing": Partitioned...
PartitionedDataTimeScenario
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 77893, "end": 81981 }
class ____(Emulated, _AbstractInterval, TypeDecorator[dt.timedelta]): """A type for ``datetime.timedelta()`` objects. The Interval type deals with ``datetime.timedelta`` objects. In PostgreSQL and Oracle Database, the native ``INTERVAL`` type is used; for others, the value is stored as a date which is...
Interval
python
apache__airflow
airflow-core/src/airflow/models/team.py
{ "start": 1742, "end": 3411 }
class ____(Base): """ Contains the list of teams defined in the environment. This table is only used when Airflow is run in multi-team mode. """ __tablename__ = "team" id: Mapped[str] = mapped_column(UUIDType(binary=False), primary_key=True, default=uuid6.uuid7) name: Mapped[str] = mapped...
Team
python
PyCQA__bandit
tests/unit/core/test_config.py
{ "start": 3500, "end": 8565 }
class ____(testtools.TestCase): sample = textwrap.dedent( """ profiles: test_1: include: - any_other_function_with_shell_equals_true - assert_used exclude: test_2: include: ...
TestConfigCompat
python
keon__algorithms
tests/test_dp.py
{ "start": 2528, "end": 3535 }
class ____(unittest.TestCase): """[summary] Test for the file hosoya_triangle Arguments: unittest {[type]} -- [description] """ def test_hosoya(self): self.assertEqual([1], hosoya_testing(1)) self.assertEqual([1, 1, 1, 2, 1,...
TestHosoyaTriangle
python
doocs__leetcode
solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/Solution.py
{ "start": 192, "end": 820 }
class ____: def maxProduct(self, root: Optional[TreeNode]) -> int: def sum(root: Optional[TreeNode]) -> int: if root is None: return 0 return root.val + sum(root.left) + sum(root.right) def dfs(root: Optional[TreeNode]) -> int: if root is None: ...
Solution
python
neetcode-gh__leetcode
python/2348-number-of-zero-filled-subarrays.py
{ "start": 0, "end": 596 }
class ____(object): def zeroFilledSubarray(self, nums): # check if there are any Zeros in the list res = nums.count(0) if res == 0: return 0 r = 0 l = len(nums) while r < l: Temp_Subarray=[] while r < l and nums[r] == ...
Solution
python
huggingface__transformers
src/transformers/models/sam3_tracker/modular_sam3_tracker.py
{ "start": 5294, "end": 5356 }
class ____(Sam2PromptEncoder): pass
Sam3TrackerPromptEncoder
python
lazyprogrammer__machine_learning_examples
supervised_class/app.py
{ "start": 571, "end": 676 }
class ____(tornado.web.RequestHandler): def get(self): self.write("Hello, Tornado!")
MainHandler
python
nedbat__coveragepy
tests/test_setup.py
{ "start": 371, "end": 1968 }
class ____(CoverageTest): """Tests of setup.py""" run_in_temp_dir = False def setUp(self) -> None: super().setUp() # Force the most restrictive interpretation. self.set_environ("LC_ALL", "C") def test_metadata(self) -> None: status, output = self.run_command_status( ...
SetupPyTest
python
neetcode-gh__leetcode
python/0707-design-linked-list.py
{ "start": 0, "end": 119 }
class ____: def __init__(self, val): self.val = val self.prev = None self.next = None
ListNode
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis27.py
{ "start": 315, "end": 1476 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis27.xlsx") self.ignore_elements = {"xl/charts/chart1.xml": ["<a:defRPr"]} def test_create_file(self): """Test the creatio...
TestCompareXLSXFiles
python
python-openxml__python-docx
src/docx/text/font.py
{ "start": 373, "end": 13604 }
class ____(ElementProxy): """Proxy object for parent of a `<w:rPr>` element and providing access to character properties such as font name, font size, bold, and subscript.""" def __init__(self, r: CT_R, parent: Any | None = None): super().__init__(r, parent) self._element = r self._...
Font
python
doocs__leetcode
solution/0200-0299/0248.Strobogrammatic Number III/Solution.py
{ "start": 0, "end": 706 }
class ____: def strobogrammaticInRange(self, low: str, high: str) -> int: def dfs(u): if u == 0: return [''] if u == 1: return ['0', '1', '8'] ans = [] for v in dfs(u - 2): for l, r in ('11', '88', '69', '96'): ...
Solution
python
docker__docker-py
tests/unit/dockertypes_test.py
{ "start": 8495, "end": 8957 }
class ____(unittest.TestCase): def test_parse_mounts(self): spec = ContainerSpec( image='scratch', mounts=[ '/local:/container', '/local2:/container2:ro', Mount(target='/target', source='/source') ] ) assert 'Mounts' in...
ContainerSpecTest