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 | catalyst-team__catalyst | examples/detection/models/yolo_x.py | {
"start": 508,
"end": 1258
} | class ____(nn.Module):
"""A Conv2d -> Batchnorm -> silu/leaky relu block"""
def __init__(
self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act="silu"
):
super().__init__()
# same padding
pad = (ksize - 1) // 2
self.conv = nn.Conv2d(
i... | BaseConv |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 54442,
"end": 54818
} | class ____(BaseModel):
"""
Response of updating a Human-in-the-loop detail.
"""
responded_by: HITLUser
responded_at: Annotated[datetime, Field(title="Responded At")]
chosen_options: Annotated[list[str], Field(min_length=1, title="Chosen Options")]
params_input: Annotated[dict[str, Any] | No... | HITLDetailResponse |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/sagemaker.py | {
"start": 4880,
"end": 7946
} | class ____(BaseTrigger):
"""Trigger to wait for a sagemaker pipeline execution to finish."""
class Type(IntEnum):
"""Type of waiter to use."""
COMPLETE = 1
STOPPED = 2
def __init__(
self,
waiter_type: Type,
pipeline_execution_arn: str,
waiter_delay:... | SageMakerPipelineTrigger |
python | ApeWorX__ape | src/ape/contracts/base.py | {
"start": 10429,
"end": 12904
} | class ____(ContractMethodHandler):
def __call__(self, *args, **kwargs) -> Any:
self._validate_is_contract()
selected_abi = _select_method_abi(self.abis, args)
arguments = self.conversion_manager.convert_method_args(selected_abi, args)
return ContractCall(
abi=selected_ab... | ContractCallHandler |
python | realpython__materials | arcade-platformer/arcade_platformer/arcade_platformer.py | {
"start": 5607,
"end": 7462
} | class ____(arcade.View):
"""Shown when the game is paused"""
def __init__(self, game_view: arcade.View) -> None:
"""Create the pause screen"""
# Initialize the parent
super().__init__()
# Store a reference to the underlying view
self.game_view = game_view
# Sto... | PauseView |
python | joke2k__faker | faker/providers/phone_number/zh_CN/__init__.py | {
"start": 49,
"end": 681
} | class ____(PhoneNumberProvider):
phonenumber_prefixes = [
134,
135,
136,
137,
138,
139,
147,
150,
151,
152,
157,
158,
159,
182,
187,
188,
130,
131,
132,
145... | Provider |
python | numba__numba | numba/core/caching.py | {
"start": 5891,
"end": 6278
} | class ____(InTreeCacheLocator):
"""
A locator for functions backed by a regular Python module with a
writable __pycache__ directory. This version is agnostic to filesystem differences,
e.g. timestamp precision with milliseconds.
"""
def get_source_stamp(self):
st = super().get_source_st... | InTreeCacheLocatorFsAgnostic |
python | wntrblm__nox | nox/logger.py | {
"start": 2511,
"end": 5364
} | class ____(logging.getLoggerClass()): # type: ignore[misc]
def __init__(self, name: str, level: int = logging.NOTSET):
super().__init__(name, level)
logging.addLevelName(SESSION_INFO, "SESSION_INFO")
logging.addLevelName(SUCCESS, "SUCCESS")
logging.addLevelName(OUTPUT, "OUTPUT")
... | LoggerWithSuccessAndOutput |
python | kubernetes-client__python | kubernetes/client/models/v1_storage_class_list.py | {
"start": 383,
"end": 6951
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1StorageClassList |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 6736,
"end": 6883
} | class ____:
class __getattr__():
pass
#? []
WeirdGetattr().something
# -----------------
# private vars
# -----------------
| WeirdGetattr |
python | apache__airflow | providers/yandex/src/airflow/providers/yandex/hooks/yq.py | {
"start": 1123,
"end": 3503
} | class ____(YandexCloudBaseHook):
"""A hook for Yandex Query."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
config = YQHttpClientConfig(
token=self._get_iam_token(), project=self.default_folder_id, user_agent=provider_user_agent()
)
... | YQHook |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass11.py | {
"start": 666,
"end": 902
} | class ____(metaclass=MetaB):
var0: int
# This should generate an error
ClassB.var0 = ""
ClassB.var1 = ""
ClassB().var0 = 1
# This should generate an error
ClassB().var0 = ""
# This should generate an error
ClassB().var1 = ""
| ClassB |
python | openai__openai-python | src/openai/types/beta/threads/runs/tool_call_delta_object.py | {
"start": 275,
"end": 615
} | class ____(BaseModel):
type: Literal["tool_calls"]
"""Always `tool_calls`."""
tool_calls: Optional[List[ToolCallDelta]] = None
"""An array of tool calls the run step was involved in.
These can be associated with one of three types of tools: `code_interpreter`,
`file_search`, or `function`.
... | ToolCallDeltaObject |
python | django__django | tests/admin_views/models.py | {
"start": 18589,
"end": 18698
} | class ____(models.Model):
start_date = models.DateTimeField()
price = models.IntegerField()
| Reservation |
python | pandas-dev__pandas | pandas/io/formats/info.py | {
"start": 29668,
"end": 30487
} | class ____(_TableBuilderAbstract):
"""
Abstract builder for series info table.
Parameters
----------
info : SeriesInfo.
Instance of SeriesInfo.
"""
def __init__(self, *, info: SeriesInfo) -> None:
self.info: SeriesInfo = info
def get_lines(self) -> list[str]:
s... | _SeriesTableBuilder |
python | xlwings__xlwings | xlwings/pro/reports/markdown.py | {
"start": 1007,
"end": 1380
} | class ____(Style):
def __init__(
self,
display_name=None,
color=None,
size=None,
bold=None,
italic=None,
name=None,
):
super().__init__(display_name=display_name)
self.color = color
self.size = size
self.bold = bold
... | FontStyle |
python | astropy__astropy | astropy/visualization/wcsaxes/frame.py | {
"start": 448,
"end": 4139
} | class ____:
"""
A single side of an axes.
This does not need to be a straight line, but represents a 'side' when
determining which part of the frame to put labels and ticks on.
Parameters
----------
parent_axes : `~astropy.visualization.wcsaxes.WCSAxes`
The parent axes
transfor... | Spine |
python | huggingface__transformers | src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py | {
"start": 2876,
"end": 3235
} | class ____:
"""Fake command line arguments needed by mask2former/detectron implementation"""
config_file: str
def setup_cfg(args: Args):
# load config from file and command-line arguments
cfg = get_cfg()
add_deeplab_config(cfg)
add_maskformer2_config(cfg)
cfg.merge_from_file(args.config_f... | Args |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Operators.py | {
"start": 55,
"end": 438
} | class ____(Node):
"""Generic node for performing any operation like Out = In.fn()"""
def __init__(self, name, fn):
self.fn = fn
Node.__init__(self, name, terminals={
'In': {'io': 'in'},
'Out': {'io': 'out', 'bypass': 'In'}
})
def process(self, **args)... | UniOpNode |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 213532,
"end": 214210
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("BypassPullRequestAllowanceEdge"), graphql_name="edges"
)
... | BypassPullRequestAllowanceConnection |
python | MongoEngine__mongoengine | mongoengine/base/metaclasses.py | {
"start": 17656,
"end": 18014
} | class ____(dict):
"""Custom dictionary for meta classes.
Handles the merging of set indexes
"""
_merge_options = ("indexes",)
def merge(self, new_options):
for k, v in new_options.items():
if k in self._merge_options:
self[k] = self.get(k, []) + v
el... | MetaDict |
python | ray-project__ray | rllib/models/torch/misc.py | {
"start": 6998,
"end": 9323
} | class ____(nn.Module):
"""Simple mock of tf.slim Conv2d"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]],
padding: Union[int, Tuple[int, int]],
# Defaulting these to nn.[.... | SlimConv2d |
python | explosion__spaCy | spacy/lang/zh/__init__.py | {
"start": 11154,
"end": 11387
} | class ____(BaseDefaults):
config = load_config_from_str(DEFAULT_CONFIG)
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
writing_system = {"direction": "ltr", "has_case": False, "has_letters": False}
| ChineseDefaults |
python | sympy__sympy | sympy/functions/special/zeta_functions.py | {
"start": 18389,
"end": 21000
} | class ____(DefinedFunction):
r"""
Dirichlet eta function.
Explanation
===========
For $\operatorname{Re}(s) > 0$ and $0 < x \le 1$, this function is defined as
.. math:: \eta(s, a) = \sum_{n=0}^\infty \frac{(-1)^n}{(n+a)^s}.
It admits a unique analytic continuation to all of $\mathbb{C}$... | dirichlet_eta |
python | jina-ai__jina | tests/integration/streaming/test_clients_streaming.py | {
"start": 1356,
"end": 1730
} | class ____(Executor):
"""Fast Executor"""
@requests
def foo(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.tags['executor'] = time.time()
print(
f'in FastExecutor: {doc.id}, time: {readable_time_from(doc.tags["executor"])}, {doc.tags["executor"]}'... | FastExecutor |
python | django__django | tests/migrations/test_migrations_squashed_replaced_order/app1/0002_squashed_initial.py | {
"start": 35,
"end": 286
} | class ____(migrations.Migration):
initial = True
replaces = [
("app1", "0001_initial"),
]
dependencies = [
("app1", "0001_squashed_initial"),
("app2", "0001_squashed_initial"),
]
operations = []
| Migration |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 164899,
"end": 166070
} | class ____(TestCase):
def test_basic(self):
for iterable, expected in [
([], True),
([1, 2, 3], True),
([1, 1], False),
([1, 2, 3, 1], False),
([1, 2, 3, '1'], True),
]:
with self.subTest(args=(iterable,)):
self.... | AllUniqueTests |
python | huggingface__transformers | src/transformers/data/processors/glue.py | {
"start": 11832,
"end": 13532
} | class ____(DataProcessor):
"""Processor for the STS-B data set (GLUE version)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
def get_example_from_tensor_dict(self, tensor_dict):
"""See... | StsbProcessor |
python | kamyu104__LeetCode-Solutions | Python/alice-and-bob-playing-flower-game.py | {
"start": 45,
"end": 211
} | class ____(object):
def flowerGame(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
return (n*m)//2
| Solution |
python | PyCQA__pylint | tests/functional/a/attribute_defined_outside_init.py | {
"start": 1084,
"end": 1289
} | class ____:
def __init__(self, param):
self.prop = param
@property
def prop(self):
return self.__prop
@prop.setter
def prop(self, value):
self.__prop = value
| Mine |
python | numba__numba | numba/tests/test_dataflow.py | {
"start": 1194,
"end": 4848
} | class ____(TestCase):
def test_assignments(self, flags=force_pyobj_jit_opt):
pyfunc = assignments
cfunc = jit((types.int32,), **flags)(pyfunc)
for x in [-1, 0, 1]:
self.assertPreciseEqual(pyfunc(x), cfunc(x))
def test_assignments2(self, flags=force_pyobj_jit_opt):
p... | TestDataFlow |
python | keras-team__keras | keras/src/layers/pooling/global_max_pooling2d.py | {
"start": 261,
"end": 2451
} | class ____(BaseGlobalPooling):
"""Global max pooling operation for 2D data.
Args:
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, height, width, channel... | GlobalMaxPooling2D |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 12417,
"end": 12468
} | class ____(TypedDict):
values: list[str]
| MyObject |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/marker/_colorbar.py | {
"start": 233,
"end": 61796
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl.marker"
_path_str = "scatterpolargl.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
... | ColorBar |
python | sympy__sympy | sympy/matrices/repmatrix.py | {
"start": 18762,
"end": 33049
} | class ____(RepMatrix):
"""Mutable matrix based on DomainMatrix as the internal representation"""
#
# MutableRepMatrix is a subclass of RepMatrix that adds/overrides methods
# to make the instances mutable. MutableRepMatrix is a superclass for both
# MutableDenseMatrix and MutableSparseMatrix.
#... | MutableRepMatrix |
python | django__django | tests/auth_tests/test_models.py | {
"start": 805,
"end": 1727
} | class ____(TestCase):
def test_user_natural_key(self):
staff_user = User.objects.create_user(username="staff")
self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user)
self.assertEqual(staff_user.natural_key(), ("staff",))
async def test_auser_natural_key(self):
st... | NaturalKeysTestCase |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_whoosh_backend.py | {
"start": 1294,
"end": 1490
} | class ____(WhooshMockSearchIndex):
def prepare_text(self, obj):
if obj.author == "daniel3":
raise SkipDocument
return obj.author
| WhooshMockSearchIndexWithSkipDocument |
python | jina-ai__jina | jina/orchestrate/pods/__init__.py | {
"start": 9852,
"end": 13173
} | class ____(BasePod):
"""
:class:`Pod` is a thread/process- container of :class:`BaseRuntime`. It leverages :class:`multiprocessing.Process` to manage the lifecycle of a :class:`BaseRuntime` object in a robust way.
A :class:`Pod` must be equipped with a proper :class:`Runtime` class to work.
"""
de... | Pod |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/slider.py | {
"start": 144,
"end": 3914
} | class ____(WidgetParameterItem):
slider: QtWidgets.QSlider
span: np.ndarray
charSpan: np.ndarray
def __init__(self, param, depth):
# Bind emitter to self to avoid garbage collection
self.emitter = Emitter()
self.sigChanging = self.emitter.sigChanging
self._suffix = None
... | SliderParameterItem |
python | matplotlib__matplotlib | lib/matplotlib/animation.py | {
"start": 27377,
"end": 31881
} | class ____(FileMovieWriter):
"""Writer for JavaScript-based HTML movies."""
supported_formats = ['png', 'jpeg', 'tiff', 'svg']
@classmethod
def isAvailable(cls):
return True
def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
metadata=None, embed_frames=... | HTMLWriter |
python | ray-project__ray | rllib/connectors/common/module_to_agent_unmapping.py | {
"start": 431,
"end": 1636
} | class ____(ConnectorV2):
"""Performs flipping of `data` from ModuleID- to AgentID based mapping.
Before mapping:
data[module1] -> [col, e.g. ACTIONS]
-> [dict mapping episode-identifying tuples to lists of data]
data[module2] -> ...
After mapping:
data[ACTIONS]: [dict mapping episode-ident... | ModuleToAgentUnmapping |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/select_rebuild.py | {
"start": 150,
"end": 594
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield Select[int]((("1", 1), ("2", 2)))
yield Button("Rebuild")
def on_button_pressed(self):
self.query_one(Select).set_options((
("This", 0), ("Should", 1), ("Be", 2),
("What", 3), ("Goes", 4), ("Into",... | SelectRebuildApp |
python | astropy__astropy | astropy/utils/data_info.py | {
"start": 26329,
"end": 27584
} | class ____(BaseColumnInfo):
@property
def name(self):
return self._attrs.get("name")
@name.setter
def name(self, name: str | None):
if name is None:
new_name = None
elif isinstance(name, str):
new_name = str(name)
else:
raise TypeError... | MixinInfo |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-make-array-equalindromic.py | {
"start": 93,
"end": 2001
} | class ____(object):
def minimumCost(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
while mid <= right:
... | Solution |
python | sanic-org__sanic | sanic/response/types.py | {
"start": 8646,
"end": 16230
} | class ____(HTTPResponse):
"""Convenience class for JSON responses
HTTP response to be sent back to the client, when the response
is of json type. Offers several utilities to manipulate common
json data types.
Args:
body (Optional[Any], optional): The body content to be returned. Defaults t... | JSONResponse |
python | nedbat__coveragepy | coverage/sysmon.py | {
"start": 6675,
"end": 19814
} | class ____(Tracer):
"""Python implementation of the raw data tracer for PEP669 implementations."""
# One of these will be used across threads. Be careful.
def __init__(self, tool_id: int) -> None:
# Attributes set from the collector:
self.data: TTraceData
self.trace_arcs = False
... | SysMonitor |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 4570,
"end": 4723
} | class ____(BaseIntType):
@classmethod
def validate(cls, value: Any) -> None:
cls.validate_int_in_range(value, 0, 4294967295)
| XsdUnsignedInt |
python | ansible__ansible | lib/ansible/modules/group.py | {
"start": 4022,
"end": 9009
} | class ____(object):
"""
This is a generic Group manipulation class that is subclassed
based on platform.
A subclass may wish to override the following action methods:-
- group_del()
- group_add()
- group_mod()
All subclasses MUST define platform and distribution (which may be Non... | Group |
python | joke2k__faker | faker/providers/person/de_LU/__init__.py | {
"start": 81,
"end": 29592
} | class ____(PersonProvider):
# Source for last names: https://nachnamen.net/luxemburg
last_names = OrderedDict(
(
("Schmit", 6799),
("Muller", 5784),
("Weber", 4858),
("Wagner", 4837),
("Hoffmann", 4628),
("Thill", 3304),
... | Provider |
python | django__django | tests/model_forms/tests.py | {
"start": 2384,
"end": 2483
} | class ____(forms.ModelForm):
class Meta:
model = Book
fields = "__all__"
| BookForm |
python | mitmproxy__pdoc | test/testdata/misc_py314.py | {
"start": 0,
"end": 69
} | class ____(RuntimeError):
"""custom exception type"""
| CustomException |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 28144,
"end": 32795
} | class ____:
def test_password_change_email(self, pyramid_request, pyramid_config, monkeypatch):
stub_user = pretend.stub(
id="id",
username="username",
name="",
email="email@example.com",
primary_email=pretend.stub(email="email@example.com", verifi... | TestPasswordChangeEmail |
python | django__django | tests/template_tests/syntax_tests/test_cache.py | {
"start": 188,
"end": 5649
} | class ____(SimpleTestCase):
libraries = {
"cache": "django.templatetags.cache",
"custom": "template_tests.templatetags.custom",
}
def tearDown(self):
cache.clear()
@setup({"cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}"})
def test_cache03(self):
... | CacheTagTests |
python | encode__starlette | starlette/authentication.py | {
"start": 3637,
"end": 3823
} | class ____:
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
raise NotImplementedError() # pragma: no cover
| AuthenticationBackend |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 737,
"end": 1122
} | class ____(dict):
def omit_zero_len(self):
return len({k: v for k, v in self.items() if v or k in ALWAYS_KEEP_ZERO_KEYS})
# keep zero for specific keys, omit other zero values
def __str__(self):
return str({k: v for k, v in self.items() if v or k in ALWAYS_KEEP_ZERO_KEYS})
# no filter
... | OmitZeroDict |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/unit_tests/integration/test_rest_stream.py | {
"start": 2727,
"end": 3670
} | class ____(TestCase):
def setUp(self) -> None:
self._config = ConfigBuilder().client_id(_CLIENT_ID).client_secret(_CLIENT_SECRET).refresh_token(_REFRESH_TOKEN)
@HttpMocker()
def test_given_error_on_fetch_chunk_of_properties_when_read_then_retry(self, http_mocker: HttpMocker) -> None:
given_... | FullRefreshTest |
python | rapidsai__cudf | python/cudf/cudf/core/window/ewm.py | {
"start": 397,
"end": 7922
} | class ____(_RollingBase):
r"""
Provide exponential weighted (EW) functions.
Available EW functions: ``mean()``
Exactly one parameter: ``com``, ``span``, ``halflife``, or ``alpha``
must be provided.
Parameters
----------
com : float, optional
Specify decay in terms of center of m... | ExponentialMovingWindow |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_ec2.py | {
"start": 1184,
"end": 4023
} | class ____:
def test_ec2_state_sensor_trigger_serialize(self):
test_ec2_state_sensor = EC2StateSensorTrigger(
instance_id=TEST_INSTANCE_ID,
target_state=TEST_TARGET_STATE,
aws_conn_id=TEST_CONN_ID,
region_name=TEST_REGION_NAME,
poll_interval=TEST_P... | TestEC2StateSensorTrigger |
python | gevent__gevent | src/gevent/tests/test__threading_2.py | {
"start": 22881,
"end": 23116
} | class ____(lock_tests.RLockTests):
# See comments at the top of the file for the difference
# between this and RLockTests, and why they both matter
locktype = staticmethod(threading.NativeRLock)
@skipDueToHang
| NativeRLockTests |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/components/reward_providers/gail_reward_provider.py | {
"start": 945,
"end": 2655
} | class ____(BaseRewardProvider):
def __init__(self, specs: BehaviorSpec, settings: GAILSettings) -> None:
super().__init__(specs, settings)
self._ignore_done = False
self._discriminator_network = DiscriminatorNetwork(specs, settings)
self._discriminator_network.to(default_device())
... | GAILRewardProvider |
python | aimacode__aima-python | text.py | {
"start": 4745,
"end": 7882
} | class ____:
"""A very simple Information Retrieval System, as discussed in Sect. 23.2.
The constructor s = IRSystem('the a') builds an empty system with two
stopwords. Next, index several documents with s.index_document(text, url).
Then ask queries with s.query('query words', n) to retrieve the top n
... | IRSystem |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/api.py | {
"start": 697,
"end": 6910
} | class ____(FacebookAdsApi):
"""Custom Facebook API class to intercept all API calls and handle call rate limits"""
MAX_RATE, MAX_PAUSE_INTERVAL = (95, timedelta(minutes=10))
MIN_RATE, MIN_PAUSE_INTERVAL = (85, timedelta(minutes=2))
# see `_should_restore_page_size` method docstring for more info.
... | MyFacebookAdsApi |
python | django__django | tests/gis_tests/test_data.py | {
"start": 1790,
"end": 2050
} | class ____:
"""
Each attribute of this object is a list of `TestGeom` instances.
"""
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value])
| TestGeomSet |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_orgs.py | {
"start": 621,
"end": 3880
} | class ____(RequestFactoryTestMixin, TestCase):
def setUp(self):
self.owner = fixture.get(User)
self.tester = fixture.get(User, username="tester")
self.project = fixture.get(Project, slug="pip")
self.organization = fixture.get(
Organization,
name="Mozilla",
... | OrganizationTestCase |
python | giampaolo__psutil | psutil/test/memleak.py | {
"start": 4305,
"end": 4540
} | class ____(UnclosedResourceError):
"""Raised when test detects HeapCreate() without a corresponding
HeapDestroy() after calling function once. Windows only.
"""
resource_name = "HeapCreate() call"
| UnclosedHeapCreateError |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 2801,
"end": 3660
} | class ____(Operation):
def call(self, x):
return backend.nn.sparse_sigmoid(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["keras.ops.sparse_sigmoid", "keras.ops.nn.sparse_sigmoid"])
def sparse_sigmoid(x):
"""Sparse sigmoid activation functio... | SparseSigmoid |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 4918,
"end": 6692
} | class ____(unittest.TestCase):
def test_empty_prompt_formats(self):
secret = vault.PromptVaultSecret(vault_id='test_id', prompt_formats=[])
secret.load()
self.assertIsNone(secret._bytes)
@patch('ansible.parsing.vault.display.prompt', return_value='the_password')
def test_prompt_form... | TestPromptVaultSecret |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | {
"start": 7838,
"end": 8177
} | class ____(StyleTransformation):
"""
Don't transform anything at all.
"""
def transform_attrs(self, attrs: Attrs) -> Attrs:
return attrs
def invalidation_hash(self) -> Hashable:
# Always return the same hash for these dummy instances.
return "dummy-style-transformation"
| DummyStyleTransformation |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 76071,
"end": 84777
} | class ____(GoogleCloudBaseOperator):
"""
Instantiate a WorkflowTemplate Inline on Google Cloud Dataproc.
The operator will wait until the WorkflowTemplate is finished executing.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operato... | DataprocInstantiateInlineWorkflowTemplateOperator |
python | getsentry__sentry | tests/sentry/api/test_base.py | {
"start": 2656,
"end": 3112
} | class ____(Endpoint):
permission_classes = ()
def get(self, request):
values = [x for x in range(0, 100)]
def data_fn(offset, limit):
page_offset = offset * limit
return values[page_offset : page_offset + limit]
return self.paginate(
request=request... | DummyPaginationEndpoint |
python | realpython__materials | python-dicts/number.py | {
"start": 0,
"end": 101
} | class ____:
def __init__(self, value):
self.value = value
print(Number(42).__dict__)
| Number |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 11684,
"end": 12265
} | class ____(BaseModelWithConfig):
ref: Optional[str] = Field(default=None, alias="$ref")
summary: Optional[str] = None
description: Optional[str] = None
get: Optional[Operation] = None
put: Optional[Operation] = None
post: Optional[Operation] = None
delete: Optional[Operation] = None
opti... | PathItem |
python | chroma-core__chroma | chromadb/db/mixins/sysdb.py | {
"start": 1451,
"end": 36955
} | class ____(SqlDB, SysDB):
# Used only to delete log streams on collection deletion.
# TODO: refactor to remove this dependency into a separate interface
_producer: Producer
def __init__(self, system: System):
super().__init__(system)
self._opentelemetry_client = system.require(OpenTelem... | SqlSysDB |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py | {
"start": 41316,
"end": 44012
} | class ____:
"""Test async execution with wrap_model_call."""
async def test_async_model_with_middleware(self) -> None:
"""Test that wrap_model_call works with async model execution."""
log = []
class LoggingMiddleware(AgentMiddleware):
async def awrap_model_call(self, reque... | TestAsyncWrapModelCall |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels21.py | {
"start": 315,
"end": 1880
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels21.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | numpy__numpy | doc/neps/nep-0016-benchmark.py | {
"start": 211,
"end": 1053
} | class ____:
pass
ArrayBase.register(ABCArray2)
not_array = NotArray()
attr_array = AttrArray()
abc_array_1 = ABCArray1()
abc_array_2 = ABCArray2()
# Make sure ABC cache is primed
isinstance(not_array, ArrayBase)
isinstance(abc_array_1, ArrayBase)
isinstance(abc_array_2, ArrayBase)
runner = perf.Runner()
def t(... | ABCArray2 |
python | getsentry__sentry | src/sentry/api/endpoints/organization_profiling_functions.py | {
"start": 2407,
"end": 12640
} | class ____(OrganizationEventsV2EndpointBase):
owner = ApiOwner.PROFILING
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def has_feature(self, organization: Organization, request: Request):
return features.has(
"organizations:profiling-global-suspect-functions", organi... | OrganizationProfilingFunctionTrendsEndpoint |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0033_dont_cascade_delete_builds.py | {
"start": 183,
"end": 723
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0032_migrate_version_data_to_build"),
]
operations = [
migrations.AlterField(
model_name="build",
name="version",
field=models.ForeignKey(
null=T... | Migration |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 10832,
"end": 12096
} | class ____(SerializedAttributes.with_attributes(
'LayerAttributes',
checkpointable_objects=['non_trainable_variables', 'layers', 'metrics',
'layer_regularization_losses', 'layer_metrics'],
functions=['call_and_return_conditional_losses', 'activity_regularizer_fn'],
copy_from=... | LayerAttributes |
python | streamlit__streamlit | lib/streamlit/web/server/routes.py | {
"start": 8541,
"end": 9799
} | class ____(_SpecialRequestHandler):
def initialize(self) -> None:
# Make a copy of the allowedOrigins list, since we might modify it later:
self._allowed_origins = _DEFAULT_ALLOWED_MESSAGE_ORIGINS.copy()
if (
config.get_option("global.developmentMode")
and "http://lo... | HostConfigHandler |
python | huggingface__transformers | src/transformers/models/gpt_neo/configuration_gpt_neo.py | {
"start": 784,
"end": 9150
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GPTNeoModel`]. It is used to instantiate a GPT
Neo model according to the specified arguments, defining the model architecture. Instantiating a configuration with
the defaults will yield a similar config... | GPTNeoConfig |
python | huggingface__transformers | src/transformers/models/arcee/modular_arcee.py | {
"start": 8221,
"end": 8309
} | class ____(NemotronMLP):
pass
@auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
| ArceeMLP |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 878866,
"end": 879138
} | class ____(
sgqlc.types.Type, ProjectV2ItemFieldValueCommon, Node
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("text",)
text = sgqlc.types.Field(String, graphql_name="text")
| ProjectV2ItemFieldTextValue |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 177097,
"end": 179164
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of CreateCheckRun"""
__schema__ = github_schema
__field_names__ = (
"repository_id",
"name",
"head_sha",
"details_url",
"external_id",
"status",
"started_at",
"conclusion",
"co... | CreateCheckRunInput |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py | {
"start": 112791,
"end": 116310
} | class ____(test.TestCase):
def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding,
expected):
"""Verifies the output values of the convolution function.
Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
... | DepthwiseConv2DTest |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-operations-to-satisfy-conditions.py | {
"start": 844,
"end": 1463
} | class ____(object):
def minimumOperations(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
INF = float("inf")
MAX_VALUE = 9
dp = [0]*(MAX_VALUE+1)
for j in xrange(len(grid[0])):
new_dp = [INF]*(MAX_VALUE+1)
cnt = [0]... | Solution2 |
python | mlflow__mlflow | tests/tracing/test_fluent.py | {
"start": 3462,
"end": 3699
} | class ____:
@mlflow.trace()
def predict(self, x, y):
return self.some_operation_raise_error(x, y)
@mlflow.trace()
def some_operation_raise_error(self, x, y):
raise ValueError("Some error")
| ErroringTestModel |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 110433,
"end": 113045
} | class ____:
rtol = 1e-5
atol = 1e-8
def setup_method(self):
self.olderr = np.seterr(invalid='ignore')
def teardown_method(self):
np.seterr(**self.olderr)
def tst_allclose(self, x, y):
assert_(np.allclose(x, y), f"{x} and {y} not close")
def tst_not_allclose(self, x, y... | TestAllclose |
python | doocs__leetcode | solution/1700-1799/1705.Maximum Number of Eaten Apples/Solution.py | {
"start": 0,
"end": 537
} | class ____:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
n = len(days)
i = ans = 0
q = []
while i < n or q:
if i < n and apples[i]:
heappush(q, (i + days[i] - 1, apples[i]))
while q and q[0][0] < i:
heappop(... | Solution |
python | has2k1__plotnine | plotnine/stats/stat_qq_line.py | {
"start": 284,
"end": 3646
} | class ____(stat):
"""
Calculate line through quantile-quantile plot
{usage}
Parameters
----------
{common_parameters}
distribution : str, default="norm"
Distribution or distribution function name. The default is
*norm* for a normal probability plot. Objects that look enough... | stat_qq_line |
python | tensorflow__tensorflow | tensorflow/python/training/experimental/loss_scale_test.py | {
"start": 3765,
"end": 12004
} | class ____(test.TestCase, parameterized.TestCase):
def _get_tensor(self, is_finite):
tensor = cond.cond(is_finite, lambda: 1., lambda: float('NaN'))
if not distribute_lib.has_strategy():
return tensor
def get():
rep_id = (
distribute_lib.get_replica_context()
.replica_id... | DynamicLossScaleTest |
python | joke2k__faker | faker/factory.py | {
"start": 576,
"end": 3939
} | class ____:
@classmethod
def create(
cls,
locale: Optional[str] = None,
providers: Optional[List[str]] = None,
generator: Optional[Generator] = None,
includes: Optional[List[str]] = None,
# Should we use weightings (more realistic) or weight every element equally ... | Factory |
python | Textualize__textual | src/textual/widget.py | {
"start": 8167,
"end": 8300
} | class ____(Exception):
"""Raised when widget class names do not satisfy the required restrictions."""
@rich.repr.auto
| BadWidgetName |
python | django__django | tests/many_to_one/models.py | {
"start": 1984,
"end": 2091
} | class ____(models.Model):
name = models.CharField(primary_key=True, max_length=15)
| ParentStringPrimaryKey |
python | microsoft__ML-For-Beginners | 8-Reinforcement/1-QLearning/rlboard.py | {
"start": 1011,
"end": 7234
} | class ____:
class Cell:
empty = 0
water = 1
wolf = 2
tree = 3
apple = 4
def __init__(self,width,height,size=50):
self.width = width
self.height = height
self.size = size+2
self.matrix = np.zeros((width,height))
self.grid_color = (0.... | Board |
python | sphinx-doc__sphinx | sphinx/domains/std/__init__.py | {
"start": 2913,
"end": 2994
} | class ____(GenericObject):
indextemplate = _('environment variable; %s')
| EnvVar |
python | coleifer__peewee | tests/regressions.py | {
"start": 34351,
"end": 34446
} | class ____(TestModel):
data = IntegerField()
class Meta:
primary_key = False
| NoPK |
python | joke2k__faker | faker/providers/person/en_US/__init__.py | {
"start": 81,
"end": 66194
} | class ____(PersonProvider):
formats_female = OrderedDict(
(
("{{first_name_female}} {{last_name}}", 0.97),
("{{prefix_female}} {{first_name_female}} {{last_name}}", 0.015),
("{{first_name_female}} {{last_name}} {{suffix_female}}", 0.02),
(
"{{p... | Provider |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/VerticalLabel.py | {
"start": 702,
"end": 3009
} | class ____(QtWidgets.QLabel):
def __init__(self, text, orientation='vertical', forceWidth=True):
QtWidgets.QLabel.__init__(self, text)
self.forceWidth = forceWidth
self.orientation = None
self.setOrientation(orientation)
def setOrientation(self, o):
if self.orien... | VerticalLabel |
python | getsentry__sentry | src/sentry/integrations/source_code_management/metrics.py | {
"start": 3697,
"end": 4210
} | class ____(StrEnum):
"""
Reasons why a SourceCodeSearchEndpoint method (handle_search_issues,
handle_search_repositories, or get) may halt without success/failure.
"""
NO_ISSUE_TRACKER = "no_issue_tracker"
RATE_LIMITED = "rate_limited"
MISSING_REPOSITORY_OR_NO_ACCESS = "missing_repository_o... | SourceCodeSearchEndpointHaltReason |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.