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
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 68327, "end": 68442 }
class ____: name: str status: ShardTypes vector_queue_size: int ShardStatus = _ShardStatus
_ShardStatus
python
lepture__authlib
authlib/integrations/base_client/framework_integration.py
{ "start": 26, "end": 1871 }
class ____: expires_in = 3600 def __init__(self, name, cache=None): self.name = name self.cache = cache def _get_cache_data(self, key): value = self.cache.get(key) if not value: return None try: return json.loads(value) except (TypeEr...
FrameworkIntegration
python
django-debug-toolbar__django-debug-toolbar
tests/panels/test_sql.py
{ "start": 2265, "end": 32305 }
class ____(BaseTestCase): panel_id = SQLPanel.panel_id def test_disabled(self): config = {"DISABLE_PANELS": {"debug_toolbar.panels.sql.SQLPanel"}} self.assertTrue(self.panel.enabled) with self.settings(DEBUG_TOOLBAR_CONFIG=config): self.assertFalse(self.panel.enabled) d...
SQLPanelTestCase
python
h5py__h5py
h5py/tests/test_dataset_getitem.py
{ "start": 7245, "end": 9362 }
class ____(TestCase): def setUp(self): TestCase.setUp(self) self.dt = np.dtype('(3,2)f') self.data = np.array([(3.2, -119), (42, 99.8), (3.14, 0)], dtype='f') self.dset = self.f.create_dataset('x', (), dtype=self.dt) self.dset[...] = self.data def test_ndim(self): ...
TestScalarArray
python
python-pillow__Pillow
src/PIL/DdsImagePlugin.py
{ "start": 4163, "end": 7830 }
class ____(IntEnum): UNKNOWN = 0 R8G8B8 = 20 A8R8G8B8 = 21 X8R8G8B8 = 22 R5G6B5 = 23 X1R5G5B5 = 24 A1R5G5B5 = 25 A4R4G4B4 = 26 R3G3B2 = 27 A8 = 28 A8R3G3B2 = 29 X4R4G4B4 = 30 A2B10G10R10 = 31 A8B8G8R8 = 32 X8B8G8R8 = 33 G16R16 = 34 A2R10G10B10 = 35 ...
D3DFMT
python
donnemartin__interactive-coding-challenges
recursion_dynamic/max_profit_k/test_max_profit.py
{ "start": 18, "end": 1564 }
class ____(unittest.TestCase): def test_max_profit(self): stock_trader = StockTrader() self.assertRaises(TypeError, stock_trader.find_max_profit, None, None) self.assertEqual(stock_trader.find_max_profit(prices=[], k=0), []) prices = [5, 4, 3, 2, 1] k = 3 self.assert...
TestMaxProfit
python
doocs__leetcode
solution/1100-1199/1152.Analyze User Website Visit Pattern/Solution.py
{ "start": 0, "end": 773 }
class ____: def mostVisitedPattern( self, username: List[str], timestamp: List[int], website: List[str] ) -> List[str]: d = defaultdict(list) for user, _, site in sorted( zip(username, timestamp, website), key=lambda x: x[1] ): d[user].append(site) ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amplitude/components.py
{ "start": 640, "end": 1542 }
class ____(RecordExtractor): """ Create records from complex response structure Issue: https://github.com/airbytehq/airbyte/issues/23145 """ def extract_records(self, response: requests.Response) -> List[Record]: response_data = response.json().get("data", []) if response_data: ...
AverageSessionLengthRecordExtractor
python
tensorflow__tensorflow
tensorflow/python/autograph/converters/directives.py
{ "start": 3114, "end": 6741 }
class ____(converter.Base): """Parses compiler directives and converts them into AST annotations.""" def _process_symbol_directive(self, call_node, directive): if len(call_node.args) < 1: raise ValueError('"%s" requires a positional first argument' ' as the target' % directive.__na...
DirectivesTransformer
python
huggingface__transformers
tests/models/encoder_decoder/test_modeling_encoder_decoder.py
{ "start": 58893, "end": 60398 }
class ____(unittest.TestCase): def get_from_encoderdecoder_pretrained_model(self): return EncoderDecoderModel.from_encoder_decoder_pretrained( "google-bert/bert-base-uncased", "google-bert/bert-base-uncased" ) def get_decoder_config(self): config = AutoConfig.from_pretrained...
EncoderDecoderModelTest
python
numpy__numpy
numpy/polynomial/tests/test_symbol.py
{ "start": 2095, "end": 3099 }
class ____: """ Ensure symbol is preserved for numeric operations on polynomials with the same symbol """ p = poly.Polynomial([1, 2, 3], symbol='z') def test_add(self, rhs): out = self.p + rhs assert_equal(out.symbol, 'z') def test_sub(self, rhs): out = self.p - rhs...
TestBinaryOperatorsSameSymbol
python
conda__conda
conda/exceptions.py
{ "start": 2615, "end": 3833 }
class ____(Help): def __init__(self): message = dals( """ usage: conda activate [-h] [--[no-]stack] [env_name_or_prefix] Activate a conda environment. Options: positional arguments: env_name_or_prefix The environment name or prefix to activate. If ...
ActivateHelp
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 34192, "end": 34975 }
class ____(TestCase): def test_basic(self): iterable = range(1, 5 + 1) for n, expected in ( (1, [(1,), (2,), (3,), (4,), (5,)]), (2, [(1, 2), (3, 4), (5,)]), (3, [(1, 2, 3), (4, 5)]), (4, [(1, 2, 3, 4), (5,)]), (5, [(1, 2, 3, 4, 5)]), ...
BatchedTests
python
neetcode-gh__leetcode
python/1239-maximum-length-of-a-concatenated-string-with-unique-characters.py
{ "start": 0, "end": 837 }
class ____: def maxLength(self, arr: List[str]) -> int: charSet = set() def overlap(charSet, s): c = Counter(charSet) + Counter(s) return max(c.values()) > 1 # prev = set() # for c in s: # if c in charSet or c in prev: # ...
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_s3.py
{ "start": 22478, "end": 37746 }
class ____: def test_s3_delete_single_object(self): bucket = "testbucket" key = "path/data.txt" conn = boto3.client("s3") conn.create_bucket(Bucket=bucket) conn.upload_fileobj(Bucket=bucket, Key=key, Fileobj=BytesIO(b"input")) # The object should be detected before ...
TestS3DeleteObjectsOperator
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tfr/python/tfr_gen.py
{ "start": 21722, "end": 53978 }
class ____(transformer.CodeGenerator): """Visit the AST and generate MLIR TFR functions.""" def __init__(self, ctx, op_defs): super(TFRGen, self).__init__(ctx) self.ctx = ctx self.symbol_table = SymbolTable() self._op_defs = op_defs def _create_mlir_loc(self, loc): """Creates mlir location f...
TFRGen
python
realpython__materials
python-wav-files/waveio/reader.py
{ "start": 1495, "end": 3338 }
class ____: DEFAULT_MAX_FRAMES = 1024 def __init__(self, path): self._wav_file = wave.open(str(path)) self.metadata = WAVMetadata( PCMEncoding(self._wav_file.getsampwidth()), self._wav_file.getframerate(), self._wav_file.getnchannels(), self._wav_...
WAVReader
python
apache__avro
lang/py/avro/schema.py
{ "start": 18379, "end": 20022 }
class ____(EqualByPropsMixin, NamedSchema): def __init__(self, name, namespace, size, names=None, other_props=None, validate_names: bool = True): # Ensure valid ctor args if not isinstance(size, int) or size < 0: fail_msg = "Fixed Schema requires a valid positive integer for size propert...
FixedSchema
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI045.py
{ "start": 994, "end": 1079 }
class ____: def __iter__(self) -> typing.Iterator: ...
TypingIteratorReturn
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 1502, "end": 1562 }
class ____(ParentClosed4): b: Required[int]
ChildClosed4_3
python
spyder-ide__spyder
spyder/widgets/simplecodeeditor.py
{ "start": 2049, "end": 18129 }
class ____(QPlainTextEdit, BaseEditMixin): """Simple editor with highlight features.""" LANGUAGE_HIGHLIGHTERS = { 'Python': (sh.PythonSH, '#'), 'Cython': (sh.CythonSH, '#'), 'Fortran77': (sh.Fortran77SH, 'c'), 'Fortran': (sh.FortranSH, '!'), 'Idl': (sh.IdlSH, ';'), ...
SimpleCodeEditor
python
geekcomputers__Python
Delete_Linked_List.py
{ "start": 94, "end": 1411 }
class ____: def __init__(self): self.head = None def Insert_At_End(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return current = self.head while current.next: current = current.next curr...
Linked_List
python
pallets__werkzeug
src/werkzeug/formparser.py
{ "start": 10705, "end": 15847 }
class ____: def __init__( self, stream_factory: TStreamFactory | None = None, max_form_memory_size: int | None = None, cls: type[MultiDict[str, t.Any]] | None = None, buffer_size: int = 64 * 1024, max_form_parts: int | None = None, ) -> None: self.max_form...
MultiPartParser
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/containers.py
{ "start": 45065, "end": 46025 }
class ____: """ Scroll offsets for the :class:`.Window` class. Note that left/right offsets only make sense if line wrapping is disabled. """ def __init__( self, top: int | Callable[[], int] = 0, bottom: int | Callable[[], int] = 0, left: int | Callable[[], int] = 0...
ScrollOffsets
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/hooks/search_ads.py
{ "start": 1285, "end": 7905 }
class ____(GoogleBaseHook): """Hook for the Google Search Ads 360 Reporting API.""" _conn: build | None = None default_api_version: str = "v0" def __init__( self, api_version: str | None = None, gcp_conn_id: str = "google_search_ads_default", **kwargs, ) -> None: ...
GoogleSearchAdsReportingHook
python
prabhupant__python-ds
data_structures/graphs/count_paths_between_nodes.py
{ "start": 37, "end": 946 }
class ____: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def count_paths_util(self, u, d, visited, path_count): visited[u] = True if u == d: path_count[0] += 1 ...
Graph
python
agronholm__apscheduler
tests/test_schedulers.py
{ "start": 47388, "end": 58957 }
class ____: def test_interface_parity(self) -> None: """ Ensure that the sync scheduler has the same properties and methods as the async schedulers, and the method parameters match too. """ actual_attributes = set(dir(Scheduler)) expected_attributes = sorted( ...
TestSyncScheduler
python
mlflow__mlflow
mlflow/models/model_config.py
{ "start": 192, "end": 5072 }
class ____: """ ModelConfig used in code to read a YAML configuration file or a dictionary. Args: development_config: Path to the YAML configuration file or a dictionary containing the configuration. If the configuration is not provided, an error is raised .. code-block...
ModelConfig
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 4399, "end": 4570 }
class ____(BaseStringType): """Xsd:string with whitespace collapsing, e.g. multiple spaces reduced to one, leading and trailing space stripped.""" pass
XsdToken
python
pytorch__pytorch
torch/ao/quantization/backend_config/backend_config.py
{ "start": 11140, "end": 17346 }
class ____: # TODO: refer to NativeBackendConfig once that is implemented """Config that defines the set of patterns that can be quantized on a given backend, and how reference quantized models can be produced from these patterns. A pattern in this context refers to a module, a functional, an operator,...
BackendConfig
python
coleifer__peewee
tests/regressions.py
{ "start": 20845, "end": 20932 }
class ____(TestModel): game = ForeignKeyField(Game) points = IntegerField()
Score
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v2.py
{ "start": 2757, "end": 3186 }
class ____(sharded_variable.ShardedVariableMixin): """A ShardedVariable class for TPU.""" @property def _in_graph_mode(self): return self.variables[0]._in_graph_mode # pylint: disable=protected-access def _add_key_attr(op, name): op._set_attr(_NAME_KEY, attr_value_pb2.AttrValue(s=compat.as_bytes(name)))...
TPUEmbeddingVariable
python
pytorch__pytorch
torch/distributed/elastic/agent/server/api.py
{ "start": 10665, "end": 12540 }
class ____: """The class is used by the agent to exchange the information with other agents. The information is used to determine the rank of the workers that agent manages in heterogeneous environments, where different agents can have different number of workers. """ __slots__ = ["role", "ran...
_RoleInstanceInfo
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/agent.py
{ "start": 348, "end": 462 }
class ____(BaseModel): """Agent metadata key-value pair.""" key: str value: str
DgApiAgentMetadataEntry
python
tensorflow__tensorflow
tensorflow/lite/python/lite_v2_test.py
{ "start": 148193, "end": 159725 }
class ____(lite_v2_test_util.ModelTest): @test_util.run_v2_only def testCond(self): input_data = { 'x': tf.constant([1.0, 2.0], shape=[1, 2]), 'b': tf.constant(True), } weights = tf.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=tf.float32) def true_fn(x): return tf.matmul(x, weig...
ControlFlowTest
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 31235, "end": 31585 }
class ____(PrefectBaseModel): ip_network: IPvAnyNetwork enabled: bool description: Optional[str] = Field( default=None, description="A description of the IP entry." ) last_seen: Optional[str] = Field( default=None, description="The last time this IP was seen accessing Prefect...
IPAllowlistEntry
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format16.py
{ "start": 315, "end": 1711 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format16.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = ...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/blenderbot/modeling_blenderbot.py
{ "start": 4990, "end": 10711 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
BlenderbotAttention
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 243403, "end": 245009 }
class ____: @pytest.mark.parametrize('byteorder', ['<', '>']) @pytest.mark.parametrize('dtype', [float, int, complex]) def test_basic(self, byteorder, dtype): dt = np.dtype(dtype).newbyteorder(byteorder) x = (np.random.random((4, 7)) * 5).astype(dt) buf = x.tobytes() assert_a...
TestFromBuffer
python
pypa__setuptools
setuptools/_vendor/backports/tarfile/__init__.py
{ "start": 10389, "end": 10589 }
class ____(HeaderError): """Exception for missing and invalid extended headers.""" pass #--------------------------- # internal stream interface #---------------------------
SubsequentHeaderError
python
protocolbuffers__protobuf
python/google/protobuf/internal/text_format_test.py
{ "start": 2901, "end": 25373 }
class ____(TextFormatBase): def testPrintExotic(self, message_module): message = message_module.TestAllTypes() message.repeated_int64.append(-9223372036854775808) message.repeated_uint64.append(18446744073709551615) message.repeated_double.append(123.456) message.repeated_double.append(1.23e22) ...
TextFormatMessageToStringTests
python
Lightning-AI__lightning
tests/tests_pytorch/core/test_datamodules.py
{ "start": 4306, "end": 8452 }
class ____(BoringDataModule): def __init__(self, data_dir: str): super().__init__() self.data_dir = data_dir def test_dm_pickle_after_init(): dm = BoringDataModule() pickle.dumps(dm) @RunIf(sklearn=True) def test_train_loop_only(tmp_path): seed_everything(7) dm = ClassifDataModu...
DataDirDataModule
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 222858, "end": 223669 }
class ____(MemoryCopyNode): """ Copy the contents of slice src to slice dst. Does not support indirect slices. memslice1[...] = memslice2 memslice1[:] = memslice2 """ is_memview_copy_assignment = True copy_slice_cname = "__pyx_memoryview_copy_contents" def _generate_assign...
MemoryCopySlice
python
great-expectations__great_expectations
tests/metrics/test_metric.py
{ "start": 1114, "end": 1635 }
class ____: @pytest.mark.unit def test_success(self): class MyColumnValuesAbove(ColumnMetric[ColumnValuesAboveResult]): name = FULLY_QUALIFIED_METRIC_NAME min_value: Comparable strict_min: bool = False @pytest.mark.unit def test_success_without_generic_retur...
TestMetricDefinition
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 2682, "end": 11738 }
class ____(TestCase): @classmethod def setUpTestData(cls): # Sequence of title/text is: # # z abc # zz bcd # zzz cde # ... for idx in range(10): title = 'z' * (idx + 1) text = ( chr(idx + ord('a')) + ...
SearchFilterTests
python
dagster-io__dagster
python_modules/libraries/dagster-sigma/dagster_sigma/resource.py
{ "start": 1757, "end": 2729 }
class ____(str, enum.Enum): PENDING = "pending" BUILDING = "building" READY = "ready" def build_folder_path_err(folder: Any, idx: int, param_name: str): return ( f"{param_name} at index {idx} is not a sequence: `{folder!r}`.\n" "Paths should be specified as a list of folder names, star...
SigmaMaterializationStatus
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 86730, "end": 96968 }
class ____(torch.nn.Module): def forward(self, primals_1: "Sym(s77)", getitem_17: "Sym(s77)", getitem_19: "Sym(s77)", getitem_21: "Sym(s77)", getitem_23: "Sym(s77)", getitem_16: "f32[s77, 16]", getitem_18: "f32[s77, 16]", getitem_20: "f32[s77, 16]", getitem_22: "f32[s77, 16]", cos: "f32[s77, 16]", tangents_1: "f32[...
GraphModule
python
Textualize__textual
src/textual/renderables/sparkline.py
{ "start": 485, "end": 4243 }
class ____(Generic[T]): """A sparkline representing a series of data. Args: data: The sequence of data to render. width: The width of the sparkline/the number of buckets to partition the data into. min_color: The color of values equal to the min value in data. max_color: The col...
Sparkline
python
django__django
django/views/generic/edit.py
{ "start": 386, "end": 2457 }
class ____(ContextMixin): """Provide a way to show and handle a form in a request.""" initial = {} form_class = None success_url = None prefix = None def get_initial(self): """Return the initial data to use for forms on this view.""" return self.initial.copy() def get_pref...
FormMixin
python
getsentry__sentry-python
sentry_sdk/integrations/__init__.py
{ "start": 11672, "end": 12735 }
class ____(ABC): """Baseclass for all integrations. To accept options for an integration, implement your own constructor that saves those options on `self`. """ install = None """Legacy method, do not implement.""" identifier = None # type: str """String unique ID of integration type...
Integration
python
sympy__sympy
sympy/physics/optics/gaussopt.py
{ "start": 7488, "end": 8054 }
class ____(RayTransferMatrix): """ Ray Transfer Matrix for a thin lens. Parameters ========== f : The focal distance. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import ThinLens >>> from sympy import symbols >>> f ...
ThinLens
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_origin.py
{ "start": 11197, "end": 14745 }
class ____(IHaveNew, LegacyNamedTupleMixin, CodeLocationOrigin): """Identifies a repository location hosted in a gRPC server managed by the user. Dagster is not responsible for managing the lifecycle of the server. """ host: str port: Optional[int] socket: Optional[str] location_name: str ...
GrpcServerCodeLocationOrigin
python
PyCQA__pylint
doc/data/messages/t/too-few-public-methods/good/dataclass_and_function.py
{ "start": 44, "end": 191 }
class ____: name: str fruit_of_residence: Fruit def bore(worm: Worm): print(f"{worm.name} is boring into {worm.fruit_of_residence}")
Worm
python
kamyu104__LeetCode-Solutions
Python/special-array-with-x-elements-greater-than-or-equal-x.py
{ "start": 1769, "end": 3033 }
class ____(object): def specialArray(self, nums): """ :type nums: List[int] :rtype: int """ MAX_NUM = 1000 def counting_sort(nums, reverse=False): # Time: O(n), Space: O(n) count = [0]*(MAX_NUM+1) for num in nums: count[num] +=...
Solution3
python
spack__spack
lib/spack/spack/util/environment.py
{ "start": 16345, "end": 47673 }
class ____: """ Tracks and applies a sequence of environment variable modifications. This class provides a high-level interface for building up a list of environment changes, such as setting, unsetting, appending, prepending, or removing values from environment variables. Modifications are stored a...
EnvironmentModifications
python
mlflow__mlflow
tests/pyfunc/test_model_export_with_class_and_artifacts.py
{ "start": 10804, "end": 42180 }
class ____(mlflow.pyfunc.PythonModel): def predict(self, context, model_input, params=None): return model_input def test_log_model_calls_register_model(sklearn_knn_model, main_scoped_model_class): with mlflow.start_run(): with mock.patch( "mlflow.tracking._model_registry.fluent._re...
DummyModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-klaviyo/components.py
{ "start": 5762, "end": 9016 }
class ____(RecordTransformation): """ Campaigns detailed stream fetches detailed campaigns info: estimated_recipient_count: integer campaign_messages: list of objects. To get this data CampaignsDetailedTransformation makes extra API requests: https://a.klaviyo.com/api/campaign-recipient-estimat...
CampaignsDetailedTransformation
python
scipy__scipy
scipy/fft/_backend.py
{ "start": 130, "end": 6544 }
class ____: """The default backend for fft calculations Notes ----- We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray`` treats the domain as a hierarchy. This means the user can install a single backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well. ...
_ScipyBackend
python
keon__algorithms
tests/test_array.py
{ "start": 9495, "end": 10379 }
class ____(unittest.TestCase): def test_remove_duplicates(self): self.assertListEqual( remove_duplicates( [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 7, 7, 7, 8, 8, 9, 10, 10] ), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ) self.assertListEqual( ...
TestRemoveDuplicate
python
openai__openai-python
src/openai/types/evals/runs/output_item_list_response.py
{ "start": 1842, "end": 2165 }
class ____(BaseModel): cached_tokens: int """The number of tokens retrieved from cache.""" completion_tokens: int """The number of completion tokens generated.""" prompt_tokens: int """The number of prompt tokens used.""" total_tokens: int """The total number of tokens used."""
SampleUsage
python
doocs__leetcode
solution/3100-3199/3151.Special Array I/Solution.py
{ "start": 0, "end": 133 }
class ____: def isArraySpecial(self, nums: List[int]) -> bool: return all(a % 2 != b % 2 for a, b in pairwise(nums))
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/transfers/test_gcs_to_s3.py
{ "start": 1724, "end": 20840 }
class ____: @mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook") def test_execute__match_glob(self, mock_hook): mock_hook.return_value.list.return_value = MOCK_FILES with NamedTemporaryFile() as f: gcs_provide_file = mock_hook.return_value.provide_file ...
TestGCSToS3Operator
python
joke2k__faker
faker/providers/address/en_IN/__init__.py
{ "start": 139, "end": 13657 }
class ____(AddressProvider): # City and States names taken from wikipedia # Street format taken from some common famous places in India # Link for cities: https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population # Link for States: https://en.wikipedia.org/wiki/States_and_union_territories_of_...
Provider
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py
{ "start": 1760, "end": 2079 }
class ____(BaseModel): class Config(BaseConfig): mutable_default: list[int] = [] immutable_annotation: Sequence[int] = [] without_annotation = [] class_variable: ClassVar[list[int]] = [] final_variable: Final[list[int]] = [] from pydantic.v1 import BaseModel as V1BaseModel ...
H
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/bandit_envs_discrete.py
{ "start": 3555, "end": 6413 }
class ____(gym.Env): """Wheel bandit environment for 2D contexts (see https://arxiv.org/abs/1802.09127). """ DEFAULT_CONFIG_WHEEL = { "delta": 0.5, "mu_1": 1.2, "mu_2": 1, "mu_3": 50, "std": 0.01, } feature_dim = 2 num_actions = 5 def __init__(s...
WheelBanditEnv
python
pytorch__pytorch
torch/distributed/pipelining/schedules.py
{ "start": 24623, "end": 26484 }
class ____(PipelineScheduleSingle): """ The forward-only schedule. Will go through all the microbatches and perform only the forward pass """ def _step_microbatches( self, arg_mbs: list | None = None, kwarg_mbs: list | None = None, target_mbs: list | None = None, ...
_ScheduleForwardOnly
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 14348, "end": 16105 }
class ____(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None): super().__init_...
TestDetrSinePositionEmbedding
python
PrefectHQ__prefect
src/prefect/docker/docker_image.py
{ "start": 402, "end": 3138 }
class ____: """ Configuration used to build and push a Docker image for a deployment. Attributes: name: The name of the Docker image to build, including the registry and repository. tag: The tag to apply to the built image. dockerfile: The path to the Dockerfile to use f...
DockerImage
python
spack__spack
lib/spack/spack/detection/test.py
{ "start": 1406, "end": 7283 }
class ____: """Runs an external detection test""" def __init__(self, *, test: DetectionTest, repository: spack.repo.RepoPath) -> None: self.test = test self.repository = repository self.tmpdir = tempfile.TemporaryDirectory() def execute(self) -> List[spack.spec.Spec]: """Ex...
Runner
python
google__pytype
pytype/pytd/parse/node_test.py
{ "start": 256, "end": 351 }
class ____(Node): """For equality testing. Same attributes as Node3.""" x: Any y: Any
Node2
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 284231, "end": 284560 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("DiscussionComment", graphql_name="node")
DiscussionCommentEdge
python
pytorch__pytorch
test/onnx/ops/test_ops.py
{ "start": 346, "end": 2672 }
class ____(common_utils.TestCase): def test_symbolic_has_correct_schema(self): torch.library.opcheck( _symbolic_impl._symbolic, ([torch.tensor(1)], "CustomOp", 1), dict( shape=[ 1, ], attr_keys=["key"], ...
SchemaTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external_data.py
{ "start": 18905, "end": 19063 }
class ____: error: Optional[SerializableErrorInfo] @whitelist_for_serdes(storage_name="ExternalExecutionParamsData") @record_custom
SensorExecutionErrorSnap
python
coleifer__peewee
playhouse/sqlite_ext.py
{ "start": 30619, "end": 34204 }
class ____(VirtualModel): class Meta: extension_module = 'lsm1' filename = None @classmethod def clean_options(cls, options): filename = cls._meta.filename if not filename: raise ValueError('LSM1 extension requires that you specify a ' ...
LSMTable
python
Delgan__loguru
loguru/_recattrs.py
{ "start": 3542, "end": 4612 }
class ____: """A class representing a process record with ID and name. Attributes ---------- id : int The process ID name : str The process name """ __slots__ = ("id", "name") def __init__(self, id_, name): """Initialize a RecordProcess instance. Param...
RecordProcess
python
doocs__leetcode
solution/0300-0399/0327.Count of Range Sum/Solution.py
{ "start": 339, "end": 852 }
class ____: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: s = list(accumulate(nums, initial=0)) arr = sorted(set(v for x in s for v in (x, x - lower, x - upper))) tree = BinaryIndexedTree(len(arr)) ans = 0 for x in s: l = bisect_left(arr...
Solution
python
ray-project__ray
rllib/execution/segment_tree.py
{ "start": 51, "end": 6381 }
class ____: """A Segment Tree data structure. https://en.wikipedia.org/wiki/Segment_tree Can be used as regular array, but with two important differences: a) Setting an item's value is slightly slower. It is O(lg capacity), instead of O(1). b) Offers efficient `reduce` operation whic...
SegmentTree
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 131821, "end": 132529 }
class ____(TorchHigherOrderOperatorVariable): def _call_function( self, tx: "InstructionTranslator", args: "list[VariableTracker]", kwargs: "dict[str, VariableTracker]", ) -> "VariableTracker": from .builder import wrap_fx_proxy p_args = tuple(arg.as_proxy() for ...
RunWithRNGStateHigherOrderVariable
python
ansible__ansible
lib/ansible/module_utils/facts/hardware/hpux.py
{ "start": 793, "end": 8345 }
class ____(Hardware): """ HP-UX-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor - processor_cores - processor_count - model - firmware """ platform = 'HP-UX' def populate(self, coll...
HPUXHardware
python
PrefectHQ__prefect
tests/server/models/test_saved_searches.py
{ "start": 2918, "end": 4622 }
class ____: @pytest.fixture async def saved_searches(self, session): saved_search_1 = await models.saved_searches.create_saved_search( session=session, saved_search=schemas.core.SavedSearch( name="My SavedSearch 1", ), ) saved_search_2 ...
TestReadSavedSearches
python
pandas-dev__pandas
pandas/plotting/_matplotlib/core.py
{ "start": 42599, "end": 44697 }
class ____(MPLPlot, ABC): """ Abstract class for plotting on plane, currently scatter and hexbin. """ _layout_type = "single" def __init__(self, data, x, y, **kwargs) -> None: MPLPlot.__init__(self, data, **kwargs) if x is None or y is None: raise ValueError(self._kind ...
PlanePlot
python
pytorch__pytorch
torch/profiler/_memory_profiler.py
{ "start": 1578, "end": 2248 }
class ____: """Bundle storage pointer and id. All profiling logic should use `allocation_id`, however it is useful to print storage pointers for debugging and unit tests sometimes look up values using the storage data pointer of a live Tensor.""" ptr: int allocation_id: int def __repr__(s...
_Storage
python
wepe__MachineLearning
KMeans/kmeans.py
{ "start": 181, "end": 3515 }
class ____(object): """ - 参数 n_clusters: 聚类个数,即k initCent: 质心初始化方式,可选"random"或指定一个具体的array,默认random,即随机初始化 max_iter: 最大迭代次数 """ def __init__(self,n_clusters=5,initCent='random',max_iter=300): if hasattr(initCent, '__array__'): ...
KMeans
python
huggingface__transformers
src/transformers/models/kosmos2_5/processing_kosmos2_5.py
{ "start": 1022, "end": 1399 }
class ____(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "padding": True, "return_token_type_ids": False, "stride": 0, "truncation": True, }, "images_kwargs": { "max_patches": 4096, }, "common_kwargs...
Kosmos2_5ProcessorKwargs
python
zarr-developers__zarr-python
tests/test_dtype/test_npy/test_float.py
{ "start": 2113, "end": 3383 }
class ____(_BaseTestFloat): test_cls = Float32 scalar_type = np.float32 valid_dtype = (np.dtype(">f4"), np.dtype("<f4")) invalid_dtype = ( np.dtype(np.int8), np.dtype(np.uint16), np.dtype(np.float64), ) valid_json_v2 = ( {"name": ">f4", "object_codec_id": None}, ...
TestFloat32
python
GoogleCloudPlatform__python-docs-samples
endpoints/getting-started-grpc/helloworld_pb2_grpc.py
{ "start": 702, "end": 1398 }
class ____: """The greeting service definition.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( "/helloworld.Greeter/SayHello", request_serializer=helloworld__pb2.HelloRequ...
GreeterStub
python
plotly__plotly.py
plotly/graph_objs/scatterternary/marker/colorbar/_title.py
{ "start": 233, "end": 4070 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterternary.marker.colorbar" _path_str = "scatterternary.marker.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an inst...
Title
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/integration_tests/integration_test.py
{ "start": 375, "end": 13135 }
class ____(BaseIntegrationTest): def setUp(self): with open("secrets/config.json", "r") as f: self.config = json.loads(f.read()) def tearDown(self): pass def test_check_valid_config(self): outcome = DestinationPGVector().check(logging.getLogger("airbyte"), self.config) ...
PGVectorIntegrationTest
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 40359, "end": 40966 }
class ____(PrefectFilterBaseModel): """Filter by `Deployment.work_queue_name`.""" any_: Optional[list[str]] = Field( default=None, description="A list of work queue names to include", examples=[["work_queue_1", "work_queue_2"]], ) def _get_filter_list( self, db: "Prefec...
DeploymentFilterWorkQueueName
python
huggingface__transformers
tests/models/siglip/test_modeling_siglip.py
{ "start": 20307, "end": 21163 }
class ____(SiglipModelTester): def __init__(self, parent): super().__init__(parent) self.batch_size = self.vision_model_tester.batch_size self.num_hidden_layers = self.vision_model_tester.num_hidden_layers self.hidden_size = self.vision_model_tester.hidden_size self.seq_lengt...
SiglipForImageClassificationModelTester
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/context.py
{ "start": 5230, "end": 5846 }
class ____(Protocol): _partition_loading_context: PartitionLoadingContext Self = TypeVar("Self", bound=_HasPartitionLoadingContext) def use_partition_loading_context( func: Callable[Concatenate[Self, P], T_Return], ) -> Callable[Concatenate[Self, P], T_Return]: """Decorator for methods that will use the...
_HasPartitionLoadingContext
python
pypa__setuptools
setuptools/_distutils/version.py
{ "start": 1471, "end": 3669 }
class ____: """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those seem to be the same for all version numbering classes; and route rich comparisons to _cmp. """ def __init__(self, vstring=None): if vstring: ...
Version
python
networkx__networkx
networkx/algorithms/tests/test_cuts.py
{ "start": 3035, "end": 3676 }
class ____: """Unit tests for the :func:`~networkx.conductance` function.""" def test_graph(self): G = nx.barbell_graph(5, 0) # Consider the singleton sets containing the "bridge" nodes. # There is only one cut edge, and each set has volume five. S = {4} T = {5} ...
TestConductance
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 21714, "end": 24292 }
class ____(BuiltinFunctionT): _id = "sha256" _inputs = [("value", (BYTES32_T, BytesT.any(), StringT.any()))] _return_type = BYTES32_T def _try_fold(self, node): validate_call_args(node, 1) value = node.args[0].get_folded_value() if isinstance(value, (vy_ast.Bytes, vy_ast.HexByte...
Sha256
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_reflection.py
{ "start": 4443, "end": 10226 }
class ____: @classmethod def bar(cls): pass def baz(cls): pass def __repr__(self): return "SoNotFoo()" def test_class_names_are_not_included_in_class_method_prettiness(): assert get_pretty_function_description(Foo.bar) == "bar" def test_repr_is_included_in_bound_method_...
Foo
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/dashboard.py
{ "start": 25395, "end": 26560 }
class ____(CamelSnakeSerializer[Dashboard]): is_editable_by_everyone = serializers.BooleanField( help_text="Whether the dashboard is editable by everyone.", ) teams_with_edit_access = serializers.ListField( child=serializers.IntegerField(), help_text="List of team IDs that have edit ...
DashboardPermissionsSerializer
python
walkccc__LeetCode
solutions/991. Broken Calculator/991.py
{ "start": 0, "end": 253 }
class ____: def brokenCalc(self, startValue: int, target: int) -> int: ops = 0 while startValue < target: if target % 2 == 0: target //= 2 else: target += 1 ops += 1 return ops + startValue - target
Solution
python
huggingface__transformers
tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py
{ "start": 31222, "end": 32802 }
class ____(EncoderDecoderMixin, unittest.TestCase): supports_sdpa = True # one submodel support SDPA def get_encoder_decoder_model(self, config, decoder_config): encoder_model = ViTModel(config).eval() decoder_model = TrOCRForCausalLM(decoder_config).eval() return encoder_model, decode...
ViT2TrOCR
python
pallets__jinja
src/jinja2/runtime.py
{ "start": 3124, "end": 3740 }
class ____: """The `self` in templates.""" def __init__(self, context: "Context") -> None: self.__context = context def __getitem__(self, name: str) -> t.Any: blocks = self.__context.blocks[name] return BlockReference(name, self.__context, blocks, 0) def __repr__(self) -> str:...
TemplateReference
python
xlwings__xlwings
xlwings/main.py
{ "start": 151371, "end": 151668 }
class ____(Sheets): def __init__(self): pass # override class name which appears in repr _name = "Sheets" @property def impl(self): return books.active.sheets.impl apps = ActiveEngineApps() books = ActiveAppBooks() sheets = ActiveBookSheets()
ActiveBookSheets