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
GoogleCloudPlatform__python-docs-samples
appengine/standard/hello_world/main.py
{ "start": 593, "end": 847 }
class ____(webapp2.RequestHandler): def get(self): self.response.headers["Content-Type"] = "text/plain" self.response.write("Hello, World!") app = webapp2.WSGIApplication( [ ("/", MainPage), ], debug=True, )
MainPage
python
django__django
tests/admin_registration/models.py
{ "start": 356, "end": 572 }
class ____(models.Model): pk = models.CompositePrimaryKey("traveler", "place") traveler = models.ForeignKey(Traveler, on_delete=models.CASCADE) place = models.ForeignKey(Place, on_delete=models.CASCADE)
Guest
python
spack__spack
lib/spack/spack/spec.py
{ "start": 7420, "end": 23046 }
class ____: """Aggregate the target platform, the operating system and the target microarchitecture.""" ANY_TARGET = _make_microarchitecture("*") @staticmethod def default_arch(): """Return the default architecture""" platform = spack.platforms.host() default_os = platform.defa...
ArchSpec
python
PrefectHQ__prefect
tests/server/schemas/test_actions.py
{ "start": 11746, "end": 13716 }
class ____: @pytest.mark.parametrize( "template", [ { "job_configuration": {"thing_one": "{{ expected_variable }}"}, "variables": { "properties": {"wrong_variable": {}}, "required": [], }, ...
TestWorkPoolCreate
python
rq__rq
rq/job.py
{ "start": 71776, "end": 72366 }
class ____: def __init__(self, func: Union[str, Callable[..., Any]], timeout: Optional[Any] = None): if not isinstance(func, str) and not inspect.isfunction(func) and not inspect.isbuiltin(func): raise ValueError('Callback `func` must be a string or function') self.func = func s...
Callback
python
html5lib__html5lib-python
html5lib/serializer.py
{ "start": 3623, "end": 15668 }
class ____(object): # attribute quoting options quote_attr_values = "legacy" # be secure by default quote_char = '"' use_best_quote_char = True # tag syntax options omit_optional_tags = True minimize_boolean_attributes = True use_trailing_solidus = False space_before_trailing_soli...
HTMLSerializer
python
huggingface__transformers
src/transformers/models/owlvit/modeling_owlvit.py
{ "start": 39184, "end": 41074 }
class ____(OwlViTPreTrainedModel): config: OwlViTVisionConfig main_input_name = "pixel_values" input_modalities = ("image",) def __init__(self, config: OwlViTVisionConfig): super().__init__(config) self.vision_model = OwlViTVisionTransformer(config) # Initialize weights and appl...
OwlViTVisionModel
python
huggingface__transformers
tests/models/blip/test_image_processing_blip.py
{ "start": 2952, "end": 4083 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = BlipImageProcessor if is_vision_available() else None fast_image_processing_class = BlipImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester =...
BlipImageProcessingTest
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/hcloud.py
{ "start": 2148, "end": 3007 }
class ____(CloudEnvironment): """Hetzner Cloud cloud environment plugin. Updates integration test environment after delegation.""" def get_environment_config(self) -> CloudEnvironmentConfig: """Return environment configuration for use in the test environment after delegation.""" parser = config...
HcloudCloudEnvironment
python
ansible__ansible
test/integration/targets/collections/test_task_resolved_plugin/action_plugins/legacy_action.py
{ "start": 178, "end": 348 }
class ____(ActionBase): TRANSFERS_FILES = False _VALID_ARGS = frozenset() def run(self, tmp=None, task_vars=None): return {'changed': False}
ActionModule
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 78555, "end": 79232 }
class ____(sgqlc.types.Enum): """Emojis that can be attached to Issues, Pull Requests and Comments. Enumeration Choices: * `CONFUSED`: Represents the `:confused:` emoji. * `EYES`: Represents the `:eyes:` emoji. * `HEART`: Represents the `:heart:` emoji. * `HOORAY`: Represents the `:hooray:` em...
ReactionContent
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 535802, "end": 536919 }
class ____(Response): """ Response of tasks.update_batch endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int """ _service = "tasks" _action = "update_batch" _version = "2.23" _schema = { "definitions": {}, "properties": { "upda...
UpdateBatchResponse
python
PyCQA__pylint
tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py
{ "start": 351, "end": 483 }
class ____: """__getnewargs__ returns <type 'tuple'>""" def __getnewargs__(self): return tuple()
SecondGoodGetNewArgs
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 142403, "end": 142820 }
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(SponsorshipNewsletterOrderField), graphql_name="field" ) direction = sgqlc.types.Field( ...
SponsorshipNewsletterOrder
python
tensorflow__tensorflow
tensorflow/tools/compatibility/tf_upgrade.py
{ "start": 839, "end": 9035 }
class ____(ast_edits.APIChangeSpec): """List of maps that describe what changed in the API.""" def __init__(self): # Maps from a function name to a dictionary that describes how to # map from an old argument keyword to the new argument keyword. self.function_keyword_renames = { "tf.batch_matmul...
TFAPIChangeSpec
python
numba__numba
numba/cuda/tests/cudapy/test_vectorize.py
{ "start": 1385, "end": 9248 }
class ____(CUDATestCase): # Presumably chosen as an odd number unlikely to coincide with the total # thread count, and large enough to ensure a significant number of blocks # are used. N = 1000001 def test_scalar(self): @vectorize(signatures, target='cuda') def vector_add(a, b): ...
TestCUDAVectorize
python
coleifer__peewee
tests/pwiz_integration.py
{ "start": 3472, "end": 4383 }
class ____(BasePwizTestCase): requires = [User, Note, Category] def test_print_models(self): with capture_output() as output: print_models(self.introspector) self.assertEqual(output.data.strip(), EXPECTED) def test_print_header(self): cmdline = '-i -e sqlite %s' % db.d...
TestPwiz
python
has2k1__plotnine
plotnine/scales/scale_color.py
{ "start": 6919, "end": 7069 }
class ____(scale_color_desaturate): """ Create a desaturated color gradient """ _aesthetics = ["fill"] @dataclass
scale_fill_desaturate
python
pypa__setuptools
setuptools/_distutils/tests/test_text_file.py
{ "start": 239, "end": 3460 }
class ____(support.TempdirManager): def test_class(self): # old tests moved from text_file.__main__ # so they are really called by the buildbots # result 1: no fancy options result1 = [ '# test file\n', '\n', 'line 3 \\\n', '# interven...
TestTextFile
python
facebook__pyre-check
client/tests/coverage_data_tests.py
{ "start": 28241, "end": 37663 }
class ____(testslide.TestCase): maxDiff = 2000 def _assert_suppressions( self, source: str, expected: Sequence[TypeErrorSuppression] ) -> None: source_module = parse_code( source.replace("PYRE_FIXME", "pyre-fixme") .replace("PYRE_IGNORE", "pyre-ignore") ....
SuppressionCollectorTest
python
fastai__fastai
fastai/layers.py
{ "start": 25302, "end": 25598 }
class ____(Module): def forward(self, x): return MishJitAutoFn.apply(x) # %% ../nbs/01_layers.ipynb 165 Mish = nn.Mish Swish = nn.SiLU # %% ../nbs/01_layers.ipynb 166 for o in swish,Swish,SwishJit,mish,Mish,MishJit: o.__default_init__ = kaiming_uniform_ # %% ../nbs/01_layers.ipynb 169
MishJit
python
gevent__gevent
src/greentest/3.13/test_selectors.py
{ "start": 1382, "end": 15395 }
class ____: def make_socketpair(self): rd, wr = socketpair() self.addCleanup(rd.close) self.addCleanup(wr.close) return rd, wr def test_register(self): s = self.SELECTOR() self.addCleanup(s.close) rd, wr = self.make_socketpair() key = s.registe...
BaseSelectorTestCase
python
huggingface__transformers
src/transformers/models/maskformer/modeling_maskformer_swin.py
{ "start": 20560, "end": 25549 }
class ____(nn.Module): def __init__(self, config, dim, input_resolution, num_heads, drop_path_rate=0.0, shift_size=0): super().__init__() self.shift_size = shift_size self.window_size = config.window_size self.input_resolution = input_resolution self.layernorm_before = nn.Lay...
MaskFormerSwinLayer
python
encode__django-rest-framework
tests/test_versioning.py
{ "start": 514, "end": 650 }
class ____(APIView): def get(self, request, *args, **kwargs): return Response({'version': request.version})
RequestVersionView
python
apache__airflow
devel-common/src/sphinx_exts/operators_and_hooks_ref.py
{ "start": 20010, "end": 23957 }
class ____(BaseJinjaReferenceDirective): """Generate list of auth managers""" def render_content( self, *, tags: set[str] | None, header_separator: str = DEFAULT_HEADER_SEPARATOR ) -> str: return _common_render_list_content( header_separator=header_separator, resourc...
AuthManagersDirective
python
getsentry__sentry
tests/sentry/search/test_utils.py
{ "start": 34577, "end": 37510 }
class ____(TestCase): def test_date(self) -> None: with pytest.raises(Release.DoesNotExist): get_first_last_release_for_group(self.group, LatestReleaseOrders.DATE, True) oldest = self.create_release(version="old") self.create_group_release(group=self.group, release=oldest) ...
GetFirstLastReleaseForGroupTest
python
cython__cython
Tools/dump_github_issues.py
{ "start": 282, "end": 3702 }
class ____(Exception): pass def gen_urls(repo): i = 0 while True: yield f"https://api.github.com/repos/{repo}/issues?state=all&per_page=100&page={i}" i += 1 def read_rate_limit(): with urlopen("https://api.github.com/rate_limit") as p: return json.load(p) def parse_rate_lim...
RateLimitReached
python
astropy__astropy
astropy/utils/console.py
{ "start": 26612, "end": 31475 }
class ____: """ A class that displays either a `ProgressBar` or `Spinner` depending on whether the total size of the operation is known or not. It is designed to be used with the ``with`` statement:: if file.has_length(): length = file.get_length() else: len...
ProgressBarOrSpinner
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/dist_autograd_test.py
{ "start": 6534, "end": 6809 }
class ____(Enum): LOCAL = 1 # Run the operation locally. RPC_SYNC = 2 # Run the operation using rpc_sync REMOTE = 3 # Run the operation using remote. RPC_ASYNC = 4 # Run the operation using rpc_async # Common utils for both CPU and CUDA test suites
ExecMode
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 32455, "end": 38498 }
class ____(MimiAttention): """ Mimi flash attention module. This module inherits from `MimiAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in cas...
MimiFlashAttention2
python
numpy__numpy
numpy/testing/tests/test_utils.py
{ "start": 77505, "end": 79701 }
class ____: """ Test assert_no_gc_cycles """ def test_passes(self): def no_cycle(): b = [] b.append([]) return b with assert_no_gc_cycles(): no_cycle() assert_no_gc_cycles(no_cycle) def test_asserts(self): def make_cycle(): ...
TestAssertNoGcCycles
python
aio-libs__aiohttp
aiohttp/client.py
{ "start": 5957, "end": 49210 }
class ____: """First-class interface for making HTTP requests.""" __slots__ = ( "_base_url", "_base_url_origin", "_source_traceback", "_connector", "_loop", "_cookie_jar", "_connector_owner", "_default_auth", "_version", "_json_ser...
ClientSession
python
gevent__gevent
src/gevent/_imap.py
{ "start": 556, "end": 892 }
class ____(object): __slots__ = ('exc', 'raise_exception') def __init__(self, exc, raise_exception=None): self.exc = exc self.raise_exception = raise_exception def _raise_exc(failure): # For cython. if failure.raise_exception: failure.raise_exception() else: raise ...
Failure
python
scipy__scipy
scipy/linalg/_matfuncs_inv_ssq.py
{ "start": 507, "end": 569 }
class ____(LogmRankWarning): pass
LogmExactlySingularWarning
python
huggingface__transformers
src/transformers/models/markuplm/modeling_markuplm.py
{ "start": 18560, "end": 20179 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([MarkupLMLayer(config) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @can_return_tuple def forward( self, hi...
MarkupLMEncoder
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol33.py
{ "start": 565, "end": 708 }
class ____(Generic[T, U]): def f(self) -> T | U: raise NotImplementedError def g(self) -> BProto[T, U]: return B[T, U]()
B
python
aimacode__aima-python
gui/grid_mdp.py
{ "start": 16421, "end": 19454 }
class ____(tk.Frame): def __init__(self, parent, controller): """HomePage constructor""" tk.Frame.__init__(self, parent) self.controller = controller frame1 = tk.Frame(self) frame1.pack(side=tk.TOP) frame3 = tk.Frame(self) frame3.pack(side=tk.TOP) fr...
HomePage
python
django__django
tests/model_options/models/default_related_name.py
{ "start": 301, "end": 559 }
class ____(models.Model): title = models.CharField(max_length=128) authors = models.ManyToManyField(Author) editor = models.ForeignKey(Editor, models.CASCADE, related_name="edited_books") class Meta: default_related_name = "books"
Book
python
kamyu104__LeetCode-Solutions
Python/check-if-numbers-are-ascending-in-a-sentence.py
{ "start": 563, "end": 819 }
class ____(object): def areNumbersAscending(self, s): """ :type s: str :rtype: bool """ nums = [int(x) for x in s.split() if x.isdigit()] return all(nums[i] < nums[i+1] for i in xrange(len(nums)-1))
Solution2
python
spack__spack
lib/spack/spack/test/error_messages.py
{ "start": 2565, "end": 2750 }
class ____(Package): version("2.1") version("2.0") variant("v1", default=True) requires("~v1", when="@2.1") depends_on("w1") """, ) _pkgw2 = ( "w2", """\
W3
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-vectara/destination_vectara/config.py
{ "start": 705, "end": 4218 }
class ____(BaseModel): oauth2: OAuth2 customer_id: str = Field( ..., title="Customer ID", description="Your customer id as it is in the authenticaion url", order=2, group="account" ) corpus_name: str = Field(..., title="Corpus Name", description="The Name of Corpus to load data into", order=3, g...
VectaraConfig
python
streamlit__streamlit
lib/tests/streamlit/web/server/bidi_component_request_handler_test.py
{ "start": 1088, "end": 6751 }
class ____(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: self.component_manager = BidiComponentManager() self.temp_dir = tempfile.TemporaryDirectory() super().setUp() # Create a fake package root with a component asset_dir self.package_root = Path(self.temp_di...
BidiComponentRequestHandlerTest
python
numba__numba
numba/core/errors.py
{ "start": 2221, "end": 2434 }
class ____(NumbaWarning): """ Warning category for reporting pedantic messages. """ def __init__(self, msg, **kwargs): super().__init__(f"{msg}\n{pedantic_warning_info}")
NumbaPedanticWarning
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_cloud_formation.py
{ "start": 4500, "end": 6348 }
class ____: def test_init(self): op = CloudFormationDeleteStackOperator( task_id="cf_delete_stack_init", stack_name="fake-stack", # Generic hooks parameters aws_conn_id="fake-conn-id", region_name="us-east-1", verify=False, ...
TestCloudFormationDeleteStackOperator
python
pyinstaller__pyinstaller
bootloader/waflib/Utils.py
{ "start": 2352, "end": 3629 }
class ____(object): __slots__ = ('maxlen', 'table', 'head') def __init__(self, maxlen=100): self.maxlen = maxlen self.table = {} self.head = lru_node() self.head.next = self.head self.head.prev = self.head def __getitem__(self, key): node = self.table[key] ...
lru_cache
python
pandas-dev__pandas
pandas/tests/series/indexing/test_getitem.py
{ "start": 13926, "end": 17608 }
class ____: def test_getitem_boolean(self, string_series): ser = string_series mask = ser > ser.median() # passing list is OK result = ser[list(mask)] expected = ser[mask] tm.assert_series_equal(result, expected) tm.assert_index_equal(result.index, ser.index[...
TestGetitemBooleanMask
python
run-llama__llama_index
llama-index-core/tests/memory/test_memory_schema.py
{ "start": 248, "end": 3411 }
class ____: """Test schema functionality in Memory class.""" def test_from_defaults_schema_parameter(self): """Test Memory.from_defaults with and without schema parameter.""" # Without schema memory_no_schema = Memory.from_defaults( token_limit=1000, table_name="...
TestMemorySchema
python
falconry__falcon
tests/test_after_hooks.py
{ "start": 4900, "end": 9189 }
class ____: # Test that the decorator skips non-callables on_delete = False hook_as_class = ResourceAwareFluffiness() def __init__(self): # Test that the decorator skips non-callables self.on_patch = [] @falcon.after(fluffiness) def on_get(self, req, resp): self._captu...
ClassResourceWithAwareHooks
python
django__django
tests/forms_tests/field_tests/test_nullbooleanfield.py
{ "start": 155, "end": 3617 }
class ____(FormFieldAssertionsMixin, SimpleTestCase): def test_nullbooleanfield_clean(self): f = NullBooleanField() self.assertIsNone(f.clean("")) self.assertTrue(f.clean(True)) self.assertFalse(f.clean(False)) self.assertIsNone(f.clean(None)) self.assertFalse(f.clean...
NullBooleanFieldTest
python
doocs__leetcode
solution/1600-1699/1686.Stone Game VI/Solution.py
{ "start": 0, "end": 415 }
class ____: def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int: vals = [(a + b, i) for i, (a, b) in enumerate(zip(aliceValues, bobValues))] vals.sort(reverse=True) a = sum(aliceValues[i] for _, i in vals[::2]) b = sum(bobValues[i] for _, i in vals[1::2]) ...
Solution
python
sympy__sympy
doc/ext/numpydoc.py
{ "start": 4554, "end": 4946 }
class ____: directive_mangling_map = {} def __init__(self, *a, **kw): super().__init__(*a, **kw) self.wrap_mangling_directives() def wrap_mangling_directives(self): for name, objtype in list(self.directive_mangling_map.items()): self.directives[name] = wrap_mangling_dir...
ManglingDomainBase
python
getsentry__sentry
src/sentry/api/serializers/models/release.py
{ "start": 27757, "end": 29046 }
class ____(Serializer): """ The minimal representation of a release necessary for group events """ def get_attrs(self, item_list, user, **kwargs): last_commit_metadata_attrs = _get_last_commit_metadata(item_list, user) deploy_metadata_attrs = _get_last_deploy_metadata(item_list, user) ...
GroupEventReleaseSerializer
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 3512, "end": 13444 }
class ____(base_layer.Layer, metaclass=abc.ABCMeta): """Encapsulates metric logic and state. Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. **kwargs: Additional layer keywords arguments. Standalone usage: ```python m = SomeMetric(......
Metric
python
bokeh__bokeh
src/bokeh/models/renderers/renderer.py
{ "start": 1872, "end": 2376 }
class ____(Model): """A collection of renderers. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) visible = Bool(default=True, help=""" Makes all grouped renderers visible or not. """) #---...
RendererGroup
python
tornadoweb__tornado
tornado/test/iostream_test.py
{ "start": 44036, "end": 47291 }
class ____(AsyncTestCase): # This test ensures that hostname checks are working correctly after # #3337 revealed that we have no test coverage in this area, and we # removed a manual hostname check that was needed only for very old # versions of python. def setUp(self): super().setUp() ...
TestIOStreamCheckHostname
python
getsentry__sentry
src/sentry/api/endpoints/frontend_version.py
{ "start": 324, "end": 596 }
class ____(Endpoint): owner = ApiOwner.HYBRID_CLOUD publish_status = {"GET": ApiPublishStatus.PRIVATE} permission_classes = () def get(self, request: Request) -> Response: return Response({"version": get_frontend_commit_sha()})
FrontendVersionEndpoint
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 233279, "end": 239601 }
class ____(IdentityOptions, FetchedValue, SchemaItem): """Defines an identity column, i.e. "GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY" syntax. The :class:`.Identity` construct is an inline construct added to the argument list of a :class:`_schema.Column` object:: from sqlalchemy import Ide...
Identity
python
kamyu104__LeetCode-Solutions
Python/sum-of-digits-of-string-after-convert.py
{ "start": 61, "end": 523 }
class ____(object): def getLucky(self, s, k): """ :type s: str :type k: int :rtype: int """ total = reduce(lambda total, x: total+sum(divmod((ord(x)-ord('a')+1), 10)), s, 0) while k > 1 and total > 9: new_total = 0 while total: ...
Solution
python
pytorch__pytorch
torch/_inductor/template_heuristics/params.py
{ "start": 97, "end": 633 }
class ____(ABC): """Abstract base class for kernel template parameters.""" @abstractmethod def to_kwargs(self) -> dict[str, Any]: """Convert params to kwargs dict for template.choice_or_none()""" @abstractmethod def to_serializeable_dict(self) -> dict[str, Any]: """Convert params t...
KernelTemplateParams
python
wandb__wandb
wandb/apis/public/files.py
{ "start": 1984, "end": 6936 }
class ____(SizedPaginator["File"]): """A lazy iterator over a collection of `File` objects. Access and manage files uploaded to W&B during a run. Handles pagination automatically when iterating through large collections of files. Example: ```python from wandb.apis.public.files import Files ...
Files
python
ray-project__ray
rllib/models/preprocessors.py
{ "start": 10612, "end": 12332 }
class ____(Preprocessor): """Preprocesses each dict value, then flattens it all into a vector. RLlib models will unpack the flattened output before _build_layers_v2(). """ @override(Preprocessor) def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: assert isinstance(sel...
DictFlatteningPreprocessor
python
altair-viz__altair
altair/expr/__init__.py
{ "start": 2097, "end": 81699 }
class ____(_ExprRef, metaclass=_ExprMeta): """ Utility providing *constants* and *classmethods* to construct expressions. `Expressions`_ can be used to write basic formulas that enable custom interactions. Alternatively, an `inline expression`_ may be defined via :class:`expr()`. Parameters -...
expr
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 52131, "end": 60193 }
class ____(Cache): """ Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and cross-attention caches. See `Cache` for details on common methods that are implemented by all cache classes. Args: caches (`Iterable`): Usually an ...
EncoderDecoderCache
python
huggingface__transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
{ "start": 15590, "end": 19355 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([MegatronBertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]) # The final layer norm. We removed the 1st LN, moved LN to each hidden layer and t...
MegatronBertEncoder
python
keras-team__keras
keras/src/regularizers/regularizers.py
{ "start": 7945, "end": 8769 }
class ____(Regularizer): """A regularizer that applies a L2 regularization penalty. The L2 regularization penalty is computed as: `loss = l2 * reduce_sum(square(x))` L2 may be passed to a layer as a string identifier: >>> dense = Dense(3, kernel_regularizer='l2') In this case, the default va...
L2
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/ScatterPlotWidget.py
{ "start": 403, "end": 11483 }
class ____(QtWidgets.QSplitter): """ This is a high-level widget for exploring relationships in tabular data. Given a multi-column record array, the widget displays a scatter plot of a specific subset of the data. Includes controls for selecting the columns to plot, filtering data, and dete...
ScatterPlotWidget
python
h5py__h5py
examples/swmr_inotify_example.py
{ "start": 924, "end": 2673 }
class ____(pyinotify.ProcessEvent): def monitor_dataset(self, filename, datasetname): logging.info("Opening file %s", filename) self.f = h5py.File(filename, 'r', libver='latest', swmr=True) logging.debug("Looking up dataset %s"%datasetname) self.dset = self.f[datasetname] s...
EventHandler
python
dagster-io__dagster
examples/airlift-migration-tutorial/tutorial_example/airflow_dags/dags.py
{ "start": 1652, "end": 4097 }
class ____(BaseOperator): def __init__( self, table_name: str, csv_path: Path, duckdb_path: Path, duckdb_database_name: str, *args, duckdb_schema: Optional[str] = None, **kwargs, ): self._table_name = table_name self._csv_path = csv...
ExportDuckDBToCSV
python
huggingface__transformers
src/transformers/models/efficientnet/modeling_efficientnet.py
{ "start": 6192, "end": 7570 }
class ____(nn.Module): r""" This corresponds to the Squeeze and Excitement phase of each block in the original implementation. """ def __init__(self, config: EfficientNetConfig, in_dim: int, expand_dim: int, expand: bool = False): super().__init__() self.dim = expand_dim if expand else ...
EfficientNetSqueezeExciteLayer
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py
{ "start": 827, "end": 1125 }
class ____(object): __slots__ = 'lexer', 'source', 'options', 'prev_end', 'token' def __init__(self, source, options): self.lexer = Lexer(source) self.source = source self.options = options self.prev_end = 0 self.token = self.lexer.next_token()
Parser
python
numba__numba
numba/tests/test_mixed_tuple_unroller.py
{ "start": 2313, "end": 2597 }
class ____(FunctionPass): _name = "reset_the_type_information" def __init__(self): FunctionPass.__init__(self) def run_pass(self, state): state.typemap = None state.return_type = None state.calltypes = None return True
ResetTypeInfo
python
getsentry__sentry
src/sentry/relocation/services/relocation_export/impl.py
{ "start": 1285, "end": 5694 }
class ____(RegionRelocationExportService): def request_new_export( self, *, relocation_uuid: str, requesting_region_name: str, replying_region_name: str, org_slug: str, encrypt_with_public_key: bytes, ) -> None: logger_data = { "uuid":...
DBBackedRelocationExportService
python
realpython__materials
arcade-platformer/arcade_platformer/13_pause_view.py
{ "start": 3289, "end": 4717 }
class ____(arcade.View): """Show instructions to the player""" def __init__(self) -> None: """Create instructions screen""" super().__init__() # Find the instructions image in the image folder instructions_image_path = ( ASSETS_PATH / "images" / "instructions_image....
InstructionsView
python
pennersr__django-allauth
allauth/socialaccount/providers/shopify/views.py
{ "start": 1965, "end": 3592 }
class ____(OAuth2LoginView): def dispatch(self, request, *args, **kwargs): is_embedded = ( getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) .get("shopify", {}) .get("IS_EMBEDDED", False) ) if is_embedded: # TODO: This bypasses LOGIN_ON_GET, but...
ShopifyOAuth2LoginView
python
django__django
django/contrib/admin/templatetags/admin_list.py
{ "start": 11648, "end": 19156 }
class ____(list): """ Wrapper class used to return items in a list_editable changelist, annotated with the form object for error reporting purposes. Needed to maintain backwards compatibility with existing admin templates. """ def __init__(self, form, *items): self.form = form s...
ResultList
python
lepture__authlib
authlib/oauth2/rfc6749/grants/authorization_code.py
{ "start": 529, "end": 15604 }
class ____(BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin): """The authorization code grant type is used to obtain both access tokens and refresh tokens and is optimized for confidential clients. Since this is a redirection-based flow, the client must be capable of interacting with the resour...
AuthorizationCodeGrant
python
doocs__leetcode
solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/Solution.py
{ "start": 0, "end": 579 }
class ____: def __init__(self, rects: List[List[int]]): self.rects = rects self.s = [0] * len(rects) for i, (x1, y1, x2, y2) in enumerate(rects): self.s[i] = self.s[i - 1] + (x2 - x1 + 1) * (y2 - y1 + 1) def pick(self) -> List[int]: v = random.randint(1, self.s[-1]) ...
Solution
python
getsentry__sentry
fixtures/page_objects/global_selection.py
{ "start": 29, "end": 1703 }
class ____(BasePage): def get_selected_project_slug(self): return self.browser.element('[data-test-id="page-filter-project-selector"]').text def get_selected_environment(self): return self.browser.element('[data-test-id="page-filter-environment-selector"]').text def get_selected_date(self)...
GlobalSelectionPage
python
langchain-ai__langchain
libs/langchain/langchain_classic/retrievers/multi_query.py
{ "start": 1667, "end": 7770 }
class ____(BaseRetriever): """Given a query, use an LLM to write a set of queries. Retrieve docs for each query. Return the unique union of all retrieved docs. """ retriever: BaseRetriever llm_chain: Runnable verbose: bool = True parser_key: str = "lines" """DEPRECATED. parser_key is n...
MultiQueryRetriever
python
ansible__ansible
test/units/module_utils/facts/test_collector.py
{ "start": 1972, "end": 4610 }
class ____(unittest.TestCase): def _assert_equal_detail(self, obj1, obj2): msg = 'objects are not equal\n%s\n\n!=\n\n%s' % (pprint.pformat(obj1), pprint.pformat(obj2)) return self.assertEqual(obj1, obj2, msg) def test(self): collector_names = ['distribution', 'all_ipv4_addresses', ...
TestSelectCollectorNames
python
tensorflow__tensorflow
tensorflow/python/types/trace.py
{ "start": 8579, "end": 9013 }
class ____(metaclass=abc.ABCMeta): """Contains information scoped to the tracing of multiple objects. `TracingContext` is a container class for flags and variables that have any kind of influence on the tracing behaviour of the class implementing the __tf_tracing_type__. This context will be shared across all ...
TracingContext
python
redis__redis-py
redis/asyncio/multidb/failure_detector.py
{ "start": 98, "end": 618 }
class ____(ABC): @abstractmethod async def register_failure(self, exception: Exception, cmd: tuple) -> None: """Register a failure that occurred during command execution.""" pass @abstractmethod async def register_command_execution(self, cmd: tuple) -> None: """Register a comman...
AsyncFailureDetector
python
pytorch__pytorch
torch/_export/db/examples/list_unpack.py
{ "start": 42, "end": 568 }
class ____(torch.nn.Module): """ Lists are treated as static construct, therefore unpacking should be erased after tracing. """ def forward(self, args: list[torch.Tensor]): """ Lists are treated as static construct, therefore unpacking should be erased after tracing. ...
ListUnpack
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 16607, "end": 18623 }
class ____(LoggingEventHandler): """ For backwards-compatibility. Please use :class:`LoggingEventHandler` instead. """ def generate_sub_moved_events(src_dir_path, dest_dir_path): """Generates an event list of :class:`DirMovedEvent` and :class:`FileMovedEvent` objects for all the files and dire...
LoggingFileSystemEventHandler
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 61319, "end": 62040 }
class ____(FieldValues): """ Values for `DurationField` with a custom output format. """ valid_inputs = { '13': datetime.timedelta(seconds=13), 'P3DT08H32M01.000123S': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123), 'PT8H1M': datetime.timedelta(hours...
TestISOOutputFormatDurationField
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_gcs.py
{ "start": 14827, "end": 16546 }
class ____: OPERATOR = GCSObjectsWithPrefixExistenceSensor( task_id="gcs-obj-prefix", bucket=TEST_BUCKET, prefix=TEST_OBJECT, google_cloud_conn_id=TEST_GCP_CONN_ID, deferrable=True, ) @mock.patch("airflow.providers.google.cloud.sensors.gcs.GCSHook") def test_gcs_...
TestGCSObjectsWithPrefixExistenceAsyncSensor
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/nystroem_sampler.py
{ "start": 551, "end": 4578 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__( self, kernel, n_components, gamma=1.0, degree=3, coef0=1, random_state=None ): self.kernel = kernel self.n_components = n_components self.gamma = gamma self.degree = degree self.coef0 = coef0 sel...
Nystroem
python
numpy__numpy
benchmarks/benchmarks/bench_ufunc.py
{ "start": 7840, "end": 8348 }
class ____(Benchmark): param_names = ['margs', 'msize'] params = [[0, (0, 0), (-1, 0), [0, -1]], ['small', 'big']] def setup(self, margs, msize): self.xs = np.random.uniform(-1, 1, 6).reshape(2, 3) self.xl = np.random.uniform(-1, 1, 50 * 50).reshape(50, 50) def time_metho...
NDArrayGetItem
python
django__django
tests/postgres_tests/test_search.py
{ "start": 5242, "end": 6377 }
class ____(GrailTestData, PostgreSQLTestCase): def test_existing_vector(self): Line.objects.update(dialogue_search_vector=SearchVector("dialogue")) searched = Line.objects.filter( dialogue_search_vector=SearchQuery("Robin killed") ) self.assertSequenceEqual(searched, [sel...
SearchVectorFieldTest
python
django__django
tests/admin_autodiscover/tests.py
{ "start": 74, "end": 742 }
class ____(SimpleTestCase): """ Test for bug #8245 - don't raise an AlreadyRegistered exception when using autodiscover() and an admin.py module contains an error. """ def test_double_call_autodiscover(self): # The first time autodiscover is called, we should get our real error. wit...
AdminAutoDiscoverTests
python
huggingface__transformers
src/transformers/models/mvp/modeling_mvp.py
{ "start": 39430, "end": 46491 }
class ____(MvpPreTrainedModel): _keys_to_ignore_on_load_unexpected = ["final_logits_bias"] _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: MvpConfig): super().__init__(config) ...
MvpModel
python
pypa__pip
src/pip/_internal/models/candidate.py
{ "start": 220, "end": 753 }
class ____: """Represents a potential "candidate" for installation.""" __slots__ = ["name", "version", "link"] name: str version: Version link: Link def __init__(self, name: str, version: str, link: Link) -> None: object.__setattr__(self, "name", name) object.__setattr__(self,...
InstallationCandidate
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 8628, "end": 9231 }
class ____(VirtualenvException): def __init__(self, message=None, **kwargs): if not message: message = "Failed to create virtual environment." self.message = message extra = kwargs.pop("extra", None) if extra is not None and isinstance(extra, str): extra = uns...
VirtualenvCreationException
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1472787, "end": 1474726 }
class ____(sgqlc.types.Type, Node, UniformResourceLocatable): """Represents a 'review_dismissed' event on a given issue or pull request. """ __schema__ = github_schema __field_names__ = ( "actor", "created_at", "database_id", "dismissal_message", "dismissal_m...
ReviewDismissedEvent
python
walkccc__LeetCode
solutions/2841. Maximum Sum of Almost Unique Subarray/2841.py
{ "start": 0, "end": 462 }
class ____: def maxSum(self, nums: list[int], m: int, k: int) -> int: ans = 0 summ = 0 count = collections.Counter() for i, num in enumerate(nums): summ += num count[num] += 1 if i >= k: numToRemove = nums[i - k] summ -= numToRemove count[numToRemove] -= 1 ...
Solution
python
django-extensions__django-extensions
tests/management/commands/test_print_user_for_session.py
{ "start": 271, "end": 645 }
class ____(TestCase): """Test if print_user_for_session command raises exception.""" def test_should_raise_CommandError_if_session_key_contains_exclamination_mark(self): with self.assertRaisesRegex(CommandError, "malformed session key"): call_command("print_user_for_session", "l6hxnwblpvrfu...
PrintUserForSessionExceptionsTests
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_17.py
{ "start": 2221, "end": 2529 }
class ____[T: (DoesNotExist1, DoesNotExist2)](list[T]): ... # F821: Undefined name `DoesNotExist1`, Undefined name `DoesNotExist2` # Same in defaults type Foo[T = DoesNotExist] = T # F821: Undefined name `DoesNotExist` def foo[T = DoesNotExist](t: T) -> T: return t # F821: Undefined name `DoesNotExist`
Foo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 15737, "end": 15826 }
class ____(IterableExportStreamAdjustableRange): data_field = "emailBounce"
EmailBounce
python
pytorch__pytorch
torchgen/_autoheuristic/train_decision.py
{ "start": 23129, "end": 23616 }
class ____: # If the model predicted the wrong choice, this is the maximum speedup of the best choice over the predicted choice max_speedup: float # For all wrong predictions, this is the geometric mean of the speedups of the best choices over the predicted choices gmean_speedup: float def to_map(s...
WrongSpeedupMetrics
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint.py
{ "start": 48398, "end": 66954 }
class ____: """Saves and restores a `Trackable` object and its dependencies. See `Trackable` for details of dependency management. `Saver` wraps `tf.compat.v1.train.Saver` for saving, including extra information about the graph of dependencies between Python objects. When restoring, it uses this information ...
TrackableSaver