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 | HypothesisWorks__hypothesis | hypothesis-python/tests/attrs/test_attrs.py | {
"start": 726,
"end": 1100
} | class ____:
annot_converter = attr.ib(converter=a_converter)
@given(st.builds(Inferrables))
def test_attrs_inference_builds(c):
pass
def test_attrs_inference_from_type():
s = st.from_type(Inferrables)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SmallSearchSpaceWarning)
... | Inferrables |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigtable.py | {
"start": 1647,
"end": 2018
} | class ____:
"""Common class for Cloud Bigtable operators for validating required fields."""
REQUIRED_ATTRIBUTES = [] # type: Iterable[str]
def _validate_inputs(self):
for attr_name in self.REQUIRED_ATTRIBUTES:
if not getattr(self, attr_name):
raise AirflowException(f"E... | BigtableValidationMixin |
python | plotly__plotly.py | plotly/graph_objs/choroplethmap/_legendgrouptitle.py | {
"start": 233,
"end": 2982
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmap"
_path_str = "choroplethmap.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that ma... | Legendgrouptitle |
python | ray-project__ray | python/ray/data/_internal/table_block.py | {
"start": 5469,
"end": 21326
} | class ____(BlockAccessor):
def __init__(self, table: Any):
self._table = table
@staticmethod
def _munge_conflict(name, count):
return f"{name}_{count + 1}"
@staticmethod
def _build_tensor_row(row: Mapping, row_idx: int) -> np.ndarray:
raise NotImplementedError
def to_d... | TableBlockAccessor |
python | ray-project__ray | python/ray/data/_internal/execution/operators/actor_pool_map_operator.py | {
"start": 26398,
"end": 26638
} | class ____:
"""Actor state"""
# Number of tasks in flight per actor
num_tasks_in_flight: int
# Node id of each ready actor
actor_location: str
# Is Actor state restarting or alive
is_restarting: bool
| _ActorState |
python | RaRe-Technologies__gensim | gensim/models/bm25model.py | {
"start": 679,
"end": 5062
} | class ____(interfaces.TransformationABC, metaclass=ABCMeta):
"""Objects of this abstract class realize the transformation between word-document co-occurrence
matrix (int) into a BM25 matrix (positive floats). Concrete subclasses of this abstract class
implement different BM25 scoring functions.
"""
... | BM25ABC |
python | conda__conda | conda/plugins/prefix_data_loaders/pypi/pkg_format.py | {
"start": 1989,
"end": 2127
} | class ____(Warning):
pass
# Dist classes
# -----------------------------------------------------------------------------
| MetadataWarning |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 26983,
"end": 27448
} | class ____(DelegatingLexer):
"""
Subclass of the `CheetahLexer` that highlights unlexed data
with the `HtmlLexer`.
"""
name = 'HTML+Cheetah'
aliases = ['html+cheetah', 'html+spitfire', 'htmlcheetah']
mimetypes = ['text/html+cheetah', 'text/html+spitfire']
def __init__(self, **options):... | CheetahHtmlLexer |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 391,
"end": 450
} | class ____(test_factory()):
fe_type = types.int8
| TestInt8 |
python | walkccc__LeetCode | solutions/2802. Find The K-th Lucky Number/2802.py | {
"start": 0,
"end": 121
} | class ____:
def kthLuckyNumber(self, k: int) -> str:
return bin(k + 1)[3:].replace('0', '4').replace('1', '7')
| Solution |
python | numpy__numpy | numpy/distutils/command/bdist_rpm.py | {
"start": 203,
"end": 709
} | class ____(old_bdist_rpm):
def _make_spec_file(self):
spec_file = old_bdist_rpm._make_spec_file(self)
# Replace hardcoded setup.py script name
# with the real setup script name.
setup_py = os.path.basename(sys.argv[0])
if setup_py == 'setup.py':
return spec_file... | bdist_rpm |
python | walkccc__LeetCode | solutions/1936. Add Minimum Number of Rungs/1936.py | {
"start": 0,
"end": 196
} | class ____:
def addRungs(self, rungs: list[int], dist: int) -> int:
ans = 0
prev = 0
for rung in rungs:
ans += (rung - prev - 1) // dist
prev = rung
return ans
| Solution |
python | pallets__werkzeug | examples/shortly/shortly.py | {
"start": 967,
"end": 4609
} | class ____:
def __init__(self, config):
self.redis = redis.Redis(
config["redis_host"], config["redis_port"], decode_responses=True
)
template_path = os.path.join(os.path.dirname(__file__), "templates")
self.jinja_env = Environment(
loader=FileSystemLoader(tem... | Shortly |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 490621,
"end": 511841
} | class ____(FieldChannelMixin, core.RowColumnEncodingFieldDef):
r"""
Row schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :... | Row |
python | django__django | tests/check_framework/test_urls.py | {
"start": 13160,
"end": 14076
} | class ____(SimpleTestCase):
@override_settings(STATIC_URL="a/", MEDIA_URL="b/")
def test_slash_no_errors(self):
self.assertEqual(check_url_settings(None), [])
@override_settings(STATIC_URL="", MEDIA_URL="")
def test_empty_string_no_errors(self):
self.assertEqual(check_url_settings(None)... | CheckURLSettingsTests |
python | realpython__materials | rp-portfolio/projects/models.py | {
"start": 31,
"end": 261
} | class ____(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FileField(upload_to="project_images/", blank=True)
| Project |
python | django__django | tests/urlpatterns_reverse/tests.py | {
"start": 14054,
"end": 20926
} | class ____(SimpleTestCase):
def test_urlpattern_reverse(self):
for name, expected, args, kwargs in test_data:
with self.subTest(name=name, args=args, kwargs=kwargs):
try:
got = reverse(name, args=args, kwargs=kwargs)
except NoReverseMatch:
... | URLPatternReverse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with1.py | {
"start": 1433,
"end": 1915
} | class ____:
async def __aenter__(self: _T1) -> _T1:
return self
async def __aexit__(
self,
t: Optional[type] = None,
exc: Optional[BaseException] = None,
tb: Optional[Any] = None,
) -> bool:
return True
async def test2():
a1 = Class4()
# This shoul... | Class4 |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 1061,
"end": 1694
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=4, name="MEMBER_EDIT", api_name="member.edit")
def render(self, audit_log_entry: AuditLogEntry) -> str:
member = _get_member_display(audit_log_entry.data.get("email"), audit_log_entry.target_user)
role = au... | MemberEditAuditLogEvent |
python | Textualize__textual | docs/examples/guide/reactivity/world_clock02.py | {
"start": 699,
"end": 1310
} | class ____(App):
CSS_PATH = "world_clock01.tcss"
time: reactive[datetime] = reactive(datetime.now)
def compose(self) -> ComposeResult:
yield WorldClock("Europe/London").data_bind(WorldClockApp.time) # (1)!
yield WorldClock("Europe/Paris").data_bind(WorldClockApp.time)
yield WorldC... | WorldClockApp |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 24176,
"end": 25237
} | class ____(Phase):
__slots__ = tuple()
# helper methods
def insertHtmlElement(self):
self.tree.insertRoot(impliedTagToken("html", "StartTag"))
self.parser.phase = self.parser.phases["beforeHead"]
# other
def processEOF(self):
self.insertHtmlElement()
return True
... | BeforeHtmlPhase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 26463,
"end": 27586
} | class ____(SemiIncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/activity/starring?apiVersion=2022-11-28#list-stargazers
"""
primary_key = "user_id"
cursor_field = "starred_at"
def request_headers(self, **kwargs) -> Mapping[str, Any]:
base_headers = super()... | Stargazers |
python | walkccc__LeetCode | solutions/3250. Find the Count of Monotonic Pairs I/3250.py | {
"start": 0,
"end": 1180
} | class ____:
def countOfPairs(self, nums: list[int]) -> int:
MOD = 1_000_000_007
MAX = 1000
n = len(nums)
# dp[i][num] := the number of valid ways to fill the arrays up to index i
# with arr1[i] = num
dp = [[0] * (MAX + 1) for _ in range(n)]
for num in range(nums[0] + 1):
dp[0][num] ... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property11.py | {
"start": 132,
"end": 510
} | class ____:
@classmethod
@property
def prop1(cls) -> str:
return ""
@classmethod
@prop1.setter
def prop1(cls, value: str):
pass
reveal_type(Class1.prop1, expected_text="str")
reveal_type(Class1().prop1, expected_text="str")
Class1.prop1 = "hi"
# This should generate an error... | Class1 |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_plugins_command.py | {
"start": 1886,
"end": 7327
} | class ____:
@classmethod
def setup_class(cls):
cls.parser = cli_parser.get_parser()
@mock_plugin_manager(plugins=[])
def test_should_display_no_plugins(self):
with redirect_stdout(io.StringIO()) as temp_stdout:
plugins_command.dump_plugins(self.parser.parse_args(["plugins", ... | TestPluginsCommand |
python | jmcnamara__XlsxWriter | xlsxwriter/test/table/test_table08.py | {
"start": 481,
"end": 2386
} | class ____(unittest.TestCase):
"""
Test assembling a complete Table file.
"""
def test_assemble_xml_file(self):
"""Test writing a table"""
self.maxDiff = None
worksheet = Worksheet()
worksheet.worksheet_meta = WorksheetMeta()
worksheet.str_table = SharedStringT... | TestAssembleTable |
python | redis__redis-py | redis/asyncio/retry.py | {
"start": 302,
"end": 1880
} | class ____(AbstractRetry[RedisError]):
__hash__ = AbstractRetry.__hash__
def __init__(
self,
backoff: "AbstractBackoff",
retries: int,
supported_errors: Tuple[Type[RedisError], ...] = (
ConnectionError,
TimeoutError,
),
):
super().__in... | Retry |
python | plotly__plotly.py | plotly/graph_objs/ohlc/_decreasing.py | {
"start": 233,
"end": 2375
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "ohlc"
_path_str = "ohlc.decreasing"
_valid_props = {"line"}
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.ohlc.d... | Decreasing |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 18470,
"end": 19503
} | class ____:
"""Result class storing the parts of ConjectureData that we
will care about after the original ConjectureData has outlived its
usefulness."""
status: Status
interesting_origin: InterestingOrigin | None
nodes: tuple[ChoiceNode, ...] = field(repr=False, compare=False)
length: int
... | ConjectureResult |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 10801,
"end": 13707
} | class ____(test.TestCase):
def _testArg(
self,
method,
x,
axis,
expected_values,
use_gpu=False,
expected_err_re=None,
):
with self.session(use_gpu=use_gpu):
ans = method(x, axis=axis)
if expected_err_re is None:
tf_ans = self.evaluate(ans)
#... | ArgMaxTest |
python | pytorch__pytorch | torchgen/gen.py | {
"start": 3966,
"end": 21479
} | class ____(YamlLoader):
def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
# Add 1 so line numbering starts at 1
mapping["__line__"] = node.start_mark.line + 1
return map... | LineLoader |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 1432,
"end": 1747
} | class ____(InvalidTokenError):
"""Raised when a claim that is required to be present is not contained
in the claimset"""
def __init__(self, claim: str) -> None:
self.claim = claim
def __str__(self) -> str:
return f'Token is missing the "{self.claim}" claim'
| MissingRequiredClaimError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassSlots1.py | {
"start": 217,
"end": 282
} | class ____:
x: int
__slots__ = ()
@dataclass(slots=True)
| A |
python | numba__numba | numba/cuda/stubs.py | {
"start": 2705,
"end": 3278
} | class ____(Stub):
'''
Shared memory namespace
'''
_description_ = '<shared>'
@stub_function
def array(shape, dtype):
'''
Allocate a shared array of the given *shape* and *type*. *shape* is
either an integer or a tuple of integers representing the array's
dimensio... | shared |
python | ray-project__ray | python/ray/dashboard/modules/serve/tests/test_serve_dashboard.py | {
"start": 21898,
"end": 22229
} | class ____:
def __init__(self, semaphore_handle):
ray.get(semaphore_handle.acquire.remote())
ray.get(semaphore_handle.release.remote())
def __call__(self):
return "test"
@pytest.mark.skipif(
sys.platform == "darwin" and not TEST_ON_DARWIN, reason="Flaky on OSX."
)
| DeploymentClassWithBlockingInit |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/tensor_callable_test.py | {
"start": 1055,
"end": 1695
} | class ____(base.Trackable):
def __init__(self):
self.read_counter = variables.Variable(0)
def _serialize_to_tensors(self):
def _get_and_increment_counter():
value = self.read_counter.read_value()
self.read_counter.assign_add(1)
return value
return {
"read_counter":
... | IncrementWhenSave |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/run_launcher.py | {
"start": 373,
"end": 707
} | class ____(BaseModel):
replicaCount: int = Field(gt=0)
name: str
labels: Optional[kubernetes.Labels] = None
nodeSelector: Optional[kubernetes.NodeSelector] = None
configSource: Optional[dict] = None
additionalCeleryArgs: Optional[list[str]] = None
model_config = ConfigDict(extra="forbid")
... | CeleryWorkerQueue |
python | huggingface__transformers | utils/modular_model_detector.py | {
"start": 7725,
"end": 37416
} | class ____:
"""
Analyzer for detecting code similarities between model implementations.
This class uses embedding-based and token-based similarity metrics to identify similar
code patterns across different model definitions in the transformers library.
Args:
hub_dataset (`str`): The Hub da... | CodeSimilarityAnalyzer |
python | scrapy__scrapy | tests/test_extension_periodic_log.py | {
"start": 2127,
"end": 6786
} | class ____:
def test_extension_enabled(self):
# Expected that settings for this extension loaded successfully
# And on certain conditions - extension raising NotConfigured
# "PERIODIC_LOG_STATS": True -> set to {"enabled": True}
# due to TypeError exception from settings.getdict
... | TestPeriodicLog |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_dialect.py | {
"start": 12645,
"end": 13682
} | class ____(fixtures.TestBase):
@provide_metadata
def test_percent_sign_round_trip(self):
"""test that the DBAPI accommodates for escaped / nonescaped
percent signs in a way that matches the compiler
"""
m = self.metadata
t = Table("t", m, Column("data", String(50)))
... | EscapingTest |
python | davidhalter__jedi | jedi/api/interpreter.py | {
"start": 581,
"end": 663
} | class ____:
def __init__(self, dct):
self.__dict__ = dct
| NamespaceObject |
python | h5py__h5py | h5py/tests/test_group.py | {
"start": 16239,
"end": 17475
} | class ____(BaseMapping):
def test_keys(self):
""" .keys provides a key view """
kv = getattr(self.f, 'keys')()
ref = self.groups
self.assertSameElements(list(kv), ref)
self.assertSameElements(list(reversed(kv)), list(reversed(ref)))
for x in self.groups:
... | TestPy3Dict |
python | bokeh__bokeh | tests/unit/bokeh/protocol/messages/test_pull_doc.py | {
"start": 1454,
"end": 2733
} | class ____:
def _sample_doc(self):
doc = document.Document()
another = AnotherModelInTestPullDoc()
doc.add_root(SomeModelInTestPullDoc(child=another))
doc.add_root(SomeModelInTestPullDoc())
return doc
def test_create_req(self) -> None:
proto.create("PULL-DOC-REQ"... | TestPullDocument |
python | coleifer__peewee | tests/migrations.py | {
"start": 1223,
"end": 1354
} | class ____(TestModel):
user = ForeignKeyField(User, unique=True, backref='sessions')
updated_at = DateField(null=True)
| Session |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 114669,
"end": 115190
} | class ____(ServerAdapter):
""" Adapter for Google App Engine. """
quiet = True
def run(self, handler):
from google.appengine.ext.webapp import util
# A main() function in the handler script enables 'App Caching'.
# Lets makes sure it is there. This _really_ improves performance.
... | AppEngineServer |
python | Textualize__textual | examples/sidebar.py | {
"start": 1469,
"end": 2234
} | class ____(App):
"""
Test app to show our sidebar.
"""
DEFAULT_CSS = """
Screen {
layers: sidebar;
}
"""
BINDINGS = [("s", "toggle_sidebar", "Toggle Sidebar")]
show_sidebar = reactive(False)
def compose(self) -> ComposeResult:
yield Sidebar()
yiel... | SidebarApp |
python | numba__numba | numba/tests/test_sets.py | {
"start": 15317,
"end": 15629
} | class ____(TestSets):
"""
Test sets with tuple keys.
"""
def _range(self, stop):
a = np.arange(stop, dtype=np.int64)
b = a & 0x5555555555555555
c = (a & 0xaaaaaaaa).astype(np.int32)
d = ((a >> 32) & 1).astype(np.bool_)
return list(zip(b, c, d))
| TestTupleSets |
python | django__django | tests/schema/models.py | {
"start": 1524,
"end": 1747
} | class ____(models.Model):
name = models.CharField(max_length=255)
birthday = models.DateField()
class Meta:
apps = new_apps
unique_together = [["name", "birthday"]]
| AuthorWithUniqueNameAndBirthday |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 17340,
"end": 17866
} | class ____(GroupByCythonAgg):
"""
Benchmarks specifically targeting our numba aggregation algorithms
(using a big enough dataframe with simple key, so a large part of the
time is actually spent in the grouped aggregation).
"""
def setup(self, dtype, method):
if method in _numba_unsuppor... | GroupByNumbaAgg |
python | joblib__joblib | joblib/compressor.py | {
"start": 18241,
"end": 18435
} | class ____(CompressorWrapper):
def __init__(self):
CompressorWrapper.__init__(
self, obj=BinaryZlibFile, prefix=_ZLIB_PREFIX, extension=".z"
)
| ZlibCompressorWrapper |
python | kamyu104__LeetCode-Solutions | Python/check-if-string-is-decomposable-into-value-equal-substrings.py | {
"start": 29,
"end": 590
} | class ____(object):
def isDecomposable(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)%3 != 2:
return False
for left in xrange(0, len(s), 3):
if any(s[i] != s[i-1] for i in xrange(left+1, min(left+3, len(s)))):
break ... | Solution |
python | huggingface__transformers | src/transformers/models/longformer/modeling_longformer.py | {
"start": 86761,
"end": 92818
} | class ____(LongformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.longformer = LongformerModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize... | LongformerForQuestionAnswering |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-txtai/llama_index/readers/txtai/base.py | {
"start": 176,
"end": 2481
} | class ____(BaseReader):
"""
txtai reader.
Retrieves documents through an existing in-memory txtai index.
These documents can then be used in a downstream LlamaIndex data structure.
If you wish use txtai itself as an index to to organize documents,
insert documents, and perform queries on them, ... | TxtaiReader |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-nvidia/tests/test_text-completion.py | {
"start": 410,
"end": 5721
} | class ____:
def __init__(self, set_env_key_to: Optional[str] = "", set_fake_key: bool = False):
self.set_env_key_to = set_env_key_to
self.set_fake_key = set_fake_key
def __enter__(self) -> None:
self.api_env_was = os.environ.get("NVIDIA_API_KEY", "")
os.environ["NVIDIA_API_KEY"]... | CachedNVIDIApiKeys |
python | doocs__leetcode | solution/1300-1399/1392.Longest Happy Prefix/Solution.py | {
"start": 0,
"end": 174
} | class ____:
def longestPrefix(self, s: str) -> str:
for i in range(1, len(s)):
if s[:-i] == s[i:]:
return s[i:]
return ''
| Solution |
python | takluyver__flit | flit/init.py | {
"start": 4385,
"end": 8784
} | class ____(IniterBase):
def prompt_text(self, prompt, default, validator, retry_msg="Try again."):
if default is not None:
p = f"{prompt} [{default}]: "
else:
p = prompt + ': '
while True:
response = input(p)
if response == '' and default is no... | TerminalIniter |
python | jazzband__django-pipeline | tests/tests/test_packager.py | {
"start": 167,
"end": 1382
} | class ____(TestCase):
def setUp(self):
default_collector.collect()
def test_package_for(self):
packager = Packager()
packager.packages["js"] = packager.create_packages(
{
"application": {
"source_filenames": (_("pipeline/js/application.js"... | PackagerTest |
python | getsentry__sentry | src/sentry/runner/commands/presenters/webhookpresenter.py | {
"start": 252,
"end": 5525
} | class ____(OptionsPresenter):
"""
Sends changes of runtime options made via sentry configoptions
to a webhook url in a truncated json format. The webhook url can
be configured to your liking.
"""
MAX_OPTION_VALUE_LENGTH = 30
def __init__(self, source: str, timestamp: float | None = None) -... | WebhookPresenter |
python | matplotlib__matplotlib | lib/matplotlib/backend_bases.py | {
"start": 105531,
"end": 124995
} | class ____:
"""
Base class for the navigation cursor, version 2.
Backends must implement a canvas that handles connections for
'button_press_event' and 'button_release_event'. See
:meth:`FigureCanvasBase.mpl_connect` for more information.
They must also define
:meth:`save_figure`
... | NavigationToolbar2 |
python | Pylons__pyramid | tests/test_util.py | {
"start": 10172,
"end": 12174
} | class ____(unittest.TestCase):
def _makeOne(self):
from pyramid.config import WeakOrderedSet
return WeakOrderedSet()
def test_ctor(self):
wos = self._makeOne()
self.assertEqual(len(wos), 0)
self.assertEqual(wos.last, None)
def test_add_item(self):
wos = sel... | Test_WeakOrderedSet |
python | numba__llvmlite | llvmlite/tests/test_ir.py | {
"start": 27698,
"end": 31012
} | class ____(TestBase):
def test_globals_access(self):
mod = self.module()
foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'bar')
globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble')
self.asse... | TestGlobalValues |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 4189,
"end": 4252
} | class ____(ReprForm):
_uuid = forms.UUIDField()
| UUIDFieldForm |
python | spack__spack | lib/spack/spack/llnl/util/filesystem.py | {
"start": 110752,
"end": 110828
} | class ____(SymlinkError):
"""Link path already exists."""
| AlreadyExistsError |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/text_line_dataset_test.py | {
"start": 9388,
"end": 10796
} | class ____(TextLineDatasetTestBase,
checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_iterator_graph(
self, test_filenames, symbolic_checkpoint, compression_type=None
):
dataset = readers.TextLineDataset(
... | TextLineDatasetCheckpointTest |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/jit/rpc_test.py | {
"start": 8754,
"end": 10359
} | class ____:
@dist_init
def test_future_passed_between_python_and_jit(self):
dst_rank = (self.rank + 1) % self.world_size
inputs = (torch.tensor([1, 1]), torch.tensor([2, 2]))
ret_fut = rpc.rpc_async(worker_name(dst_rank), two_args_two_kwargs, args=inputs)
expected_res = torch.ten... | FutureTypingTest |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_trigger_error.py | {
"start": 319,
"end": 583
} | class ____(View):
def get(self, request: HttpRequest) -> HttpResponseBase:
try:
raise ValueError("An example error")
except Exception:
capture_exception()
return Error500View.as_view()(request)
| DebugTriggerErrorView |
python | streamlit__streamlit | lib/tests/streamlit/runtime/connection_factory_test.py | {
"start": 1406,
"end": 1499
} | class ____(BaseConnection[None]):
def _connect(self, **kwargs):
pass
| MockConnection |
python | spack__spack | lib/spack/spack/vendor/archspec/cpu/microarchitecture.py | {
"start": 979,
"end": 16097
} | class ____:
"""A specific CPU micro-architecture"""
# pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-instance-attributes
#: Aliases for micro-architecture's features
feature_aliases = FEATURE_ALIASES
def __init__(
self,
name: str,
parents: List["M... | Microarchitecture |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/executor/step_delegating/step_handler/base.py | {
"start": 2586,
"end": 3079
} | class ____(ABC):
@property
@abstractmethod
def name(self) -> str:
pass
@abstractmethod
def launch_step(self, step_handler_context: StepHandlerContext) -> Iterator[DagsterEvent]:
pass
@abstractmethod
def check_step_health(self, step_handler_context: StepHandlerContext) -> Ch... | StepHandler |
python | great-expectations__great_expectations | tests/datasource/fluent/test_invalid_datasource.py | {
"start": 1297,
"end": 3020
} | class ____:
"""
Ensure that applicable Datasource/DataAsset public methods are overridden.
Applicable public methods are those that would typically be called when a users is trying to run
some action on a Datasource and would want to know if the Datasource is invalid.
If a method is not overridden,... | TestPublicMethodsAreOverridden |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/base.py | {
"start": 4337,
"end": 8107
} | class ____:
"""
Source column information.
Parameters
----------
table_source_pairs
Sequence of DataSourcePair objects.
Union operations will result in multiple elements.
Notes
-----
This is a thin wrapper around DataSourceInfo that provides
direct access to column-... | ColumnSourceInfo |
python | TheAlgorithms__Python | data_structures/disjoint_set/disjoint_set.py | {
"start": 93,
"end": 1835
} | class ____:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.parent = x
def union_set(x... | Node |
python | django__django | tests/indexes/tests.py | {
"start": 26632,
"end": 27143
} | class ____(TransactionTestCase):
available_apps = ["indexes"]
def test_covering_ignored(self):
index = Index(
name="test_covering_ignored",
fields=["headline"],
include=["pub_date"],
)
with connection.schema_editor() as editor:
editor.add_... | CoveringIndexIgnoredTests |
python | kamyu104__LeetCode-Solutions | Python/next-greater-element-ii.py | {
"start": 29,
"end": 474
} | class ____(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result, stk = [0] * len(nums), []
for i in reversed(xrange(2*len(nums))):
while stk and stk[-1] <= nums[i % len(nums)]:
stk.pop()
... | Solution |
python | huggingface__transformers | tests/models/kyutai_speech_to_text/test_modeling_kyutai_speech_to_text.py | {
"start": 21700,
"end": 24831
} | class ____(unittest.TestCase):
def test_bf16_fp32_conversion(self):
r"""
A test to check whether the argument `keep_in_fp32_modules` correctly does its job
"""
model_checkpoint = "kyutai/stt-2.6b-en-trfs"
orig_import = __import__
accelerate_mock = unittest.mock.Mock()... | KyutaiSpeechToTextBf16Test |
python | prakhar1989__Algorithms | graphs/graph.py | {
"start": 0,
"end": 4524
} | class ____(object):
"""
Graph class - made of nodes and edges
methods: add_edge, add_edges, add_node, add_nodes, has_node,
has_edge, nodes, edges, neighbors, del_node, del_edge, node_order,
set_edge_weight, get_edge_weight
"""
DEFAULT_WEIGHT = 1
DIRECTED = False
def __init__(self)... | graph |
python | pytorch__pytorch | torch/serialization.py | {
"start": 74947,
"end": 85571
} | class ____:
def __init__(self, name):
self._dtype = _get_dtype_from_pickle_storage_type(name)
@property
def dtype(self):
return self._dtype
def __str__(self):
return f"StorageType(dtype={self.dtype})"
def _load(
zip_file,
map_location,
pickle_module,
pickle_fi... | StorageType |
python | PyCQA__pylint | tests/functional/ext/consider_refactoring_into_while_condition/consider_refactoring_into_while_condition_py38.py | {
"start": 270,
"end": 618
} | class ____:
def test_assignment_expr(self):
b = 10
while True: # [consider-refactoring-into-while-condition]
if (a := 10) == (a := 10):
break
while True: # [consider-refactoring-into-while-condition]
if (a if a == 10 else 0) == (b if b == 10 else 0):... | Issue8015 |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 27248,
"end": 42418
} | class ____(TestCase):
def setUp(self):
super().setUp()
if not jtu.is_cuda_compute_capability_equal("9.0"):
self.skipTest("Only works on GPU with capability sm90a")
@parameterized.product(
lhs_transpose=(False, True),
rhs_transpose=(False, True),
in_mlir_dtype_cls=(
ir.F16... | WGMMATest |
python | numba__numba | numba/np/npyimpl.py | {
"start": 2858,
"end": 4050
} | class ____(namedtuple('_ArrayIndexingHelper',
('array', 'indices'))):
def update_indices(self, loop_indices, name):
bld = self.array.builder
intpty = self.array.context.get_value_type(types.intp)
ONE = ir.Constant(ir.IntType(intpty.width), 1)
# ... | _ArrayIndexingHelper |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 31953,
"end": 33650
} | class ____(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.argmin(x, axis=self.axis, keepdims=self.keepdims)
def compute_output_spec(self, ... | Argmin |
python | PyCQA__pylint | tests/functional/u/unused/unused_argument.py | {
"start": 664,
"end": 948
} | class ____(Base):
"child 1"
def inherited(self, aaa, aab, aac):
"overridden method, though don't use every argument"
return aaa
def newmethod(self, aax, aay): # [unused-argument]
"another method, warning for aay desired"
return self, aax
| Sub |
python | numba__numba | numba/tests/test_stencils.py | {
"start": 21250,
"end": 127272
} | class ____(TestStencilBase):
# NOTE: the original implementation of this test used manipulations of the
# Python AST repr of a kernel to create another implementation of the
# stencil being tested so to act as another reference point when
# comparing the various forms of @stencil calls. This implementat... | TestManyStencils |
python | django__django | tests/annotations/models.py | {
"start": 310,
"end": 783
} | class ____(models.Model):
isbn = models.CharField(max_length=9)
name = models.CharField(max_length=255)
pages = models.IntegerField()
rating = models.FloatField()
price = models.DecimalField(decimal_places=2, max_digits=6)
authors = models.ManyToManyField(Author)
contact = models.ForeignKey(... | Book |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 1712,
"end": 3777
} | class ____:
# Whether to upcast parameters and gradients to float32 to avoid accumulation
# errors. It is likely this is always True, but we currently keep this variable
# for experimental purposes.
convert_to_f32: bool = True
enable_load_balance: bool = True
rotate_method: _RotateMethod = _Rota... | _ContextParallelOptions |
python | psf__black | tests/data/cases/target_version_flag.py | {
"start": 211,
"end": 265
} | class ____[T: str]:
def method1(self) -> T: ...
| ClassA |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 132856,
"end": 138478
} | class ____(Request):
"""
Get all 'plot' events for this task
:param task: Task ID
:type task: str
:param iters: Max number of latest iterations for which to return plots
:type iters: int
:param scroll_id: Scroll ID of previous call (used for getting more results)
:type scroll_id: str
... | GetTaskPlotsRequest |
python | joke2k__faker | faker/providers/currency/nl_NL/__init__.py | {
"start": 68,
"end": 295
} | class ____(CurrencyProvider):
price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"]
def pricetag(self) -> str:
return "\N{EURO SIGN}" + self.numerify(self.random_element(self.price_formats))
| Provider |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_bootstrap64.py | {
"start": 306,
"end": 1602
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("bootstrap64.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with default title."""
workbook = Workb... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/trackable/data_structures.py | {
"start": 11170,
"end": 14732
} | class ____(TrackableDataStructure, collections_abc.Sequence):
"""An append-only sequence type which is trackable.
Maintains checkpoint dependencies on its contents (which must also be
trackable), and forwards any `Layer` metadata such as updates and losses.
Note that `List` is purely a container. It lets a `t... | List |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/v1_compat_tests/dense_update_ops_test.py | {
"start": 1033,
"end": 2631
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_v1_only("Non-strict shape assignment only in V1.")
# Bypassing Shape validation in assign with validate_shape only works in V1.
# TF V2 raises error:
# ValueError: Cannot assign value to variable ' Variable:0': Shape mismatch.
# The variable shape (1,)... | AssignOpTest |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_helper_functions.py | {
"start": 3949,
"end": 4539
} | class ____:
"""Test helper functions from ls commands."""
def test_list_package_symbols_success(self):
"""Test _list_package_symbols with valid package."""
# Should not raise exception for valid package
_list_package_symbols("automation.dagster_docs")
def test_list_package_symbols_... | TestLsHelperFunctions |
python | arrow-py__arrow | arrow/arrow.py | {
"start": 1308,
"end": 64985
} | class ____:
"""An :class:`Arrow <arrow.arrow.Arrow>` object.
Implements the ``datetime`` interface, behaving as an aware ``datetime`` while implementing
additional functionality.
:param year: the calendar year.
:param month: the calendar month.
:param day: the calendar day.
:param hour: (o... | Arrow |
python | pytorch__pytorch | torch/_dynamo/types.py | {
"start": 3174,
"end": 3438
} | class ____(Protocol):
def __call__(
self,
frame: DynamoFrameType,
cache_entry: Optional[CacheEntry],
frame_state: FrameState,
) -> ConvertFrameReturn: ...
DynamoCallback = Union[DynamoCallbackFn, None, bool]
| DynamoCallbackFn |
python | huggingface__transformers | examples/pytorch/language-modeling/run_fim.py | {
"start": 2543,
"end": 6244
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
"""
model_name_or_path: Optional[str] = field(
default=None,
metadata={
"help": (
"The model checkpoint for weights initialization. Don't se... | ModelArguments |
python | doocs__leetcode | solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/Solution.py | {
"start": 151,
"end": 560
} | class ____:
def sortLinkedList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = head, head.next
while curr:
if curr.val < 0:
t = curr.next
prev.next = t
curr.next = head
head = curr
curr = ... | Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/scripting.py | {
"start": 50580,
"end": 51875
} | class ____(RegexLexer):
"""
For `MOOCode <http://www.moo.mud.org/>`_ (the MOO scripting
language).
.. versionadded:: 0.9
"""
name = 'MOOCode'
filenames = ['*.moo']
aliases = ['moocode', 'moo']
mimetypes = ['text/x-moocode']
tokens = {
'root': [
# Numbers
... | MOOCodeLexer |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/container.py | {
"start": 4375,
"end": 4432
} | class ____(Enum):
V1 = "V1"
V2 = "V2"
| CGroupVersion |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 6194,
"end": 6413
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI PipelineJob link."""
name = "Pipeline Job"
key = "pipeline_job_conf"
format_str = VERTEX_AI_PIPELINE_JOB_LINK
| VertexAIPipelineJobLink |
python | sphinx-doc__sphinx | sphinx/util/logging.py | {
"start": 13322,
"end": 13672
} | class ____(logging.Filter):
"""Prepend prefix to all log records."""
def __init__(self, prefix: str) -> None:
self.prefix = prefix
super().__init__()
def filter(self, record: logging.LogRecord) -> bool:
if self.prefix:
record.msg = self.prefix + ' ' + record.msg
... | MessagePrefixFilter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.