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 | openai__openai-python | src/openai/resources/beta/threads/runs/steps.py | {
"start": 970,
"end": 7896
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> StepsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com... | Steps |
python | huggingface__transformers | src/transformers/models/florence2/modeling_florence2.py | {
"start": 8854,
"end": 10390
} | class ____(nn.Module):
def __init__(self, config: Florence2VisionConfig, stage_idx: int):
super().__init__()
self.config = config
self.dim = config.embed_dim[stage_idx]
self.groups = config.num_groups[stage_idx]
self.qkv = nn.Linear(self.dim, self.dim * 3, bias=config.qkv_bia... | Florence2VisionChannelAttention |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 16715,
"end": 17408
} | class ____(nn.Module):
def __init__(self, config: DPTConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.interme... | DPTViTIntermediate |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 37025,
"end": 37378
} | class ____(ChainedSource):
def name(self) -> str:
return f"{self.base.name()}.__tensor_flatten__()[0]"
def guard_source(self) -> GuardSource:
return self.base.guard_source()
# NB: We don't expect you to actually ever generate guards against this
# source, it is ephemeral
@dataclasses.dataclas... | SubclassAttrListSource |
python | readthedocs__readthedocs.org | readthedocs/projects/admin.py | {
"start": 2483,
"end": 2545
} | class ____(admin.TabularInline):
model = Domain
| DomainInline |
python | ApeWorX__ape | src/ape/pytest/fixtures.py | {
"start": 962,
"end": 1054
} | class ____:
return_scope: Scope
invalid_fixtures: dict[Scope, list[str]]
| FixtureRebase |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 22849,
"end": 23179
} | class ____(models.Model):
fk_to_self = models.ForeignKey(
"ForeignKeyToSelfModel", null=True, related_name="+", on_delete=models.CASCADE
)
fk_to_self_using_str = models.ForeignKey(
"self", null=True, related_name="+", on_delete=models.CASCADE
)
history = HistoricalRecords()
| ForeignKeyToSelfModel |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 647750,
"end": 648053
} | 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("Team", graphql_name="node")
| TeamEdge |
python | pypa__virtualenv | src/virtualenv/seed/embed/via_app_data/pip_install/symlink.py | {
"start": 212,
"end": 2015
} | class ____(PipInstall):
def _sync(self, src, dst):
os.symlink(str(src), str(dst))
def _generate_new_files(self):
# create the pyc files, as the build image will be R/O
cmd = [str(self._creator.exe), "-m", "compileall", str(self._image_dir)]
process = Popen(cmd, stdout=PIPE, stde... | SymlinkPipInstall |
python | bottlepy__bottle | test/test_plugins.py | {
"start": 622,
"end": 5538
} | class ____(tools.ServerTestBase):
def verify_installed(self, plugin, otype, **config):
self.assertEqual(type(plugin), otype)
self.assertEqual(plugin.config, config)
self.assertEqual(plugin.app, self.app)
self.assertTrue(plugin in self.app.plugins)
def test_install_plugin(self):... | TestPluginManagement |
python | tiangolo__fastapi | fastapi/temp_pydantic_v1_params.py | {
"start": 16462,
"end": 20310
} | class ____(FieldInfo): # type: ignore[misc]
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: Union[bool, None] = None,
media_type: str = "application/json",
... | Body |
python | pypa__pip | src/pip/_vendor/pygments/util.py | {
"start": 657,
"end": 770
} | class ____(ValueError):
"""Raised if one of the lookup functions didn't find a matching class."""
| ClassNotFound |
python | PyCQA__pylint | pylint/checkers/format.py | {
"start": 3622,
"end": 4191
} | class ____:
"""A wrapper for readable access to token information."""
def __init__(self, tokens: list[tokenize.TokenInfo]) -> None:
self._tokens = tokens
def token(self, idx: int) -> str:
return self._tokens[idx][1]
def type(self, idx: int) -> int:
return self._tokens[idx][0]
... | TokenWrapper |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/tests/test_github_repository_reader.py | {
"start": 27368,
"end": 39254
} | class ____:
"""Test event system functionality."""
@pytest.fixture
def event_handler(self):
"""Create a test event handler."""
class TestEventHandler(BaseEventHandler):
def __init__(self, **data):
super().__init__(**data)
object.__setattr__(self,... | TestGithubRepositoryReaderEvents |
python | apache__airflow | airflow-core/src/airflow/example_dags/plugins/workday.py | {
"start": 4177,
"end": 4327
} | class ____(AirflowPlugin):
name = "workday_timetable_plugin"
timetables = [AfterWorkdayTimetable]
# [END howto_timetable]
| WorkdayTimetablePlugin |
python | scrapy__scrapy | scrapy/exceptions.py | {
"start": 564,
"end": 663
} | class ____(Exception):
"""Indicates a decision was made not to process a request"""
| IgnoreRequest |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 2318,
"end": 5637
} | class ____:
a = attr.ib(
type=List[C],
validator=attr.validators.deep_iterable(
attr.validators.instance_of(C), attr.validators.instance_of(list)
),
)
a2 = attr.ib(
type=Tuple[C],
validator=attr.validators.deep_iterable(
attr.validators.instanc... | Validated |
python | pydata__xarray | xarray/tests/test_units.py | {
"start": 186454,
"end": 187021
} | class ____:
def test_duck_array_ops(self):
import dask.array
d = dask.array.array([1, 2, 3])
q = unit_registry.Quantity(d, units="m")
da = xr.DataArray(q, dims="x")
actual = da.mean().compute()
actual.name = None
expected = xr.DataArray(unit_registry.Quantit... | TestPintWrappingDask |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 1914,
"end": 208068
} | class ____(SimpleTestCase):
# A Form is a collection of Fields. It knows how to validate a set of data
# and it knows how to render itself in a couple of default ways (e.g., an
# HTML table). You can pass it data in __init__(), as a dictionary.
def test_form(self):
# Pass a dictionary to a Form... | FormsTestCase |
python | ansible__ansible | test/units/plugins/callback/test_callback.py | {
"start": 1062,
"end": 2254
} | class ____(unittest.TestCase):
# FIXME: This doesn't really test anything...
def test_init(self):
CallbackBase()
def test_display(self):
display_mock = MagicMock()
display_mock.verbosity = 0
cb = CallbackBase(display=display_mock)
self.assertIs(cb._display, display_m... | TestCallback |
python | dask__distributed | distributed/comm/ws.py | {
"start": 14113,
"end": 14634
} | class ____(WSConnector):
prefix = "wss://"
comm_class = WSS
def _get_connect_args(self, **connection_args):
wss_args = {
"ssl_options": connection_args.get("ssl_context"),
**connection_args.get("extra_conn_args", {}),
}
if connection_args.get("server_hostnam... | WSSConnector |
python | RaRe-Technologies__gensim | gensim/test/test_text_analysis.py | {
"start": 5423,
"end": 6474
} | class ____(unittest.TestCase):
def setUp(self):
self.dictionary = BaseTestCases.TextAnalyzerTestBase.dictionary
self.top_ids = BaseTestCases.TextAnalyzerTestBase.top_ids
self.corpus = \
[self.dictionary.doc2bow(doc) for doc in BaseTestCases.TextAnalyzerTestBase.texts]
def t... | TestCorpusAnalyzer |
python | kamyu104__LeetCode-Solutions | Python/median-of-a-row-wise-sorted-matrix.py | {
"start": 120,
"end": 646
} | class ____(object):
def matrixMedian(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def check(x):
return sum(bisect_right(row, x) for row in grid) > (len(grid)*len(grid[0]))//2
left, right = min(row[0] for row in grid), max(row[-1] for row i... | Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/recentsearch.py | {
"start": 134,
"end": 487
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": str(obj.id),
"organizationId": str(obj.organization_id),
"type": obj.type,
"query": obj.query,
"lastSeen": obj.last_seen,
"dateCreated": obj.date_ad... | RecentSearchSerializer |
python | Textualize__textual | tests/test_animator.py | {
"start": 226,
"end": 506
} | class ____:
"""An animatable object."""
def __init__(self, value):
self.value = value
def blend(self, destination: Animatable, factor: float) -> Animatable:
return Animatable(self.value + (destination.value - self.value) * factor)
@dataclass
| Animatable |
python | jmcnamara__XlsxWriter | xlsxwriter/color.py | {
"start": 2509,
"end": 2625
} | class ____(Enum):
"""
Enum to represent different types of URLS.
"""
RGB = 1
THEME = 2
| ColorTypes |
python | django__django | tests/servers/test_basehttp.py | {
"start": 319,
"end": 490
} | class ____(ThreadingMixIn):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def sendall(self, data):
self.makefile("wb").write(data)
| Stub |
python | python-excel__xlwt | xlwt/Formatting.py | {
"start": 6596,
"end": 7900
} | class ____(object):
NO_LINE = 0x00
THIN = 0x01
MEDIUM = 0x02
DASHED = 0x03
DOTTED = 0x04
THICK = 0x05
DOUBLE = 0x06
HAIR = 0x07
#The following for BIFF8
MEDIUM_DASHED = 0x08
THIN_DASH_DOTTED = 0x09
MEDIUM_DASH_DOTTED = 0x0A
... | Borders |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_visual.py | {
"start": 10865,
"end": 12195
} | class ____:
def test_valid_no_datetime(self) -> None:
prop = bcpv.MinMaxBounds(accept_datetime=False)
assert prop.is_valid('auto')
assert prop.is_valid((12, 13))
assert prop.is_valid((-32, -13))
assert prop.is_valid((12.1, 13.1))
assert prop.is_valid((None, 13.1))
... | Test_MinMaxBounds |
python | celery__celery | celery/backends/asynchronous.py | {
"start": 585,
"end": 1229
} | class ____:
"""
An adapted eventlet event, designed to match the API of `threading.Event` and
`gevent.event.Event`.
"""
def __init__(self):
import eventlet
self.evt = eventlet.Event()
def is_set(self):
return self.evt.ready()
def set(self):
return self.evt.... | EventletAdaptedEvent |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 7874,
"end": 8263
} | class ____(Event):
name: str = "log_batch"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
return {
"metrics": bool(arguments.get("metrics")),
"params": bool(arguments.get("params")),
"tags": bool(arguments.get("tags")),
... | LogBatchEvent |
python | walkccc__LeetCode | solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py | {
"start": 0,
"end": 466
} | class ____:
def pseudoPalindromicPaths(self, root: TreeNode | None) -> int:
ans = 0
def dfs(root: TreeNode | None, path: int) -> None:
nonlocal ans
if not root:
return
if not root.left and not root.right:
path ^= 1 << root.val
if path & (path - 1) == 0:
ans... | Solution |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 2498,
"end": 2869
} | class ____(object):
def __init__(self, runner, mask, **options):
self.runner = runner
self.mask = mask
def __call__(self):
if self.mask:
# Tests are all run in isolated subprocesses, so we
# don't have to worry about this affecting other tests
set_num... | mask_runner |
python | facebook__pyre-check | tools/incremental_test/specification.py | {
"start": 11508,
"end": 11863
} | class ____(RepositoryUpdate):
_updates: List[SingleUpdate]
def to_json(self) -> Dict[str, Any]:
return {
"kind": "batch",
"updates": [update.to_json() for update in self._updates],
}
def update_steps(self) -> List[SingleUpdate]:
return self._updates
@datac... | BatchRepositoryUpdate |
python | ray-project__ray | python/ray/util/scheduling_strategies.py | {
"start": 5086,
"end": 5524
} | class ____:
"""An expression used to select node by node's labels
Attributes:
key: the key of label
operator: In、NotIn、Exists、DoesNotExist
"""
def __init__(self, key: str, operator: Union[In, NotIn, Exists, DoesNotExist]):
self.key = key
self.operator = operator
LabelM... | _LabelMatchExpression |
python | mwaskom__seaborn | tests/test_statistics.py | {
"start": 793,
"end": 4122
} | class ____:
def integrate(self, y, x):
y = np.asarray(y)
x = np.asarray(x)
dx = np.diff(x)
return (dx * y[:-1] + dx * y[1:]).sum() / 2
def test_gridsize(self, rng):
x = rng.normal(0, 3, 1000)
n = 200
kde = KDE(gridsize=n)
density, support = kde... | TestKDE |
python | pytorch__pytorch | test/inductor/test_torchinductor_opinfo.py | {
"start": 40588,
"end": 51219
} | class ____(TestCase):
def tearDown(self):
torch._dynamo.reset()
check_model = check_model
check_model_gpu = check_model_gpu
@onlyNativeDeviceTypes
@suppress_warnings
@skipCUDAMemoryLeakCheckIf(
True
) # inductor kernels failing this test intermittently
@requires_gpu_an... | TestInductorOpInfo |
python | streamlit__streamlit | lib/tests/streamlit/web/server/websocket_headers_test.py | {
"start": 1019,
"end": 3049
} | class ____(ServerTestCase):
@tornado.testing.gen_test
async def test_get_websocket_headers(self):
"""`get_websocket_headers()` returns the current session's
`BrowserWebSocketHandler.request.headers`.
"""
with self._patch_app_session():
await self.server.start()
... | WebSocketHeadersTest |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 124012,
"end": 124531
} | class ____(Operation):
def call(self, x):
return backend.numpy.isposinf(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype="bool")
@keras_export(["keras.ops.isposinf", "keras.ops.numpy.isposinf"])
def isposinf(x):
"""Test element-wise for positive infinity.
Args:
... | Isposinf |
python | psf__black | tests/data/cases/fmtskip6.py | {
"start": 0,
"end": 123
} | class ____:
def f(self):
for line in range(10):
if True:
pass # fmt: skip
# output
| A |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/main_widget.py | {
"start": 1589,
"end": 1889
} | class ____:
ToggleBreakpoint = 'toggle breakpoint'
ToggleConditionalBreakpoint = 'toggle conditional breakpoint'
ClearAllBreakpoints = 'clear all breakpoints'
ShowBreakpointsTable = 'show breakpoint table'
ToggleBreakpointsTable = 'toggle breakpoint table'
| DebuggerBreakpointActions |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 816,
"end": 1013
} | class ____(analytics.Event):
user_id: int | None = None
organization_id: int
unfurls_count: int
@analytics.eventclass("integrations.slack.chart_unfurl_action")
| SlackIntegrationChartUnfurl |
python | google__jax | tests/optimizers_test.py | {
"start": 867,
"end": 10229
} | class ____(jtu.JaxTestCase):
def _CheckOptimizer(self, optimizer, loss, x0, num_steps, *args, **kwargs):
self._CheckFuns(optimizer, loss, x0, *args)
self._CheckRun(optimizer, loss, x0, num_steps, *args, **kwargs)
def _CheckFuns(self, optimizer, loss, x0, *args):
init_fun, update_fun, get_params = opti... | OptimizerTests |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py | {
"start": 8718,
"end": 11469
} | class ____(FileTaskHandler, LoggingMixin):
"""
CloudwatchTaskHandler is a python log handler that handles and reads task instance logs.
It extends airflow FileTaskHandler and uploads to and reads from Cloudwatch.
:param base_log_folder: base folder to store logs locally
:param log_group_arn: ARN o... | CloudwatchTaskHandler |
python | pypa__pip | tests/unit/test_models.py | {
"start": 1589,
"end": 1965
} | class ____:
def test_sets_correct_variables(self) -> None:
obj = candidate.InstallationCandidate(
"A", "1.0.0", Link("https://somewhere.com/path/A-1.0.0.tar.gz")
)
assert obj.name == "A"
assert obj.version == parse_version("1.0.0")
assert obj.link.url == "https://... | TestInstallationCandidate |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 18837,
"end": 19716
} | class ____(PreTrainedModel):
config: VisualBertConfig
base_model_prefix = "visual_bert"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn... | VisualBertPreTrainedModel |
python | pytorch__pytorch | test/inductor/test_indexing.py | {
"start": 1004,
"end": 11994
} | class ____(InductorTestCase):
def test_indexing_simplification(self):
sizevars = SizeVarAllocator()
i0 = sympy.Symbol("i0", integer=True)
i1 = sympy.Symbol("i1", integer=True)
i2 = sympy.Symbol("i2", integer=True)
r3 = sympy.Symbol("r3", integer=True)
var_ranges = {i... | TestIndexingSimplification |
python | mlflow__mlflow | mlflow/entities/multipart_upload.py | {
"start": 727,
"end": 1273
} | class ____:
url: str
part_number: int
headers: dict[str, Any]
def to_proto(self):
credential = ProtoMultipartUploadCredential()
credential.url = self.url
credential.part_number = self.part_number
credential.headers.update(self.headers)
return credential
@cla... | MultipartUploadCredential |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 45487,
"end": 45622
} | class ____:
xlColorIndexAutomatic = -4105 # from enum XlColorIndex
xlColorIndexNone = -4142 # from enum XlColorIndex
| ColorIndex |
python | getsentry__sentry | src/sentry/notifications/notifications/codeowners_auto_sync.py | {
"start": 425,
"end": 1700
} | class ____(ProjectNotification):
metrics_key = "auto_sync"
notification_setting_type_enum = NotificationSettingEnum.DEPLOY
template_path = "sentry/emails/codeowners-auto-sync-failure"
def determine_recipients(self) -> list[Actor]:
return Actor.many_from_object(self.organization.get_owners())
... | AutoSyncNotification |
python | kamyu104__LeetCode-Solutions | Python/number-of-nodes-with-value-one.py | {
"start": 1374,
"end": 1746
} | class ____(object):
def numberOfNodes(self, n, queries):
"""
:type n: int
:type queries: List[int]
:rtype: int
"""
def dfs(u, curr):
curr ^= cnt[u]%2
return curr+sum(dfs(v, curr) for v in xrange(2*u, min(2*u+1, n)+1))
cnt = collect... | Solution3 |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 416309,
"end": 420032
} | class ____:
@pytest.mark.parametrize(
"methodname",
[
"__array__", "__array_finalize__", "__array_function__", "__array_ufunc__",
"__array_wrap__", "__complex__", "__copy__", "__deepcopy__",
"__reduce__", "__reduce_ex__", "__setstate__",
"all", "any", ... | TestTextSignatures |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 7759,
"end": 7987
} | class ____(graphene.ObjectType):
fields = non_null_list(GrapheneConfigTypeField)
class Meta:
interfaces = (GrapheneConfigValidationError,)
name = "MissingFieldsConfigError"
| GrapheneMissingFieldsConfigError |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 638,
"end": 1067
} | class ____(TypedDict):
"""Represents an action request with a name, args, and description."""
name: str
"""The name of the action being requested."""
args: dict[str, Any]
"""Key-value pairs of args needed for the action (e.g., `{"a": 1, "b": 2}`)."""
description: NotRequired[str]
"""The d... | ActionRequest |
python | google__flatbuffers | goldens/py/flatbuffers/goldens/Universe.py | {
"start": 176,
"end": 2541
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Universe()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsUniverse(cls, buf, offset=0):
... | Universe |
python | huggingface__transformers | examples/pytorch/question-answering/run_qa_beam_search.py | {
"start": 1799,
"end": 3065
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
config_name: Optional[str] = field(
default=No... | ModelArguments |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 155922,
"end": 157884
} | class ____(Response):
"""
Response of tasks.clone endpoint.
:param id: ID of the new task
:type id: str
:param new_project: In case the new_project_name was specified returns the
target project details
:type new_project: dict
"""
_service = "tasks"
_action = "clone"
_ve... | CloneResponse |
python | langchain-ai__langchain | libs/langchain/langchain_classic/retrievers/multi_query.py | {
"start": 691,
"end": 1667
} | class ____(BaseOutputParser[list[str]]):
"""Output parser for a list of lines."""
@override
def parse(self, text: str) -> list[str]:
lines = text.strip().split("\n")
return list(filter(None, lines)) # Remove empty lines
# Default prompt
DEFAULT_QUERY_PROMPT = PromptTemplate(
input_va... | LineListOutputParser |
python | pytorch__pytorch | tools/test/heuristics/test_interface.py | {
"start": 14726,
"end": 21043
} | class ____(TestTD):
def test_get_test_stats_with_whole_tests(self) -> None:
self.maxDiff = None
tests = ["test1", "test2", "test3", "test4", "test5"]
heuristic1 = interface.TestPrioritizations(
tests,
{
TestRun("test3"): 0.3,
TestRun("t... | TestAggregatedHeuristicsTestStats |
python | huggingface__transformers | src/transformers/models/ibert/quant_modules.py | {
"start": 25851,
"end": 27043
} | class ____(Function):
"""
Straight-through Estimator(STE) for torch.round()
"""
@staticmethod
def forward(ctx, x):
return torch.round(x)
@staticmethod
def backward(ctx, grad_output):
return grad_output.clone()
def batch_frexp(inputs, max_bit=31):
"""
Decompose the... | round_ste |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 77,
"end": 354
} | class ____(Exception):
"""Baseclass for all template errors."""
def __init__(self, message: str | None = None) -> None:
super().__init__(message)
@property
def message(self) -> str | None:
return self.args[0] if self.args else None
| TemplateError |
python | PyCQA__pylint | doc/data/messages/n/no-self-use/good/use_self.py | {
"start": 0,
"end": 120
} | class ____:
name: str = "Amelia"
def greeting(self):
print(f"Greetings {self.name} the pythonista!")
| Person |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 64114,
"end": 81670
} | class ____(CodeGen):
"""Generator for Rust code.
The .write() method inherited from CodeGen will output a code file
<prefix>.rs
"""
code_extension = "rs"
def __init__(self, project="project", printer=None):
super().__init__(project=project)
self.printer = printer or RustCodeP... | RustCodeGen |
python | jmcnamara__XlsxWriter | xlsxwriter/test/utility/test_xl_cell_to_rowcol_abs.py | {
"start": 287,
"end": 1653
} | class ____(unittest.TestCase):
"""
Test xl_cell_to_rowcol_abs() utility function.
"""
def test_xl_cell_to_rowcol_abs(self):
"""Test xl_cell_to_rowcol_abs()"""
tests = [
# row, col, A1 string
(0, 0, "A1"),
(0, 1, "B1"),
(0, 2, "C1"),
... | TestUtility |
python | crytic__slither | slither/core/solidity_types/function_type.py | {
"start": 168,
"end": 2469
} | class ____(Type):
def __init__(
self,
params: List[FunctionTypeVariable],
return_values: List[FunctionTypeVariable],
) -> None:
assert all(isinstance(x, FunctionTypeVariable) for x in params)
assert all(isinstance(x, FunctionTypeVariable) for x in return_values)
s... | FunctionType |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 268196,
"end": 269342
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self, name: str, access_token: str, start_date: str, survey_ids: Optional[list[str]] = None
):
"""Airbyte Source for Surveymonkey.
Documentation can be found at https://docs.airbyte.com/integrations/sources/surveymonkey
... | SurveymonkeySource |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/_collections.py | {
"start": 3568,
"end": 4402
} | class ____(ImmutableDictBase[_KT, _VT]):
"""A dictionary that is not publicly mutable."""
def __new__(cls, *args: Any) -> FacadeDict[Any, Any]:
new: FacadeDict[Any, Any] = ImmutableDictBase.__new__(cls)
return new
def copy(self) -> NoReturn:
raise NotImplementedError(
"... | FacadeDict |
python | getsentry__sentry | src/sentry/integrations/slack/spec.py | {
"start": 778,
"end": 3459
} | class ____(MessagingIntegrationSpec):
@property
def provider_slug(self) -> str:
return IntegrationProviderSlug.SLACK.value
@property
def action_service(self) -> ActionService:
return ActionService.SLACK
@property
def integration_provider(self) -> type[IntegrationProvider]:
... | SlackMessagingSpec |
python | django__django | tests/bulk_create/models.py | {
"start": 4186,
"end": 4418
} | class ____(models.Model):
name = models.CharField(max_length=15, null=True)
country = models.OneToOneField(Country, models.CASCADE, primary_key=True)
big_auto_fields = models.ManyToManyField(BigAutoFieldModel)
| RelatedModel |
python | openai__openai-python | src/openai/types/chat/chat_completion_tool_message_param.py | {
"start": 354,
"end": 730
} | class ____(TypedDict, total=False):
content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]]
"""The contents of the tool message."""
role: Required[Literal["tool"]]
"""The role of the messages author, in this case `tool`."""
tool_call_id: Required[str]
"""Tool call that this... | ChatCompletionToolMessageParam |
python | wandb__wandb | wandb/plot/custom_chart.py | {
"start": 2131,
"end": 5010
} | class ____:
table: wandb.Table
spec: CustomChartSpec
def set_key(self, key: str):
"""Sets the key for the spec and updates dependent configurations."""
self.spec.key = key
def plot_table(
vega_spec_name: str,
data_table: wandb.Table,
fields: dict[str, Any],
string_fields: ... | CustomChart |
python | giampaolo__psutil | tests/test_connections.py | {
"start": 9196,
"end": 18157
} | class ____(ConnectionTestCase):
def test_filters(self):
def check(kind, families, types):
for conn in this_proc_net_connections(kind=kind):
assert conn.family in families
assert conn.type in types
if not SKIP_SYSCONS:
for conn in psutil... | TestFilters |
python | walkccc__LeetCode | solutions/1206. Design Skiplist/1206.py | {
"start": 47,
"end": 121
} | class ____:
val: int = -1
next: 'Node' = None
down: 'Node' = None
| Node |
python | getsentry__sentry | tests/snuba/api/endpoints/test_discover_homepage_query.py | {
"start": 502,
"end": 9146
} | class ____(DiscoverSavedQueryBase):
def setUp(self) -> None:
super().setUp()
self.url = reverse("sentry-api-0-discover-homepage-query", args=[self.org.slug])
self.query = {"fields": ["test"], "conditions": [], "limit": 10}
self.project_ids = [
self.create_project(organiza... | DiscoverHomepageQueryTest |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 7511,
"end": 7679
} | class ____(AppOptions):
extensions = Bool(False)
settings = Bool(False)
staging = Bool(True)
static = Bool(False)
all = Bool(False)
| LabCleanAppOptions |
python | scrapy__scrapy | tests/test_pipeline_media.py | {
"start": 1341,
"end": 6689
} | class ____:
pipeline_class = UserDefinedPipeline
settings = None
def setup_method(self):
crawler = get_crawler(DefaultSpider, self.settings)
crawler.spider = crawler._create_spider()
self.pipe = self.pipeline_class.from_crawler(crawler)
self.pipe.download_func = _mocked_down... | TestBaseMediaPipeline |
python | huggingface__transformers | tests/models/metaclip_2/test_modeling_metaclip_2.py | {
"start": 18378,
"end": 20536
} | class ____:
def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
if text_kwargs is None:
text_kwargs = {}
if vision_kwargs is None:
vision_kwargs = {}
self.parent = parent
self.text_model_tester = MetaClip2TextModelTester(parent... | MetaClip2ModelTester |
python | coleifer__peewee | tests/keys.py | {
"start": 5894,
"end": 7676
} | class ____(ModelTestCase):
requires = [User, Relationship]
def test_multiple_fks(self):
a = User.create(username='a')
b = User.create(username='b')
c = User.create(username='c')
self.assertEqual(list(a.relationships), [])
self.assertEqual(list(a.related_to), [])
... | TestMultipleForeignKeysJoining |
python | getsentry__sentry | src/sentry/notifications/apps.py | {
"start": 36,
"end": 562
} | class ____(AppConfig):
name = "sentry.notifications"
def ready(self) -> None:
# Register the providers and templates for the new platform
import sentry.notifications.platform.discord.provider # noqa: F401
import sentry.notifications.platform.email.provider # noqa: F401
import ... | Config |
python | pypa__hatch | tests/backend/builders/plugin/test_interface.py | {
"start": 3421,
"end": 3702
} | class ____:
def test_normalization(self, isolation):
config = {"project": {"name": "my-app", "version": "1.0.0-rc.1"}}
builder = MockBuilder(str(isolation), config=config)
assert builder.project_id == builder.project_id == "my_app-1.0.0rc1"
| TestProjectID |
python | huggingface__transformers | src/transformers/models/mamba/modeling_mamba.py | {
"start": 22345,
"end": 23414
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.residual_in_fp32 = config.residual_in_fp32
self.norm = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
... | MambaBlock |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 15563,
"end": 22520
} | class ____(nn.Module):
def __init__(self, config: FunnelConfig, block_index: int) -> None:
super().__init__()
self.config = config
self.block_index = block_index
d_model, n_head, d_head = config.d_model, config.n_head, config.d_head
self.hidden_dropout = nn.Dropout(config.hi... | FunnelRelMultiheadAttention |
python | django__django | tests/template_tests/filter_tests/test_force_escape.py | {
"start": 2650,
"end": 3145
} | class ____(SimpleTestCase):
def test_escape(self):
escaped = force_escape("<some html & special characters > here")
self.assertEqual(escaped, "<some html & special characters > here")
self.assertIsInstance(escaped, SafeData)
def test_unicode(self):
self.assertEqual(
... | FunctionTests |
python | sympy__sympy | sympy/vector/dyadic.py | {
"start": 7167,
"end": 7698
} | class ____(BasisDependentMul, Dyadic):
""" Products of scalars and BaseDyadics """
def __new__(cls, *args, **options):
obj = BasisDependentMul.__new__(cls, *args, **options)
return obj
@property
def base_dyadic(self):
""" The BaseDyadic involved in the product. """
retu... | DyadicMul |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 8595,
"end": 10083
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
if config.feat_extract_norm == "group":
conv_layers = [UniSpeechGroupNormConvLayer(config, layer_id=0)] + [
UniSpeechNoLayerNormConvLayer(confi... | UniSpeechFeatureEncoder |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_branch_operator.py | {
"start": 2216,
"end": 13803
} | class ____:
def test_without_dag_run(self, dag_maker):
"""This checks the defensive against non-existent tasks in a dag run"""
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
... | TestBranchOperator |
python | mwaskom__seaborn | seaborn/_marks/line.py | {
"start": 7505,
"end": 8301
} | class ____(Paths):
"""
An oriented line mark drawn between min/max values.
Examples
--------
.. include:: ../docstrings/objects.Range.rst
"""
def _setup_segments(self, data, orient):
# TODO better checks on what variables we have
# TODO what if only one exist?
val ... | Range |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 270920,
"end": 271327
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "pull_request_review")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
pull_request_review = sgqlc.types.Field(
"... | DeletePullRequestReviewPayload |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/del1.py | {
"start": 499,
"end": 885
} | class ____:
x: int
b = ClassB()
b.x = 3
reveal_type(b.x, expected_text="Literal[3]")
del b.x
reveal_type(b.x, expected_text="int")
x2: list[str | int] = ["a", 1, "b", 2]
reveal_type(x2[0], expected_text="str | int")
x2[0] = 0
reveal_type(x2[0], expected_text="Literal[0]")
reveal_type(x2[1], expected_text="str | ... | ClassB |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 1784,
"end": 1930
} | class ____(abc.ABCMeta): # safe
def method(self):
foo()
# very invalid code, but that's up to mypy et al to check
| non_keyword_abcmeta_2 |
python | pallets__werkzeug | examples/couchy/models.py | {
"start": 253,
"end": 1356
} | class ____(Document):
target = TextField()
public = BooleanField()
added = DateTimeField(default=datetime.utcnow())
shorty_id = TextField(default=None)
db = None
@classmethod
def load(cls, id):
return super().load(URL.db, id)
@classmethod
def query(cls, code):
retur... | URL |
python | PyCQA__pylint | tests/functional/r/regression/regression_4723.py | {
"start": 271,
"end": 420
} | class ____(A):
def play(): # [no-method-argument]
pass
def func():
with B().get() as b:
b.play() # [too-many-function-args]
| B |
python | huggingface__transformers | src/transformers/data/processors/glue.py | {
"start": 17166,
"end": 18889
} | class ____(DataProcessor):
"""Processor for the RTE 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 b... | RteProcessor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 7040,
"end": 7971
} | class ____(_MetricsBase):
maximum: bool
median: bool
minimum: bool
mode: bool
def to_gql(self) -> str:
body = " ".join(
[
"count" if self.count else "",
"maximum" if self.maximum else "",
"median" if self.median else "",
... | _MetricsDate |
python | ray-project__ray | python/ray/tests/test_concurrency_group.py | {
"start": 6325,
"end": 10581
} | class ____:
"""
This test verifies that synchronous tasks can access thread-local data that
was set by previous synchronous tasks when the concurrency group has only
one thread. For concurrency groups with multiple threads, it doesn't promise
access to the same thread-local data because Ray currentl... | TestThreadingLocalData |
python | huggingface__transformers | tests/models/siglip/test_modeling_siglip.py | {
"start": 23088,
"end": 25502
} | class ____(unittest.TestCase):
@slow
def test_inference(self):
model_name = "google/siglip-base-patch16-224"
model = SiglipModel.from_pretrained(model_name).to(torch_device)
processor = SiglipProcessor.from_pretrained(model_name)
image = prepare_img()
inputs = processor(... | SiglipModelIntegrationTest |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 7431,
"end": 8901
} | class ____(Operator):
"""Operator for torch.nn.functional.relu."""
def __init__(self):
super().__init__("torch.nn.functional.relu")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.nn.functional.relu"
def can_produce(sel... | ReLUOperator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 4419,
"end": 4670
} | class ____:
def __exit__(self, typ, exc, tb, weird_extra_arg, extra_arg2 = None) -> None: ... # PYI036: Extra arg must have default
async def __aexit__(self, typ, exc, tb, *, weird_extra_arg) -> None: ... # PYI036: kwargs must have default
| BadSix |
python | pytorch__pytorch | test/test_sparse_csr.py | {
"start": 6945,
"end": 51832
} | class ____(TestCase):
"""Testing sparse compressed (CSR, CSC, BSR, BSC) tensor generic features.
"""
def genTensor(self, size, nnz, *, layout, device=None, dtype=torch.float, index_dtype=torch.int64):
if device is None:
device = self.device_type
return self.genSparseCompressedTe... | TestSparseCompressed |
python | django__django | tests/admin_checks/models.py | {
"start": 1422,
"end": 1503
} | class ____(models.Model):
state = models.ForeignKey(State, models.CASCADE)
| City |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.