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 | ray-project__ray | rllib/examples/envs/classes/correlated_actions_env.py | {
"start": 85,
"end": 3236
} | class ____(gym.Env):
"""Environment that can only be solved through an autoregressive action model.
In each step, the agent observes a random number (between -1 and 1) and has
to choose two actions, a1 (discrete, 0, 1, or 2) and a2 (cont. between -1 and 1).
The reward is constructed such that actions ... | CorrelatedActionsEnv |
python | xlwings__xlwings | tests/test_conversion.py | {
"start": 4764,
"end": 7648
} | class ____(TestBase):
def test_array(self):
# 1d array
array_1d = np.array([1.1, 2.2, np.nan, -4.4])
self.wb1.sheets[0].range("A1").value = array_1d
cells = self.wb1.sheets[0].range("A1:D1").options(np.array).value
assert_array_equal(cells, array_1d)
# 2d array
... | TestNumpy |
python | sqlalchemy__sqlalchemy | test/orm/test_composites.py | {
"start": 32401,
"end": 33050
} | class ____(PrimaryKeyTest):
@classmethod
def setup_mappers(cls):
graphs = cls.tables.graphs
@dataclasses.dataclass
class Version:
id: int
version: int
cls.classes.Version = Version
class Graph(cls.Comparable):
def __init__(self, vers... | PrimaryKeyTestDataclasses |
python | pyqtgraph__pyqtgraph | pyqtgraph/console/Console.py | {
"start": 211,
"end": 7178
} | class ____(QtWidgets.QWidget):
"""
Widget displaying console output and accepting command input.
Implements:
- eval python expressions / exec python statements
- storable history of commands
- exception handling allowing commands to be interpreted in the context of any level in th... | ConsoleWidget |
python | spyder-ide__spyder | spyder/plugins/remoteclient/widgets/connectionpages.py | {
"start": 2066,
"end": 2312
} | class ____:
NewEnv = 1
ImportEnv = 2
NoEnv = 4
# =============================================================================
# ---- Pages
# =============================================================================
| CreateEnvMethods |
python | huggingface__transformers | src/transformers/models/tapas/modeling_tapas.py | {
"start": 57788,
"end": 57985
} | class ____(str, enum.Enum):
RATIO = "ratio"
FIRST_ORDER = "first_order"
SECOND_ORDER = "second_order"
# Beginning of everything related to segmented tensors
| AverageApproximationFunction |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 95335,
"end": 96610
} | class ____(TypedDict, total=False):
"""
:class:`altair.FeatureGeometryGeoJsonProperties` ``TypedDict`` wrapper.
Parameters
----------
geometry
The feature's geometry
properties
Properties associated with this feature.
type
Specifies the type of GeoJSON object.
bb... | FeatureGeometryGeoJsonPropertiesKwds |
python | python__mypy | mypy/config_parser.py | {
"start": 662,
"end": 25918
} | class ____(argparse.ArgumentTypeError):
"""Provide a fallback value if the Python version is unsupported."""
def __init__(self, *args: Any, fallback: tuple[int, int]) -> None:
self.fallback = fallback
super().__init__(*args)
def parse_version(v: str | float) -> tuple[int, int]:
m = re.mat... | VersionTypeError |
python | pytorch__pytorch | torch/__init__.py | {
"start": 72775,
"end": 73007
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.cfloat
| ComplexFloatStorage |
python | numba__llvmlite | llvmlite/binding/ffi.py | {
"start": 11001,
"end": 13163
} | class ____(object):
"""
A wrapper around a ctypes pointer to a LLVM object ("resource").
"""
_closed = False
_as_parameter_ = _DeadPointer()
# Whether this object pointer is owned by another one.
_owned = False
def __init__(self, ptr):
if ptr is None:
raise ValueErro... | ObjectRef |
python | kamyu104__LeetCode-Solutions | Python/regions-cut-by-slashes.py | {
"start": 498,
"end": 1832
} | class ____(object):
def regionsBySlashes(self, grid):
"""
:type grid: List[str]
:rtype: int
"""
def index(n, i, j, k):
return (i*n + j)*4 + k
union_find = UnionFind(len(grid)**2 * 4)
N, E, S, W = range(4)
for i in xrange(len(grid)):
... | Solution |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py | {
"start": 25843,
"end": 30164
} | class ____:
"""Test before_agent and after_agent middleware hooks."""
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("hook_type", ["before", "after"])
async def test_hook_execution(self, is_async: bool, hook_type: str) -> None:
"""Test that agent hooks are called i... | TestAgentMiddlewareHooks |
python | ray-project__ray | python/ray/serve/tests/test_config_files/test_dag/hello_serve.py | {
"start": 154,
"end": 289
} | class ____:
async def __call__(self, starlette_request: Request) -> None:
return hello()
model = HelloModel.bind()
| HelloModel |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/container_volume.py | {
"start": 1193,
"end": 5794
} | class ____(BaseHook):
"""
A hook which wraps an Azure Volume.
:param azure_container_volume_conn_id: Reference to the
:ref:`Azure Container Volume connection id <howto/connection:azure_container_volume>`
of an Azure account of which container volumes should be used.
"""
conn_name_a... | AzureContainerVolumeHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-instagram/integration_tests/test_streams.py | {
"start": 1233,
"end": 3326
} | class ____:
"""Custom integration tests should test incremental with nested state"""
def test_incremental_streams(self, config, state):
records, states = self._read_records(config, "user_insights")
assert len(records) == 30, "UserInsights for two accounts over last 30 day should return 30 recor... | TestInstagramSource |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/where_test.py | {
"start": 706,
"end": 1403
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, cond_shape, input_shape, other_shape, dtype, device):
def _create_tensor(shape):
return torch.randn(*shape, dtype=dtype, device=device)
self.inputs = {
"condition": _create_tensor(cond_shape) > 0,
"input": _... | WhereBenchmark |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/confirm.py | {
"start": 956,
"end": 4077
} | class ____(Enum):
YES = "y"
NO = "n"
QUIT = "q"
def user_confirm(
message: str,
timeout: float | None = None,
default_answer: Answer | None = Answer.NO,
quit_allowed: bool = True,
) -> Answer:
"""Ask the user for confirmation.
:param message: message to display to the user (should... | Answer |
python | weaviate__weaviate-python-client | weaviate/backup/sync.py | {
"start": 163,
"end": 220
} | class ____(_BackupExecutor[ConnectionSync]):
pass
| _Backup |
python | django__django | django/template/response.py | {
"start": 5098,
"end": 5584
} | class ____(SimpleTemplateResponse):
rendering_attrs = [*SimpleTemplateResponse.rendering_attrs, "_request"]
def __init__(
self,
request,
template,
context=None,
content_type=None,
status=None,
charset=None,
using=None,
headers=None,
):... | TemplateResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 651,
"end": 1282
} | class ____(ClassB, ClassC):
def __init__(self):
super().method2()
super().method3()
# This should generate an error
super().non_method1()
def method(self):
def inner():
super().method1()
super(ClassD)
# This should generate an error
super(ClassD).non_meth... | ClassD |
python | tensorflow__tensorflow | tensorflow/python/framework/ops.py | {
"start": 214627,
"end": 217206
} | class ____(contextlib.AbstractContextManager[Optional[str]]): # pylint: disable=invalid-name
"""A context manager for use when defining a Python op.
This context manager validates that the given `values` are from the
same graph, makes that graph the default graph, and pushes a
name scope in that graph (see
... | name_scope_v1 |
python | numpy__numpy | numpy/lib/tests/test__datasource.py | {
"start": 8530,
"end": 9675
} | class ____:
def test_ValidFile(self, tmp_path):
# Create local temp file
repos = datasource.Repository(valid_baseurl(), tmp_path)
tmpfile = valid_textfile(tmp_path)
assert_(repos.exists(tmpfile))
def test_InvalidFile(self, tmp_path):
repos = datasource.Repository(valid_b... | TestRepositoryExists |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 16888,
"end": 17225
} | class ____(CharStreamException):
def __init__(self, *args):
if args and isinstance(args[0], Exception):
io = args[0]
CharStreamException.__init__(self, str(io))
self.io = io
else:
CharStreamException.__init__(self, *args)
self.io = self
| CharStreamIOException |
python | huggingface__transformers | src/transformers/models/sam2/modeling_sam2.py | {
"start": 23826,
"end": 26633
} | class ____(Sam2PreTrainedModel):
config_class = Sam2HieraDetConfig
main_input_name = "pixel_values"
_can_record_outputs = {
"hidden_states": Sam2MultiScaleBlock,
"attentions": Sam2MultiScaleAttention,
}
def __init__(self, config: Sam2HieraDetConfig):
super().__init__(config)... | Sam2HieraDetModel |
python | tensorflow__tensorflow | tensorflow/python/autograph/impl/conversion_test.py | {
"start": 1238,
"end": 4119
} | class ____(test.TestCase):
def _simple_program_ctx(self):
return converter.ProgramContext(
options=converter.ConversionOptions(recursive=True),
autograph_module=api)
def test_is_allowlisted(self):
def test_fn():
return constant_op.constant(1)
self.assertFalse(conversion.is_allo... | ConversionTest |
python | pypa__pip | src/pip/_vendor/idna/core.py | {
"start": 480,
"end": 598
} | class ____(IDNAError):
"""Exception when a disallowed or unallocated codepoint is used"""
pass
| InvalidCodepoint |
python | py-pdf__pypdf | pypdf/_encryption.py | {
"start": 32821,
"end": 48697
} | class ____:
"""
Collects and manages parameters for PDF document encryption and decryption.
Args:
V: A code specifying the algorithm to be used in encrypting and
decrypting the document.
R: The revision of the standard security handler.
Length: The length of the encryptio... | Encryption |
python | astropy__astropy | astropy/samp/utils.py | {
"start": 1677,
"end": 2518
} | class ____:
"""
A thread-safe pool of `xmlrpc.ServerProxy` objects.
"""
def __init__(self, size, proxy_class, *args, **keywords):
self._proxies = queue.Queue(size)
for _ in range(size):
self._proxies.put(proxy_class(*args, **keywords))
def __getattr__(self, name):
... | ServerProxyPool |
python | streamlit__streamlit | lib/tests/streamlit/streamlit_test.py | {
"start": 2236,
"end": 7675
} | class ____(unittest.TestCase):
"""Test Streamlit.__init__.py."""
def test_streamlit_version(self):
"""Test streamlit.__version__."""
assert __version__ == get_version()
def test_get_option(self):
"""Test streamlit.get_option."""
# This is set in lib/tests/conftest.py to Fal... | StreamlitTest |
python | zarr-developers__zarr-python | src/zarr/abc/codec.py | {
"start": 8766,
"end": 15687
} | class ____:
"""Base class for implementing CodecPipeline.
A CodecPipeline implements the read and write paths for chunk data.
On the read path, it is responsible for fetching chunks from a store (via ByteGetter),
decoding them and assembling an output array. On the write path, it encodes the chunks
... | CodecPipeline |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 84221,
"end": 84478
} | class ____(CIntType):
is_enum = 1
def sign_and_name(self):
return 'int'
def specialization_name(self):
# ensure that the to/from Python functions don't conflict with
# "int"
return '__pyx_anon_enum'
| CAnonEnumType |
python | kubernetes-client__python | kubernetes/client/models/v1_container.py | {
"start": 383,
"end": 35110
} | 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... | V1Container |
python | huggingface__transformers | src/transformers/models/lfm2_vl/modeling_lfm2_vl.py | {
"start": 1680,
"end": 3273
} | class ____(nn.Module):
def __init__(self, config: Lfm2VlConfig):
super().__init__()
in_channels = config.vision_config.hidden_size * (config.downsample_factor**2)
self.factor = config.downsample_factor
self.layer_norm = nn.LayerNorm(in_channels)
self.linear_1 = nn.Linear(
... | Lfm2VlMultiModalProjector |
python | fluentpython__example-code | attic/concurrency/flags/count_colors.py | {
"start": 16,
"end": 506
} | class ____:
def __init__(self, master):
canvas = tkinter.Canvas(master)
canvas.image = tkinter.PhotoImage(file = 'img/br.gif')
print(vars(canvas.image))
canvas.create_image(0,0, image=canvas.image, anchor=tkinter.NW)
canvas.bind('<Button-2>', self.right_click)
can... | Test |
python | Textualize__textual | src/textual/widgets/_selection_list.py | {
"start": 1209,
"end": 2501
} | class ____(Generic[SelectionType], Option):
"""A selection for a [`SelectionList`][textual.widgets.SelectionList]."""
def __init__(
self,
prompt: ContentText,
value: SelectionType,
initial_state: bool = False,
id: str | None = None,
disabled: bool = False,
):... | Selection |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_versions.py | {
"start": 961,
"end": 1373
} | class ____(GQLResult):
node: Optional[ArtifactMembershipFragment]
RegistryVersions.model_rebuild()
RegistryVersionsOrganization.model_rebuild()
RegistryVersionsOrganizationOrgEntity.model_rebuild()
RegistryVersionsOrganizationOrgEntityArtifactMemberships.model_rebuild()
RegistryVersionsOrganizationOrgEntityArtifa... | RegistryVersionsOrganizationOrgEntityArtifactMembershipsEdges |
python | doocs__leetcode | solution/0000-0099/0032.Longest Valid Parentheses/Solution2.py | {
"start": 0,
"end": 402
} | class ____:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
ans = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
... | Solution |
python | joblib__joblib | joblib/test/test_numpy_pickle.py | {
"start": 37666,
"end": 42130
} | class ____(CompressorWrapper):
def __init__(self):
CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b"prefix")
def test_register_compressor_already_registered():
# Test registration of existing compressor files.
compressor_name = "test-name"
# register a test compressor
register... | StandardLibGzipCompressorWrapper |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 69292,
"end": 76730
} | class ____(SocketDummyServerTestCase):
def test_httplib_headers_case_insensitive(self) -> None:
self.start_response_handler(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 0\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
with HTTPConnectionPool(self.... | TestHeaders |
python | pytorch__pytorch | benchmarks/dynamo/microbenchmarks/microbench.py | {
"start": 1815,
"end": 1946
} | class ____(torch.nn.Module):
def forward(self, x, y):
# return x / (torch.abs(x) + 1.0),
return (x + y,)
| MyModel2 |
python | django__django | tests/db_functions/migrations/0002_create_test_models.py | {
"start": 43,
"end": 3543
} | class ____(migrations.Migration):
dependencies = [
("db_functions", "0001_setup_extensions"),
]
operations = [
migrations.CreateModel(
name="Author",
fields=[
("name", models.CharField(max_length=50)),
("alias", models.CharField(max_le... | Migration |
python | openai__openai-python | src/openai/types/responses/response_file_search_tool_call.py | {
"start": 1062,
"end": 1664
} | class ____(BaseModel):
id: str
"""The unique ID of the file search tool call."""
queries: List[str]
"""The queries used to search for files."""
status: Literal["in_progress", "searching", "completed", "incomplete", "failed"]
"""The status of the file search tool call.
One of `in_progress`... | ResponseFileSearchToolCall |
python | FactoryBoy__factory_boy | tests/test_fuzzy.py | {
"start": 19076,
"end": 20215
} | class ____(unittest.TestCase):
def test_unbiased(self):
chars = ['a', 'b', 'c']
fuzz = fuzzy.FuzzyText(prefix='pre', suffix='post', chars=chars, length=12)
res = utils.evaluate_declaration(fuzz)
self.assertEqual('pre', res[:3])
self.assertEqual('post', res[-4:])
sel... | FuzzyTextTestCase |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/obscure_tito.py | {
"start": 216,
"end": 335
} | class ____:
def update(self, parameter):
...
def taint_parameter(self, tainted_parameter):
...
| C |
python | ansible__ansible | lib/ansible/_internal/_templating/_jinja_bits.py | {
"start": 23455,
"end": 43835
} | class ____(SandboxedEnvironment):
"""
Our custom environment, which simply allows us to override the class-level
values for the Template and Context classes used by jinja2 internally.
"""
context_class = AnsibleContext
template_class = AnsibleTemplate
code_generator_class = AnsibleCodeGener... | AnsibleEnvironment |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 33252,
"end": 37562
} | class ____(test.TestCase):
def _npSoftplus(self, np_features):
np_features = np.asarray(np_features)
zero = np.asarray(0).astype(np_features.dtype)
return np.logaddexp(zero, np_features)
def _testSoftplus(self, np_features, use_gpu=False):
np_features = np.asarray(np_features)
np_softplus = se... | SoftplusTest |
python | sympy__sympy | sympy/solvers/polysys.py | {
"start": 978,
"end": 27168
} | class ____(Exception):
"""Raised when solver's conditions were not met. """
def solve_poly_system(seq, *gens, strict=False, **args):
"""
Return a list of solutions for the system of polynomial equations
or else None.
Parameters
==========
seq: a list/tuple/set
Listing all the equ... | SolveFailed |
python | huggingface__transformers | tests/models/udop/test_tokenization_udop.py | {
"start": 1278,
"end": 83357
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "microsoft/udop-large"
tokenizer_class = UdopTokenizer
rust_tokenizer_class = UdopTokenizer
from_pretrained_filter = filter_non_english
test_seq2seq = False
test_sentencepiece = True
def get_words_and_boxes(self):
... | UdopTokenizationTest |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_table_row_count_to_be_between.py | {
"start": 2728,
"end": 15973
} | class ____(BatchExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectTableRowCountToBeBetween is a \
Batch Expectation.
BatchExpectations are one of the most common types of Expectation.
They are evaluated for an entire Batch, and answer a semantic question about the Batch itself.
... | ExpectTableRowCountToBeBetween |
python | jupyterlab__jupyterlab | jupyterlab/semver.py | {
"start": 1677,
"end": 9495
} | class ____(list):
def __setitem__(self, i, v):
try:
list.__setitem__(self, i, v)
except IndexError:
if len(self) == i:
self.append(v)
else:
raise
def list_get(xs, i):
try:
return xs[i]
except IndexError:
re... | Extendlist |
python | huggingface__transformers | examples/modular-transformers/modeling_roberta.py | {
"start": 1587,
"end": 5723
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.E... | RobertaEmbeddings |
python | realpython__materials | python-getter-setter/employee4.py | {
"start": 28,
"end": 302
} | class ____:
def __set_name__(self, owner, name):
self._name = name
def __get__(self, instance, owner):
return instance.__dict__[self._name]
def __set__(self, instance, value):
instance.__dict__[self._name] = date.fromisoformat(value)
| Date |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/knowledge_graph/retrievers.py | {
"start": 1315,
"end": 2075
} | class ____(str, Enum):
"""
Query mode enum for Knowledge Graphs.
Can be passed as the enum struct, or as the underlying string.
Attributes:
KEYWORD ("keyword"): Default query mode, using keywords to find triplets.
EMBEDDING ("embedding"): Embedding mode, using embeddings to find
... | KGRetrieverMode |
python | kamyu104__LeetCode-Solutions | Python/maximum-xor-score-subarray-queries.py | {
"start": 42,
"end": 723
} | class ____(object):
def maximumSubarrayXor(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
dp = [[nums[i] if j == 0 else 0 for j in xrange(len(nums)-i)] for i in xrange(len(nums))]
for i in reversed(xrange(l... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/util.py | {
"start": 53782,
"end": 55725
} | class ____:
"""Helper class to promote private subclass docstring to public counterpart.
Example:
```python
class TransformedDistribution(Distribution):
@distribution_util.AppendDocstring(
additional_note="A special note!",
kwargs_dict={"foo": "An extra arg."})
def _prob(self, y, foo=None)... | AppendDocstring |
python | tensorflow__tensorflow | tensorflow/python/types/distribute.py | {
"start": 12650,
"end": 21596
} | class ____(Iterable):
# pylint: disable=line-too-long
"""Represents a dataset distributed among devices and machines.
A `tf.distribute.DistributedDataset` could be thought of as a "distributed"
dataset. When you use `tf.distribute` API to scale training to multiple
devices or machines, you also need to distr... | DistributedDatasetInterface |
python | Textualize__textual | docs/examples/widgets/vertical_rules.py | {
"start": 127,
"end": 917
} | class ____(App):
CSS_PATH = "vertical_rules.tcss"
def compose(self) -> ComposeResult:
with Horizontal():
yield Label("solid")
yield Rule(orientation="vertical")
yield Label("heavy")
yield Rule(orientation="vertical", line_style="heavy")
yield ... | VerticalRulesApp |
python | arrow-py__arrow | tests/test_arrow.py | {
"start": 40600,
"end": 53173
} | class ____:
def test_year(self):
result = list(
arrow.Arrow.span_range("year", datetime(2013, 2, 1), datetime(2016, 3, 31))
)
assert result == [
(
arrow.Arrow(2013, 1, 1),
arrow.Arrow(2013, 12, 31, 23, 59, 59, 999999),
),
... | TestArrowSpanRange |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 79325,
"end": 85129
} | class ____(Kernel):
"""Wrapper for kernels in sklearn.metrics.pairwise.
A thin wrapper around the functionality of the kernels in
sklearn.metrics.pairwise.
Note: Evaluation of eval_gradient is not analytic but numeric and all
kernels support only isotropic distances. The parameter gamma is
... | PairwiseKernel |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/providers/workspace.py | {
"start": 663,
"end": 7734
} | class ____:
@send_notification(method=CompletionRequestTypes.WORKSPACE_CONFIGURATION_CHANGE)
def send_configurations(self, configurations, *args):
self.configurations = configurations
params = {
'settings': configurations
}
return params
@send_response
@handl... | WorkspaceProvider |
python | pytorch__pytorch | torch/export/_trace.py | {
"start": 4987,
"end": 27750
} | class ____:
aten: ATenExportArtifact
in_spec: TreeSpec
out_spec: TreeSpec
fake_mode: FakeTensorMode
module_call_specs: dict[str, dict[str, pytree.TreeSpec]]
DEFAULT_EXPORT_DYNAMO_CONFIG = ExportDynamoConfig()
DEFAULT_EXPORT_DYNAMO_CONFIG.reorderable_logging_functions = {
logging.critical,
... | ExportArtifact |
python | getsentry__sentry | src/sentry/replays/lib/new_query/conditions.py | {
"start": 2375,
"end": 2731
} | class ____(GenericBase):
"""Boolean scalar condition class."""
@staticmethod
def visit_eq(expression: Expression, value: bool) -> Condition:
return Condition(expression, Op.EQ, value)
@staticmethod
def visit_neq(expression: Expression, value: bool) -> Condition:
return Condition(ex... | BooleanScalar |
python | realpython__materials | django-vue-graphql/source_code_final/back_end/blog/schema.py | {
"start": 304,
"end": 384
} | class ____(DjangoObjectType):
class Meta:
model = models.Post
| PostType |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 22486,
"end": 22679
} | class ____(NotFoundError):
"""
64-bit Lapack libraries not found.
Known libraries in numpy/distutils/site.cfg file are:
openblas64_, openblas_ilp64
"""
| LapackILP64NotFoundError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 574273,
"end": 575031
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for DeploymentStatus."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("DeploymentStatusEdge"), graphql_name="edges")
"""A list of edges."""
... | DeploymentStatusConnection |
python | zarr-developers__zarr-python | src/zarr/core/indexing.py | {
"start": 34863,
"end": 36014
} | class ____:
array: AnyArray
# TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool
def __getitem__(self, selection: OrthogonalSelection | AnyArray) -> NDArrayLikeOrScalar:
from zarr.core.array import Array
# if input is a Zarr array, we materi... | OIndex |
python | PyCQA__isort | isort/exceptions.py | {
"start": 3632,
"end": 4241
} | class ____(ISortError):
"""Raised when one of isorts literal sorting comments is used but isort can't parse the
the given data structure.
"""
def __init__(self, code: str, original_error: Exception | type[Exception]):
super().__init__(
f"isort failed to parse the given literal {code... | LiteralParsingFailure |
python | getsentry__sentry | tests/sentry/tsdb/test_snuba.py | {
"start": 600,
"end": 19074
} | class ____(OutcomesSnubaTest):
def setUp(self) -> None:
super().setUp()
self.db = SnubaTSDB()
# Set up the times
self.now = datetime.now(timezone.utc)
self.start_time = self.now - timedelta(days=7)
self.one_day_later = self.start_time + timedelta(days=1)
self... | SnubaTSDBTest |
python | geekcomputers__Python | insta_monitering/insta_api.py | {
"start": 4280,
"end": 5529
} | class ____(tornado.web.RequestHandler):
def get(self):
try:
q = self.get_argument("q")
user = self.get_argument("userId")
type = self.get_argument("type")
productId = self.get_argument("productId")
date = self.get_argument("date")
limit... | SenderHandlerinstaGreater |
python | huggingface__transformers | tests/models/beit/test_modeling_beit.py | {
"start": 1740,
"end": 8798
} | class ____:
def __init__(
self,
parent,
vocab_size=100,
batch_size=13,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=4,
num_attention_heads=4,
i... | BeitModelTester |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | {
"start": 15280,
"end": 17759
} | class ____(_regconfig_fn):
"""The PostgreSQL ``ts_headline`` SQL function.
This function applies automatic casting of the REGCONFIG argument
to use the :class:`_postgresql.REGCONFIG` datatype automatically,
and applies a return type of :class:`_types.TEXT`.
Assuming the PostgreSQL dialect has been... | ts_headline |
python | matplotlib__matplotlib | galleries/examples/widgets/polygon_selector_demo.py | {
"start": 341,
"end": 3267
} | class ____:
"""
Select indices from a matplotlib collection using `PolygonSelector`.
Selected indices are saved in the `ind` attribute. This tool fades out the
points that are not part of the selection (i.e., reduces their alpha
values). If your collection has alpha < 1, this tool will permanently
... | SelectFromCollection |
python | hyperopt__hyperopt | hyperopt/pyll/base.py | {
"start": 24965,
"end": 35318
} | class ____:
"""Placeholder representing a garbage-collected value"""
def rec_eval(
expr,
deepcopy_inputs=False,
memo=None,
max_program_len=None,
memo_gc=True,
print_trace=False,
print_node_on_error=True,
):
"""
expr - pyll Apply instance to be evaluated
memo - optional dic... | GarbageCollected |
python | html5lib__html5lib-python | html5lib/tests/tree_construction.py | {
"start": 813,
"end": 2876
} | class ____(pytest.Collector):
def __init__(self, name, parent=None, config=None, session=None, testdata=None):
super(TreeConstructionTest, self).__init__(name, parent, config, session)
self.testdata = testdata
def collect(self):
for treeName, treeAPIs in sorted(treeTypes.items()):
... | TreeConstructionTest |
python | ray-project__ray | rllib/algorithms/tests/test_placement_groups.py | {
"start": 321,
"end": 743
} | class ____(Callback):
def on_step_end(self, iteration, trials, **info):
num_running = len([t for t in trials if t.status == Trial.RUNNING])
# All 3 trials (3 different learning rates) should be scheduled.
assert 3 == min(3, len(trials))
# Cannot run more than 2 at a time
# (... | _TestCallback |
python | spack__spack | lib/spack/spack/vendor/jinja2/exceptions.py | {
"start": 2424,
"end": 4171
} | class ____(TemplateError):
"""Raised to tell the user that there is a problem with the template."""
def __init__(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> None:
super().__init__(message)
sel... | TemplateSyntaxError |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py | {
"start": 3293,
"end": 5903
} | class ____(APITestCase):
__test__ = Abstract(__module__, __qualname__)
@cached_property
def organization(self):
return self.create_organization()
@cached_property
def project(self):
return self.create_project(organization=self.organization)
@cached_property
def user(self):... | AlertRuleBase |
python | docker__docker-py | docker/types/services.py | {
"start": 23000,
"end": 25250
} | class ____(dict):
"""
Indicate whether a service or a job should be deployed as a replicated
or global service, and associated parameters
Args:
mode (string): Can be either ``replicated``, ``global``,
``replicated-job`` or ``global-job``
replicas (int):... | ServiceMode |
python | getsentry__sentry | tests/sentry/tasks/test_base.py | {
"start": 4850,
"end": 10018
} | class ____(Exception):
pass
@patch("sentry_sdk.capture_exception")
def test_retry_timeout_enabled_taskbroker(capture_exception) -> None:
@retry(timeouts=True)
def timeout_retry_task():
raise ProcessingDeadlineExceeded()
with pytest.raises(RetryTaskError):
timeout_retry_task()
ass... | ExpectedException |
python | getsentry__sentry | src/sentry/migrations/0984_authprovider_json_field.py | {
"start": 244,
"end": 2075
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataprep.py | {
"start": 1969,
"end": 12236
} | class ____(BaseHook):
"""
Hook for connection with Dataprep API.
To get connection Dataprep with Airflow you need Dataprep token.
https://clouddataprep.com/documentation/api#section/Authentication
It should be added to the Connection in Airflow in JSON format.
"""
conn_name_attr = "data... | GoogleDataprepHook |
python | kamyu104__LeetCode-Solutions | Python/symmetric-tree.py | {
"start": 942,
"end": 1478
} | class ____(object):
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root is None:
return True
return self.isSymmetricRecu(root.left, root.right)
def isSymmetricRecu(self, left, right):
if left is None and right is None:
ret... | Solution2 |
python | python-pillow__Pillow | src/PIL/BlpImagePlugin.py | {
"start": 1454,
"end": 1544
} | class ____(IntEnum):
UNCOMPRESSED = 1
DXT = 2
UNCOMPRESSED_RAW_BGRA = 3
| Encoding |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1573816,
"end": 1574019
} | class ____(VegaLiteSchema):
"""Vector10string schema wrapper."""
_schema = {"$ref": "#/definitions/Vector10<string>"}
def __init__(self, *args):
super().__init__(*args)
| Vector10string |
python | streamlit__streamlit | lib/tests/streamlit/data_mocks/ray_mocks.py | {
"start": 731,
"end": 1490
} | class ____:
"""This is dummy Dataset class, which imitates ray.data.dataset.Dataset class
for testing purposes. We use this to make sure that our code does a special handling
if it detects a Ray Datasets.
This allows testing of the functionality without having the library installed,
but it won't ca... | Dataset |
python | django__django | django/db/models/fields/json.py | {
"start": 701,
"end": 5177
} | class ____(CheckFieldDefaultMixin, Field):
empty_strings_allowed = False
description = _("A JSON object")
default_error_messages = {
"invalid": _("Value must be valid JSON."),
}
_default_hint = ("dict", "{}")
def __init__(
self,
verbose_name=None,
name=None,
... | JSONField |
python | huggingface__transformers | src/transformers/models/bartpho/tokenization_bartpho.py | {
"start": 1120,
"end": 14295
} | class ____(SentencePieceBackend):
"""
Adapted from [`XLMRobertaTokenizer`]. Based on [SentencePiece](https://github.com/google/sentencepiece).
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regardi... | BartphoTokenizer |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/dynamic_rendezvous.py | {
"start": 17095,
"end": 18074
} | class ____(ABC):
"""Execute rendezvous operations."""
@abstractmethod
def run(
self,
state_handler: Callable[[_RendezvousContext, float], _Action],
deadline: float,
update_deadline: Callable[[timedelta], float] | None = None,
) -> None:
"""Execute a rendezvous op... | _RendezvousOpExecutor |
python | coleifer__peewee | tests/sqliteq.py | {
"start": 7081,
"end": 7373
} | class ____(BaseTestQueueDatabase, BaseTestCase):
database_config = {'use_gevent': True}
n_rows = 10
n_threads = 40
def create_thread(self, fn, *args):
return gevent.Greenlet(fn, *args)
def create_event(self):
return GreenEvent()
| TestThreadedDatabaseGreenlets |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-potholes-that-can-be-fixed.py | {
"start": 1450,
"end": 2062
} | class ____(object):
def maxPotholes(self, road, budget):
"""
:type road: str
:type budget: int
:rtype: int
"""
ls = []
l = 0
for i in xrange(len(road)):
l += 1
if i+1 == len(road) or road[i+1] != road[i]:
if road... | Solution2 |
python | huggingface__transformers | tests/models/falcon/test_modeling_falcon.py | {
"start": 1993,
"end": 7902
} | class ____(unittest.TestCase):
@slow
def test_lm_generate_falcon(self):
tokenizer = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b")
model = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b")
model.eval()
model.to(torch_device)
inputs = tokenizer("... | FalconLanguageGenerationTest |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/model_parallel.py | {
"start": 14351,
"end": 26647
} | class ____(AbstractContextManager):
def __init__(self, module: Module, enabled: bool) -> None:
self._module = module
self._enabled = enabled
def _set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
from torch.distributed._composable.fsdp import FSDPModule
for mod in... | _FSDPNoSync |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_blank03.py | {
"start": 315,
"end": 1382
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_blank03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | hyperopt__hyperopt | hyperopt/rdists.py | {
"start": 5538,
"end": 7005
} | class ____:
"""Stats for Y = q * round(X / q) where X ~ N(mu, sigma)"""
def __init__(self, mu, sigma, q):
self.mu, self.sigma = list(map(float, (mu, sigma)))
self.q = q
# -- distfn for using the CDF
self._norm_logcdf = scipy.stats.norm(loc=mu, scale=sigma).logcdf
def in_dom... | qnormal_gen |
python | sympy__sympy | sympy/functions/elementary/trigonometric.py | {
"start": 60913,
"end": 64414
} | class ____(ReciprocalTrigonometricFunction):
"""
The cosecant function.
Returns the cosecant of x (measured in radians).
Explanation
===========
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import csc
>>> from sympy.abc import x
... | csc |
python | doocs__leetcode | solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.py | {
"start": 192,
"end": 594
} | class ____:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]):
if root is None:
return
dfs(root.left)
nonlocal pre, ans
ans = min(ans, root.val - pre)
pre = root.val
dfs(root.righ... | Solution |
python | graphql-python__graphene | graphene/tests/issues/test_1293.py | {
"start": 701,
"end": 769
} | class ____(graphene.ObjectType):
goodbye = graphene.String()
| Query |
python | pezy__LeetCode | 001. Add Two Numbers/solution.py | {
"start": 140,
"end": 1199
} | class ____:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
p = head
quot = 0
while l1 or l2 or quot != 0:
if l1:
quot += l1.val
l1 =... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 27777,
"end": 28371
} | class ____(sgqlc.types.Enum):
"""The possible states in which authentication can be configured with
an identity provider.
Enumeration Choices:
* `CONFIGURED`: Authentication with an identity provider is
configured but not enforced.
* `ENFORCED`: Authentication with an identity provider is
... | IdentityProviderConfigurationState |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_getlimits.py | {
"start": 1140,
"end": 1368
} | class ____(TestCase):
def test_singleton(self):
ftype = finfo(half)
ftype2 = finfo(half)
assert_equal(id(ftype), id(ftype2))
@skip(reason="torch.finfo is not a singleton. Why demanding it is?")
| TestHalf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.