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 | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 15492,
"end": 16435
} | class ____(GroupsConsumerMixin, BaseCrossValidator):
def __init__(self, registry=None):
self.registry = registry
def split(self, X, y=None, groups="default", metadata="default"):
if self.registry is not None:
self.registry.append(self)
record_metadata_not_default(self, groups=groups, metadata=metadata)
split_index = len(X) // 2
train_indices = list(range(0, split_index))
test_indices = list(range(split_index, len(X)))
yield test_indices, train_indices
yield train_indices, test_indices
def get_n_splits(self, X=None, y=None, groups=None, metadata=None):
return 2
def _iter_test_indices(self, X=None, y=None, groups=None):
split_index = len(X) // 2
train_indices = list(range(0, split_index))
test_indices = list(range(split_index, len(X)))
yield test_indices
yield train_indices
| ConsumingSplitter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 52910,
"end": 55205
} | class ____(fixtures.TablesTest):
__backend__ = True
__requires__ = ("identity_columns",)
run_inserts = "once"
run_deletes = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"tbl_a",
metadata,
Column(
"id",
Integer,
Identity(
always=True, start=42, nominvalue=True, nomaxvalue=True
),
primary_key=True,
),
Column("desc", String(100)),
)
Table(
"tbl_b",
metadata,
Column(
"id",
Integer,
Identity(increment=-5, start=0, minvalue=-1000, maxvalue=0),
primary_key=True,
),
Column("desc", String(100)),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables.tbl_a.insert(),
[{"desc": "a"}, {"desc": "b"}],
)
connection.execute(
cls.tables.tbl_b.insert(),
[{"desc": "a"}, {"desc": "b"}],
)
connection.execute(
cls.tables.tbl_b.insert(),
[{"id": 42, "desc": "c"}],
)
def test_select_all(self, connection):
res = connection.execute(
select(text("*"))
.select_from(self.tables.tbl_a)
.order_by(self.tables.tbl_a.c.id)
).fetchall()
eq_(res, [(42, "a"), (43, "b")])
res = connection.execute(
select(text("*"))
.select_from(self.tables.tbl_b)
.order_by(self.tables.tbl_b.c.id)
).fetchall()
eq_(res, [(-5, "b"), (0, "a"), (42, "c")])
def test_select_columns(self, connection):
res = connection.execute(
select(self.tables.tbl_a.c.id).order_by(self.tables.tbl_a.c.id)
).fetchall()
eq_(res, [(42,), (43,)])
@testing.requires.identity_columns_standard
def test_insert_always_error(self, connection):
def fn():
connection.execute(
self.tables.tbl_a.insert(),
[{"id": 200, "desc": "a"}],
)
assert_raises((DatabaseError, ProgrammingError), fn)
| IdentityColumnTest |
python | PyCQA__pylint | pylint/testutils/pyreverse.py | {
"start": 638,
"end": 2646
} | class ____(
argparse.Namespace
): # pylint: disable=too-many-instance-attributes, too-many-arguments
"""Holds the configuration options for Pyreverse.
The default values correspond to the defaults of the options' parser.
"""
# pylint: disable=too-many-locals
def __init__(
self,
*,
mode: str = "PUB_ONLY",
classes: list[str] | None = None,
show_ancestors: int | None = None,
all_ancestors: bool | None = None,
show_associated: int | None = None,
all_associated: bool | None = None,
no_standalone: bool = False,
show_builtin: bool = False,
show_stdlib: bool = False,
module_names: bool | None = None,
only_classnames: bool = False,
output_format: str = "dot",
colorized: bool = False,
max_color_depth: int = 2,
max_depth: int | None = None,
color_palette: tuple[str, ...] = DEFAULT_COLOR_PALETTE,
ignore_list: tuple[str, ...] = tuple(),
project: str = "",
output_directory: str = "",
) -> None:
super().__init__()
self.mode = mode
if classes:
self.classes = classes
else:
self.classes = []
self.show_ancestors = show_ancestors
self.all_ancestors = all_ancestors
self.show_associated = show_associated
self.all_associated = all_associated
self.no_standalone = no_standalone
self.show_builtin = show_builtin
self.show_stdlib = show_stdlib
self.module_names = module_names
self.only_classnames = only_classnames
self.output_format = output_format
self.colorized = colorized
self.max_depth = max_depth
self.max_color_depth = max_color_depth
self.color_palette = color_palette
self.ignore_list = ignore_list
self.project = project
self.output_directory = output_directory
# pylint: enable=too-many-locals
| PyreverseConfig |
python | pytorch__pytorch | torch/_dynamo/resume_execution.py | {
"start": 9996,
"end": 30401
} | class ____:
cache = ExactWeakKeyDictionary()
generated_code_metadata = ExactWeakKeyDictionary()
@classmethod
def lookup(
cls, code: types.CodeType, lineno: int, init_offset: int, *key: Any
) -> types.CodeType:
if code not in cls.cache:
cls.cache[code] = {}
key = tuple(key)
if key not in cls.cache[code]:
cls.cache[code][key] = cls.generate(code, lineno, init_offset, *key)
return cls.cache[code][key]
@classmethod
def generate(
cls,
code: types.CodeType,
lineno: int,
init_offset: int,
resume_offset: int,
setup_fn_target_offsets: tuple[int, ...], # only used in Python 3.11+
nstack: int,
argnames: tuple[str, ...],
argnames_null: tuple[str, ...],
setup_fns: tuple[ReenterWith, ...],
handle_inactive_ctx: bool,
stack_ctx_vars: tuple[tuple[int, tuple[Any, ...]], ...],
argnames_ctx_vars: tuple[tuple[str, tuple[Any, ...]], ...],
null_idxes: tuple[int, ...],
# mainly used to ensure distinct code objects per stack trace,
# which prevents excessive recompilation of inner frames
nested_code_objs: tuple[types.CodeType],
) -> types.CodeType:
assert resume_offset is not None
assert not (
code.co_flags
& (CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR)
)
assert code.co_flags & CO_OPTIMIZED
if code in ContinueExecutionCache.generated_code_metadata:
return cls.generate_based_on_original_code_object(
code,
lineno,
init_offset,
resume_offset,
setup_fn_target_offsets,
nstack,
argnames,
argnames_null,
setup_fns,
handle_inactive_ctx,
stack_ctx_vars,
argnames_ctx_vars,
null_idxes,
nested_code_objs,
)
is_py311_plus = sys.version_info >= (3, 11)
meta = ResumeFunctionMetadata(code)
def update(
instructions: list[Instruction], code_options: dict[str, Any]
) -> None:
meta.instructions = copy.deepcopy(instructions)
args = ["__nested_resume_fns", "__nested_frame_values"]
args += [f"___stack{i}" for i in range(nstack)]
args.extend(v for v in argnames if v not in args)
freevars = tuple(code_options["co_cellvars"] or []) + tuple(
code_options["co_freevars"] or []
)
freevars = tuple(sorted(freevars))
code_options["co_name"] = (
f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_{code_options['co_name']}_at_{lineno}"
)
if is_py311_plus:
qualified_path = code_options["co_qualname"].rsplit(".", maxsplit=1)
if len(qualified_path) == 1:
code_options["co_qualname"] = code_options["co_name"]
else:
assert len(qualified_path) == 2
module_name, co_name = qualified_path
code_options["co_qualname"] = (
f"{module_name}.{TORCH_DYNAMO_RESUME_IN_PREFIX}_{co_name}_at_{lineno}"
)
code_options["co_firstlineno"] = lineno
code_options["co_cellvars"] = ()
code_options["co_freevars"] = freevars
code_options["co_argcount"] = len(args)
code_options["co_posonlyargcount"] = 0
code_options["co_kwonlyargcount"] = 0
code_options["co_varnames"] = tuple(
args
+ [v for v in argnames_null if v not in args]
+ [v for v in code_options["co_varnames"] if v not in args]
+ [IS_TRACING_RESUME_PROLOGUE_VARNAME]
)
code_options["co_flags"] = code_options["co_flags"] & ~(
CO_VARARGS | CO_VARKEYWORDS
)
target = next(i for i in instructions if i.offset == resume_offset)
prefix = []
if is_py311_plus:
if freevars:
prefix.append(
create_instruction("COPY_FREE_VARS", arg=len(freevars))
)
prefix.append(create_instruction("RESUME", arg=0))
# Set is_tracing_resume_prologue to prevent graph breaks.
# This doesn't really do anything at runtime, but dynamo will trace this
# and will know that we're in a resume function prologue.
prefix.extend(
[
create_instruction("LOAD_CONST", argval=True),
create_instruction(
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
),
]
)
cleanup: list[Instruction] = []
hooks = {fn.stack_index: fn for fn in setup_fns}
hook_target_offsets = {
fn.stack_index: setup_fn_target_offsets[i]
for i, fn in enumerate(setup_fns)
}
offset_to_inst = {inst.offset: inst for inst in instructions}
# map old hook targets to new targets generated by the hook
old_hook_target_remap = {}
stack_i = 0
null_i = 0
stack_ctx_vars_d = dict(stack_ctx_vars) # type: ignore[var-annotated,arg-type]
for i in range(nstack + len(null_idxes)):
if null_i < len(null_idxes) and null_idxes[null_i] == i:
prefix.append(create_instruction("PUSH_NULL"))
null_i += 1
else:
prefix.append(
create_instruction("LOAD_FAST", argval=f"___stack{stack_i}")
)
if handle_inactive_ctx and stack_i in stack_ctx_vars_d:
# NOTE: we assume that current stack var is a context manager CLASS!
# Load args for context variable and construct it
prefix.extend(_load_tuple_and_call(stack_ctx_vars_d[stack_i]))
stack_i += 1
if i in hooks:
hook = hooks.pop(i)
hook_insts, exn_target = hook(code_options, cleanup)
prefix.extend(hook_insts)
if is_py311_plus:
hook_target_offset = hook_target_offsets.pop(i)
old_hook_target = offset_to_inst[hook_target_offset]
meta.prefix_block_target_offset_remap.append(hook_target_offset)
old_hook_target_remap[old_hook_target] = exn_target
if is_py311_plus:
# reverse the mapping since targets of later/nested contexts are inserted
# into the mapping later, but show up earlier in the prefix.
meta.prefix_block_target_offset_remap = list(
reversed(meta.prefix_block_target_offset_remap)
)
assert not hooks
# NOTE: we assume that local var is a context manager CLASS!
# initialize inactive context vars in argnames
if handle_inactive_ctx:
for name, vals in argnames_ctx_vars:
prefix.append(create_instruction("LOAD_FAST", argval=name))
prefix.extend(_load_tuple_and_call(vals))
prefix.append(create_instruction("STORE_FAST", argval=name))
# 3.12+: store NULL into variables that were NULL
if argnames_null:
assert sys.version_info >= (3, 12)
for v in argnames_null:
assert v not in args
prefix.extend(
[
create_instruction("PUSH_NULL"),
create_instruction("STORE_FAST", argval=v),
]
)
# Call nested resume function
if nested_code_objs:
prefix.extend(
[
# set up __nested_resume_fns[-1] call
*add_push_null(
[
create_instruction(
"LOAD_FAST", argval="__nested_resume_fns"
),
create_instruction("LOAD_CONST", argval=-1),
create_binary_subscr(),
]
),
# del __nested_resume_fns[-1]
create_instruction("LOAD_FAST", argval="__nested_resume_fns"),
create_instruction("LOAD_CONST", argval=-1),
create_instruction("DELETE_SUBSCR"),
# load [__nested_resume_fns, __nested_frame_values]
create_instruction("LOAD_FAST", argval="__nested_resume_fns"),
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
create_instruction("BUILD_LIST", arg=2),
# load __nested_frame_values[-1]
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
create_instruction("LOAD_CONST", argval=-1),
create_binary_subscr(),
# create [
# __nested_resume_fns,
# __nested_frame_values,
# *__nested_frame_values[-1],
# ]
create_instruction("LIST_EXTEND", arg=1),
# del __nested_frame_values[-1]
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
create_instruction("LOAD_CONST", argval=-1),
create_instruction("DELETE_SUBSCR"),
# delete __nested values
create_instruction("DELETE_FAST", argval="__nested_resume_fns"),
create_instruction(
"DELETE_FAST", argval="__nested_frame_values"
),
# Set is_tracing_resume_prologue back to allow graph breaks
# in the nested resume
create_instruction("LOAD_CONST", argval=False),
create_instruction(
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
),
# finish the call
*create_call_function_ex(False, False),
]
)
else:
# Set is_tracing_resume_prologue back to allow graph breaks after the jump
prefix.extend(
[
create_instruction("LOAD_CONST", argval=False),
create_instruction(
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
),
]
)
prefix.append(create_jump_absolute(target))
# because the line number table monotonically increases from co_firstlineno
# remove starts_line for any instructions before the graph break instruction
# this will ensure the instructions after the break have the correct line numbers
for inst in instructions:
if inst.offset == target.offset:
break
inst.starts_line = None
if sys.version_info >= (3, 11):
inst.positions = None
if cleanup:
prefix.extend(cleanup)
prefix.extend(cls.unreachable_codes(code_options))
# remap original instructions' exception table entries
if old_hook_target_remap:
# pyrefly: ignore [unbound-name]
assert is_py311_plus
for inst in instructions:
if (
inst.exn_tab_entry
and inst.exn_tab_entry.target in old_hook_target_remap
):
inst.exn_tab_entry.target = old_hook_target_remap[ # type: ignore[assignment]
inst.exn_tab_entry.target
]
# TODO(jansel): add dead code elimination here
instructions[:] = prefix + instructions
new_code, _ = transform_code_object(code, update)
ContinueExecutionCache.generated_code_metadata[new_code] = meta
return new_code
@staticmethod
def unreachable_codes(code_options: dict[str, Any]) -> list[Instruction]:
"""Codegen a `raise None` to make analysis work for unreachable code"""
return [
create_load_const(None),
create_instruction("RAISE_VARARGS", arg=1),
]
@classmethod
def generate_based_on_original_code_object(
cls,
code: types.CodeType,
lineno: int,
init_offset: int,
resume_offset: int,
setup_fn_target_offsets: tuple[int, ...],
*args: Any,
) -> types.CodeType:
"""
This handles the case of generating a resume into code generated
to resume something else. We want to always generate starting
from the original code object so that if control flow paths
converge we only generated 1 resume function (rather than 2^n
resume functions).
"""
meta: ResumeFunctionMetadata = ContinueExecutionCache.generated_code_metadata[
code
]
def find_orig_offset(cur_offset: int) -> int:
orig_offset = -1
def find_orig_offset_transform(
instructions: list[Instruction], code_options: dict[str, Any]
) -> None:
nonlocal orig_offset
(target,) = (i for i in instructions if i.offset == cur_offset)
# match the functions starting at the last instruction as we have added a prefix
new_target_tuple = tuple(
i2
for i1, i2 in zip(
reversed(instructions), reversed(meta.instructions)
)
if i1 is target
)
if not new_target_tuple:
# Instruction with cur_offset in instructions was not found
# in the original code - orig_offset left as -1.
# Caller expected to handle this case.
return
assert len(new_target_tuple) == 1
new_target = new_target_tuple[0]
assert target.opcode == new_target.opcode
assert new_target.offset is not None
orig_offset = new_target.offset
transform_code_object(code, find_orig_offset_transform)
return orig_offset
orig_init_offset = find_orig_offset(init_offset)
# It is fine if the initial instruction is not found in the original code;
# this means we graph broke in the prefix, which only happens with nested graph breaks.
# We should not be running into ambiguous graph break issues here.
orig_resume_offset = find_orig_offset(resume_offset)
assert orig_resume_offset > -1, (
"resume instruction not found in original code - this is a bug."
)
if sys.version_info >= (3, 11):
# setup_fn_target_offsets currently contains the target offset of
# each setup_fn, based on `code`. When we codegen the resume function
# based on the original code object, `meta.code`, the offsets in
# setup_fn_target_offsets must be based on `meta.code` instead.
offset_key = (orig_init_offset, orig_resume_offset)
# NOTE: we key by offset_key since the same resume function may graph
# break in multiple places and we need different block_target_offset_remap's
# for each graph break location. Keying by orig_resume_offset may not be enough
# if 2 graph breaks on different initial offsets resume on the same instruction
# (although this is rare and not tested anywhere).
if offset_key not in meta.block_target_offset_remap:
block_target_offset_remap = meta.block_target_offset_remap[
offset_key
] = {}
def remap_block_offsets(
instructions: list[Instruction], code_options: dict[str, Any]
) -> None:
# NOTE: each prefix block generates exactly one PUSH_EXC_INFO,
# so we can tell which block a prefix PUSH_EXC_INFO belongs to,
# by counting. Then we can use meta.prefix_block_target_offset_remap
# to determine where in the original code the PUSH_EXC_INFO offset
# replaced.
prefix_blocks: list[Instruction] = []
for inst in instructions:
# NOTE meta.prefix_block_target_offset_remap is based off of how we codegen'd
# context managers at the prefix/prologue of the resume function. It is the same for
# every graph break in the same resume function, so we do not need to recompute
# for each graph break (unlike for meta.block_target_offset_remap)
if len(prefix_blocks) == len(
meta.prefix_block_target_offset_remap
):
break
if inst.opname == "PUSH_EXC_INFO":
prefix_blocks.append(inst)
# remap block target offsets for blocks generated in the resume prefix
for inst, o in zip(
prefix_blocks, meta.prefix_block_target_offset_remap
):
block_target_offset_remap[cast(int, inst.offset)] = o
# current bytecode targets are after the prefix PUSH_EXC_INFO's
cur_start_offset = (
cast(int, prefix_blocks[-1].offset) if prefix_blocks else -1
)
# get the remaining block target offsets of the current bytecode
cur_inst_offsets = sorted(
n for n in setup_fn_target_offsets if n > cur_start_offset
)
targets = _filter_iter(
instructions, cur_inst_offsets, lambda inst, o: inst.offset == o
)
# The original code and resume code should have matching suffixes.
# Match the post-prefix block target offsets of the current resume code
# and the original code.
orig_targets = reversed(
_filter_iter(
zip(reversed(instructions), reversed(meta.instructions)),
reversed(targets),
lambda v1, v2: v1[0] is v2,
)
)
for orig, cur in zip(orig_targets, targets):
block_target_offset_remap[cur.offset] = orig[1].offset
transform_code_object(code, remap_block_offsets)
# if offset_key or offset is not in setup_fn_target_offsets, it is an error
# that needs to be fixed
setup_fn_target_offsets = tuple(
meta.block_target_offset_remap[offset_key][n]
for n in setup_fn_target_offsets
)
return ContinueExecutionCache.lookup(
meta.code,
lineno,
orig_init_offset,
orig_resume_offset,
setup_fn_target_offsets,
*args,
)
| ContinueExecutionCache |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolModule4.py | {
"start": 243,
"end": 321
} | class ____(Protocol[X]):
def __call__(self, x: Fn[X]) -> None: ...
| FnHandler |
python | Textualize__textual | src/textual/suggester.py | {
"start": 2903,
"end": 4723
} | class ____(Suggester):
"""Give completion suggestions based on a fixed list of options.
Example:
```py
countries = ["England", "Scotland", "Portugal", "Spain", "France"]
class MyApp(App[None]):
def compose(self) -> ComposeResult:
yield Input(suggester=SuggestFromList(countries, case_sensitive=False))
```
If the user types ++p++ inside the input widget, a completion suggestion
for `"Portugal"` appears.
"""
def __init__(
self, suggestions: Iterable[str], *, case_sensitive: bool = True
) -> None:
"""Creates a suggester based off of a given iterable of possibilities.
Args:
suggestions: Valid suggestions sorted by decreasing priority.
case_sensitive: Whether suggestions are computed in a case sensitive manner
or not. The values provided in the argument `suggestions` represent the
canonical representation of the completions and they will be suggested
with that same casing.
"""
super().__init__(case_sensitive=case_sensitive)
self._suggestions = list(suggestions)
self._for_comparison = (
self._suggestions
if self.case_sensitive
else [suggestion.casefold() for suggestion in self._suggestions]
)
async def get_suggestion(self, value: str) -> str | None:
"""Gets a completion from the given possibilities.
Args:
value: The current value.
Returns:
A valid completion suggestion or `None`.
"""
for idx, suggestion in enumerate(self._for_comparison):
if suggestion.startswith(value):
return self._suggestions[idx]
return None
| SuggestFromList |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/horizontal_shard.py | {
"start": 2748,
"end": 3084
} | class ____(Protocol):
def __call__(
self,
mapper: Mapper[_T],
primary_key: _PKIdentityArgument,
*,
lazy_loaded_from: Optional[InstanceState[Any]],
execution_options: OrmExecuteOptionsParameter,
bind_arguments: _BindArguments,
**kw: Any,
) -> Any: ...
| IdentityChooser |
python | getsentry__sentry | src/sentry/buffer/redis.py | {
"start": 4798,
"end": 6972
} | class ____:
def __init__(self) -> None:
# map of model_key (generated from _get_model_key function) to queue name
self._routers: dict[str, ChooseQueueFunction] = dict()
def assign_queue(self, model: type[models.Model], generate_queue: ChooseQueueFunction) -> None:
"""
RedisBuffer is shared among multiple models.
Thus, the process_incr task and the default assigned queue for it is shared among multiple models.
If any backlogs or slowdowns occur when incrementing counts for any specific model, other models will be affected.
To alleviate this, we can assign a dedicated queue for any given model.
If a dedicated queue is assigned, the process_incr task will be processed in the assigned queue.
On the other hand, if no dedicated queue is assigned, the process_incr task will be processed in
the default queue (i.e. counters-0 queue).
A queue can be assigned to a model by passing in the generate_queue function.
"""
key = _get_model_key(model=model)
metrics.incr(f"redisbuffer-router.assign_queue.{key}")
self._routers[key] = generate_queue
def create_pending_buffers_router(self, incr_batch_size: int) -> PendingBufferRouter:
"""
We create a PendingBuffer (with buffer size incr_batch_size) for each model with an assigned queue.
In addition, we create a default PendingBuffer (with buffer size incr_batch_size) for models without an
assigned queue. The default PendingBuffer is implicitly assigned to the default queue of the process_incr task.
These PendingBuffers are wrapped in a PendingBufferRouter.
"""
pending_buffers_router = PendingBufferRouter(incr_batch_size=incr_batch_size)
for model_key, generate_queue in self._routers.items():
pending_buffers_router.create_pending_buffer(
model_key=model_key, generate_queue=generate_queue
)
return pending_buffers_router
redis_buffer_router = RedisBufferRouter()
# Note HMSET is not supported after redis 4.0.0, after updating we can use HSET directly.
| RedisBufferRouter |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 96644,
"end": 103476
} | class ____(TritonHOPifier):
def raise_unsupported(self, msg: str) -> Never:
unimplemented(
gb_type="triton kernel unsupported feature",
context="",
explanation=f"Encountered triton kernel unsupported feature: {msg}",
hints=[],
)
def is_callable(self, maybe_callable: VariableTracker) -> bool:
return isinstance(
maybe_callable, (NestedUserFunctionVariable, UserFunctionVariable)
)
def get_value(self, val: VariableTracker) -> Any:
return val.value # type: ignore[attr-defined]
def check_grid(self, grid: "BaseListVariable") -> tuple[torch.fx.proxy.Proxy, ...]:
from .lists import BaseListVariable
if isinstance(grid, BaseListVariable):
return grid.as_proxy()
else:
unimplemented(
gb_type="unsupported grid type for triton hop check_grid",
context=f"grid type = {type(grid)}",
explanation="`torch.compile` only supports list-like grid for check_grid",
hints=[
*graph_break_hints.SUPPORTABLE,
],
)
def call_grid(
self, grid: Any, meta: dict[str, Any], tx: "InstructionTranslator"
) -> Any:
meta_var = {variables.ConstantVariable.create(k): v for k, v in meta.items()}
grid = grid.call_function(tx, [meta_var], {})
return grid
# We use this function to wrap call_prune_configs
def call_user_defined_fn(
self,
user_fn: Callable[..., Any],
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
tx: Optional["InstructionTranslator"],
variable: Any,
) -> VariableTracker:
from .builder import SourcelessBuilder
wrapped_user_function = SourcelessBuilder.create(tx, user_fn) # type: ignore[arg-type]
result = wrapped_user_function.call_function(tx, args, kwargs)
return result
def wrap_user_defined_obj(
self,
user_obj: Any,
tx: Optional["InstructionTranslator"],
variable: Any,
name: str,
) -> VariableTracker:
from .builder import VariableBuilder
wrapped_user_obj = VariableBuilder(
tx, AttrSource(variable.kernel_source, f"{name}")
)._wrap(user_obj)
return wrapped_user_obj
def maybe_unpack_configs(
self, configs: Any, tx: Optional["InstructionTranslator"]
) -> list[Any]:
# unpack the list of configs
configs = configs.unpack_var_sequence(tx)
# guard_as_python_constant inserts guards for Dynamo to check if the configs object changed.
configs = [config.guard_as_python_constant() for config in configs]
return configs
def maybe_unpack_heuristic_result(self, result: VariableTracker) -> Any:
if not result.is_python_constant():
self.raise_unsupported(
"@triton.heuristics must return constant values because configs can only contain constant values."
)
return result.guard_as_python_constant()
# We need to override call_getitem here so that we can add the source in the case
# where we call the triton kernel with a grid
def call_getitem( # type: ignore[override]
self,
variable: "TritonKernelVariable",
args: Sequence[Any],
) -> "TritonKernelVariable":
# __getitem__ should only be called if we don't already have a grid
# Only grid needs to be passed
if variable.grid is not None or len(args) != 1:
self.raise_unsupported(
"Triton kernels should be called with only a single grid"
)
return type(variable)(
kernel=variable.kernel,
kernel_idx=variable.kernel_idx,
grid=args[0],
kernel_source=variable.source,
)
def call_HOP(
self,
variable: "TritonKernelVariable",
grids: Any,
combined_args_raw: dict[str, Any],
tx: "InstructionTranslator",
) -> "variables.ConstantVariable":
from .constant import ConstantVariable
from .dicts import ConstDictVariable
# as we can only pass tensors as non-const args in fx graph,
# here we replace TMA descriptors
# (TMADescriptorExperimentalVariable and TMADescriptorStableVariable
# instances) with the underlying tensors, while moving the
# TMA descriptor-related metadata to a separate argument,
# so that we can reconstruct the TMA descriptors downstream
tma_descriptor_metadata: TMADescriptorMetadata = {}
for k in list(combined_args_raw.keys()):
v = combined_args_raw[k]
if isinstance(
v, (TMADescriptorExperimentalVariable, TMADescriptorStableVariable)
):
tma_descriptor_metadata[k] = v.to_metadata()
combined_args_raw[k] = v.get_tensor()
combined_args = {
variables.ConstantVariable.create(k): v
for k, v in combined_args_raw.items()
}
from torch._higher_order_ops.triton_kernel_wrap import (
kernel_side_table,
triton_kernel_wrapper_mutation,
)
# Combine args and kwargs and pass as a dict so that if user defined triton
# kernel uses variables as 'grid' or 'kernel', it does not conflict with
# parameters of the wrapper function
constant_args = {
k: v.as_python_constant()
for k, v in combined_args_raw.items()
if isinstance(v, ConstantVariable)
}
non_constant_args = {
k: v
for k, v in combined_args.items()
if not isinstance(v, ConstantVariable)
}
for v in non_constant_args.values():
v = v.realize()
if not isinstance(v, (variables.TensorVariable, variables.SymNodeVariable)):
self.raise_unsupported(
f"Unexpected argument type for a Triton kernel: {repr(v)}."
)
constant_args_idx = kernel_side_table.add_constant_args(constant_args)
meta = ConstDictVariable(non_constant_args, dict)
tx.output.create_proxy(
"call_function",
triton_kernel_wrapper_mutation,
(),
{
"kernel_idx": variable.kernel_idx,
"constant_args_idx": constant_args_idx,
"grid": grids,
"tma_descriptor_metadata": tma_descriptor_metadata,
"kwargs": meta.as_proxy(),
},
)
return variables.ConstantVariable(
None,
)
dynamo_triton_hopifier_singleton = DynamoTritonHOPifier()
| DynamoTritonHOPifier |
python | realpython__materials | django-flashcards-app/source_code_final/cards/apps.py | {
"start": 36,
"end": 142
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "cards"
| CardsConfig |
python | astropy__astropy | astropy/utils/state.py | {
"start": 731,
"end": 2127
} | class ____:
"""
Science state subclasses are used to manage global items that can
affect science results. Subclasses will generally override
`validate` to convert from any of the acceptable inputs (such as
strings) to the appropriate internal objects, and set an initial
value to the ``_value`` member so it has a default.
Examples
--------
::
class MyState(ScienceState):
@classmethod
def validate(cls, value):
if value not in ('A', 'B', 'C'):
raise ValueError("Must be one of A, B, C")
return value
"""
def __init__(self):
raise RuntimeError("This class is a singleton. Do not instantiate.")
@classmethod
def get(cls):
"""
Get the current science state value.
"""
return cls.validate(cls._value)
@classmethod
def set(cls, value):
"""Set the current science state value."""
# Create context with current value
ctx = _ScienceStateContext(cls, cls._value)
# Set new value
value = cls.validate(value)
cls._value = value
# Return context manager
return ctx
@classmethod
def validate(cls, value):
"""
Validate the value and convert it to its native type, if
necessary.
"""
return value
| ScienceState |
python | huggingface__transformers | tests/models/rt_detr_v2/test_modeling_rt_detr_v2.py | {
"start": 1544,
"end": 9843
} | class ____:
def __init__(
self,
parent,
batch_size=3,
is_training=True,
use_labels=True,
n_targets=3,
num_labels=10,
initializer_range=0.02,
layer_norm_eps=1e-5,
batch_norm_eps=1e-5,
# backbone
backbone_config=None,
# encoder HybridEncoder
encoder_hidden_dim=32,
encoder_in_channels=[128, 256, 512],
feat_strides=[8, 16, 32],
encoder_layers=1,
encoder_ffn_dim=64,
encoder_attention_heads=2,
dropout=0.0,
activation_dropout=0.0,
encode_proj_layers=[2],
positional_encoding_temperature=10000,
encoder_activation_function="gelu",
activation_function="silu",
eval_size=None,
normalize_before=False,
# decoder RTDetrV2Transformer
d_model=32,
num_queries=30,
decoder_in_channels=[32, 32, 32],
decoder_ffn_dim=64,
num_feature_levels=3,
decoder_n_points=4,
decoder_n_levels=3,
decoder_layers=2,
decoder_attention_heads=2,
decoder_activation_function="relu",
attention_dropout=0.0,
num_denoising=0,
label_noise_ratio=0.5,
box_noise_scale=1.0,
learn_initial_query=False,
anchor_image_size=None,
image_size=64,
disable_custom_kernels=True,
with_box_refine=True,
):
self.parent = parent
self.batch_size = batch_size
self.num_channels = 3
self.is_training = is_training
self.use_labels = use_labels
self.n_targets = n_targets
self.num_labels = num_labels
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.batch_norm_eps = batch_norm_eps
self.backbone_config = backbone_config
self.encoder_hidden_dim = encoder_hidden_dim
self.encoder_in_channels = encoder_in_channels
self.feat_strides = feat_strides
self.encoder_layers = encoder_layers
self.encoder_ffn_dim = encoder_ffn_dim
self.encoder_attention_heads = encoder_attention_heads
self.dropout = dropout
self.activation_dropout = activation_dropout
self.encode_proj_layers = encode_proj_layers
self.positional_encoding_temperature = positional_encoding_temperature
self.encoder_activation_function = encoder_activation_function
self.activation_function = activation_function
self.eval_size = eval_size
self.normalize_before = normalize_before
self.d_model = d_model
self.num_queries = num_queries
self.decoder_in_channels = decoder_in_channels
self.decoder_ffn_dim = decoder_ffn_dim
self.num_feature_levels = num_feature_levels
self.decoder_n_points = decoder_n_points
self.decoder_n_levels = decoder_n_levels
self.decoder_layers = decoder_layers
self.decoder_attention_heads = decoder_attention_heads
self.decoder_activation_function = decoder_activation_function
self.attention_dropout = attention_dropout
self.num_denoising = num_denoising
self.label_noise_ratio = label_noise_ratio
self.box_noise_scale = box_noise_scale
self.learn_initial_query = learn_initial_query
self.anchor_image_size = anchor_image_size
self.image_size = image_size
self.disable_custom_kernels = disable_custom_kernels
self.with_box_refine = with_box_refine
self.encoder_seq_length = math.ceil(self.image_size / 32) * math.ceil(self.image_size / 32)
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
pixel_mask = torch.ones([self.batch_size, self.image_size, self.image_size], device=torch_device)
labels = None
if self.use_labels:
# labels is a list of Dict (each Dict being the labels for a given example in the batch)
labels = []
for i in range(self.batch_size):
target = {}
target["class_labels"] = torch.randint(
high=self.num_labels, size=(self.n_targets,), device=torch_device
)
target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device)
labels.append(target)
config = self.get_config()
config.num_labels = self.num_labels
return config, pixel_values, pixel_mask, labels
def get_config(self):
hidden_sizes = [10, 20, 30, 40]
backbone_config = RTDetrResNetConfig(
embeddings_size=10,
hidden_sizes=hidden_sizes,
depths=[1, 1, 2, 1],
out_features=["stage2", "stage3", "stage4"],
out_indices=[2, 3, 4],
)
return RTDetrV2Config(
backbone_config=backbone_config,
encoder_hidden_dim=self.encoder_hidden_dim,
encoder_in_channels=hidden_sizes[1:],
feat_strides=self.feat_strides,
encoder_layers=self.encoder_layers,
encoder_ffn_dim=self.encoder_ffn_dim,
encoder_attention_heads=self.encoder_attention_heads,
dropout=self.dropout,
activation_dropout=self.activation_dropout,
encode_proj_layers=self.encode_proj_layers,
positional_encoding_temperature=self.positional_encoding_temperature,
encoder_activation_function=self.encoder_activation_function,
activation_function=self.activation_function,
eval_size=self.eval_size,
normalize_before=self.normalize_before,
d_model=self.d_model,
num_queries=self.num_queries,
decoder_in_channels=self.decoder_in_channels,
decoder_ffn_dim=self.decoder_ffn_dim,
num_feature_levels=self.num_feature_levels,
decoder_n_points=self.decoder_n_points,
decoder_n_levels=self.decoder_n_levels,
decoder_layers=self.decoder_layers,
decoder_attention_heads=self.decoder_attention_heads,
decoder_activation_function=self.decoder_activation_function,
attention_dropout=self.attention_dropout,
num_denoising=self.num_denoising,
label_noise_ratio=self.label_noise_ratio,
box_noise_scale=self.box_noise_scale,
learn_initial_query=self.learn_initial_query,
anchor_image_size=self.anchor_image_size,
image_size=self.image_size,
disable_custom_kernels=self.disable_custom_kernels,
with_box_refine=self.with_box_refine,
)
def prepare_config_and_inputs_for_common(self):
config, pixel_values, pixel_mask, labels = self.prepare_config_and_inputs()
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
def create_and_check_rt_detr_model(self, config, pixel_values, pixel_mask, labels):
model = RTDetrV2Model(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
result = model(pixel_values)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.num_queries, self.d_model))
def create_and_check_rt_detr_object_detection_head_model(self, config, pixel_values, pixel_mask, labels):
model = RTDetrV2ForObjectDetection(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
result = model(pixel_values)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels))
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
self.parent.assertEqual(result.loss.shape, ())
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels))
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
@require_torch
| RTDetrV2ModelTester |
python | spack__spack | lib/spack/spack/phase_callbacks.py | {
"start": 993,
"end": 4698
} | class ____(type):
"""Permit to register arbitrary functions during class definition and run them
later, before or after a given install phase.
Each method decorated with ``run_before`` or ``run_after`` gets temporarily
stored in a global shared state when a class being defined is parsed by the Python
interpreter. At class definition time that temporary storage gets flushed and a list
of callbacks is attached to the class being defined.
"""
def __new__(mcs, name, bases, attr_dict):
for temporary_stage in (_RUN_BEFORE, _RUN_AFTER):
staged_callbacks = temporary_stage.callbacks
# Here we have an adapter from an old-style package. This means there is no
# hierarchy of builders, and every callback that had to be combined between
# *Package and *Builder has been combined already by _PackageAdapterMeta
if name == "Adapter":
continue
# If we are here we have callbacks. To get a complete list, we accumulate all the
# callbacks from base classes, we deduplicate them, then prepend what we have
# registered here.
#
# The order should be:
# 1. Callbacks are registered in order within the same class
# 2. Callbacks defined in derived classes precede those defined in base
# classes
callbacks_from_base = []
for base in bases:
current_callbacks = getattr(base, temporary_stage.attribute_name, None)
if not current_callbacks:
continue
callbacks_from_base.extend(current_callbacks)
callbacks_from_base = list(lang.dedupe(callbacks_from_base))
# Set the callbacks in this class and flush the temporary stage
attr_dict[temporary_stage.attribute_name] = staged_callbacks[:] + callbacks_from_base
del temporary_stage.callbacks[:]
return super(PhaseCallbacksMeta, mcs).__new__(mcs, name, bases, attr_dict)
@staticmethod
def run_after(phase: str, when: Optional[str] = None):
"""Decorator to register a function for running after a given phase.
Example::
@run_after("install", when="@2:")
def install_missing_files(self):
# Do something after the install phase for versions 2.x and above
pass
Args:
phase: phase after which the function must run.
when: condition under which the function is run (if :obj:`None`, it is always run).
"""
def _decorator(fn):
key = (phase, when)
item = (key, fn)
_RUN_AFTER.callbacks.append(item)
return fn
return _decorator
@staticmethod
def run_before(phase: str, when: Optional[str] = None):
"""Decorator to register a function for running before a given phase.
Example::
@run_before("build", when="@2:")
def patch_generated_source_file(pkg):
# Do something before the build phase for versions 2.x and above
pass
Args:
phase: phase before which the function must run.
when: condition under which the function is run (if :obj:`None`, it is always run).
"""
def _decorator(fn):
key = (phase, when)
item = (key, fn)
_RUN_BEFORE.callbacks.append(item)
return fn
return _decorator
# Export these names as standalone to be used in packages
run_after = PhaseCallbacksMeta.run_after
run_before = PhaseCallbacksMeta.run_before
| PhaseCallbacksMeta |
python | sqlalchemy__sqlalchemy | examples/sharding/separate_schema_translates.py | {
"start": 2124,
"end": 2488
} | class ____(Base):
__tablename__ = "weather_locations"
id: Mapped[int] = mapped_column(primary_key=True)
continent: Mapped[str]
city: Mapped[str]
reports: Mapped[list[Report]] = relationship(back_populates="location")
def __init__(self, continent: str, city: str):
self.continent = continent
self.city = city
| WeatherLocation |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_detector_index.py | {
"start": 5572,
"end": 20462
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"POST": ApiPublishStatus.EXPERIMENTAL,
"PUT": ApiPublishStatus.EXPERIMENTAL,
"DELETE": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
permission_classes = (OrganizationDetectorPermission,)
def filter_detectors(self, request: Request, organization) -> QuerySet[Detector]:
"""
Filter detectors based on the request parameters.
"""
if not request.user.is_authenticated:
return Detector.objects.none()
if raw_idlist := request.GET.getlist("id"):
try:
ids = [int(id) for id in raw_idlist]
# If filtering by IDs, we must search across all accessible projects
projects = self.get_projects(
request,
organization,
include_all_accessible=True,
)
return Detector.objects.filter(
project_id__in=projects,
id__in=ids,
)
except ValueError:
raise ValidationError({"id": ["Invalid ID format"]})
projects = self.get_projects(
request,
organization,
)
queryset: QuerySet[Detector] = Detector.objects.filter(
project_id__in=projects,
)
if raw_query := request.GET.get("query"):
for filter in parse_detector_query(raw_query):
assert isinstance(filter, SearchFilter)
match filter:
case SearchFilter(key=SearchKey("name"), operator=("=" | "IN" | "!=")):
queryset = apply_filter(queryset, filter, "name")
case SearchFilter(key=SearchKey("type"), operator=("=" | "IN" | "!=")):
values = (
filter.value.value
if isinstance(filter.value.value, list)
else [filter.value.value]
)
values = [DETECTOR_TYPE_ALIASES.get(value, value) for value in values]
if filter.operator == "!=":
queryset = queryset.exclude(type__in=values)
else:
queryset = queryset.filter(type__in=values)
case SearchFilter(key=SearchKey("assignee"), operator=("=" | "IN" | "!=")):
# Filter values can be emails, team slugs, "me", "my_teams", "none"
values = (
filter.value.value
if isinstance(filter.value.value, list)
else [filter.value.value]
)
assignee_q = convert_assignee_values(values, projects, request.user)
if filter.operator == "!=":
queryset = queryset.exclude(assignee_q)
else:
queryset = queryset.filter(assignee_q)
case SearchFilter(key=SearchKey("query"), operator="="):
# 'query' is our free text key; all free text gets returned here
# as '=', and we search any relevant fields for it.
queryset = queryset.filter(
Q(description__icontains=filter.value.value)
| Q(name__icontains=filter.value.value)
| Q(type__icontains=filter.value.value)
).distinct()
return queryset
@extend_schema(
operation_id="Fetch a Project's Detectors",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OrganizationParams.PROJECT,
DetectorParams.QUERY,
DetectorParams.SORT,
DetectorParams.ID,
],
responses={
201: DetectorSerializer,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(self, request: Request, organization: Organization) -> Response:
"""
List an Organization's Detectors
`````````````````````````````
Return a list of detectors for a given organization.
"""
if not request.user.is_authenticated:
return self.respond(status=status.HTTP_401_UNAUTHORIZED)
queryset = self.filter_detectors(request, organization)
sort_by = request.GET.get("sortBy", "id")
sort_by_field = sort_by.lstrip("-")
if sort_by not in SORT_MAP:
raise ValidationError({"sortBy": ["Invalid sort field"]})
if sort_by_field == "connectedWorkflows":
queryset = queryset.annotate(connected_workflows=Count("detectorworkflow"))
elif sort_by_field == "latestGroup":
latest_detector_group_subquery = (
DetectorGroup.objects.filter(detector=OuterRef("pk"))
.order_by("-date_added")
.values("date_added")[:1]
)
queryset = queryset.annotate(
latest_group_date_added=Subquery(latest_detector_group_subquery)
)
elif sort_by_field == "openIssues":
queryset = queryset.annotate(
open_issues_count=Count(
"detectorgroup__group",
filter=Q(detectorgroup__group__status=GroupStatus.UNRESOLVED),
)
)
order_by_field = [SORT_MAP[sort_by]]
return self.paginate(
request=request,
paginator_cls=OffsetPaginator,
queryset=queryset,
order_by=order_by_field,
on_results=lambda x: serialize(x, request.user),
count_hits=True,
)
@extend_schema(
operation_id="Create a Detector",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
],
request=PolymorphicProxySerializer(
"GenericDetectorSerializer",
serializers=[
gt.detector_settings.validator
for gt in grouptype.registry.all()
if gt.detector_settings and gt.detector_settings.validator
],
resource_type_field_name=None,
),
responses={
201: DetectorSerializer,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def post(self, request: Request, organization: Organization) -> Response:
"""
Create a Detector
````````````````
Create a new detector for a project.
:param string name: The name of the detector
:param string type: The type of detector to create
:param string projectId: The detector project
:param object dataSource: Configuration for the data source
:param array dataConditions: List of conditions to trigger the detector
:param array workflowIds: List of workflow IDs to connect to the detector
"""
detector_type = request.data.get("type")
if not detector_type:
raise ValidationError({"type": ["This field is required."]})
# Restrict creating metric issue detectors by plan type
if detector_type == MetricIssue.slug and not features.has(
"organizations:incidents", organization, actor=request.user
):
raise ResourceDoesNotExist
try:
project_id = request.data.get("projectId")
if not project_id:
raise ValidationError({"projectId": ["This field is required."]})
project = Project.objects.get(id=project_id)
except Project.DoesNotExist:
raise ValidationError({"projectId": ["Project not found"]})
if project.organization.id != organization.id:
raise ValidationError({"projectId": ["Project not found"]})
# TODO: Should be in the validator?
if not request.access.has_project_access(project):
return Response(status=status.HTTP_403_FORBIDDEN)
validator = get_detector_validator(request, project, detector_type)
if not validator.is_valid():
return Response(validator.errors, status=status.HTTP_400_BAD_REQUEST)
with transaction.atomic(router.db_for_write(Detector)):
detector = validator.save()
# Handle workflow connections in bulk
workflow_ids = request.data.get("workflowIds", [])
if workflow_ids:
bulk_validator = BulkDetectorWorkflowsValidator(
data={
"detector_id": detector.id,
"workflow_ids": workflow_ids,
},
context={
"organization": organization,
"request": request,
},
)
if not bulk_validator.is_valid():
raise ValidationError({"workflowIds": bulk_validator.errors})
bulk_validator.save()
return Response(serialize(detector, request.user), status=status.HTTP_201_CREATED)
@extend_schema(
operation_id="Mutate an Organization's Detectors",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OrganizationParams.PROJECT,
DetectorParams.QUERY,
DetectorParams.SORT,
DetectorParams.ID,
],
responses={
200: RESPONSE_SUCCESS,
201: DetectorSerializer,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def put(self, request: Request, organization: Organization) -> Response:
"""
Mutate an Organization's Detectors
"""
if not request.user.is_authenticated:
return self.respond(status=status.HTTP_401_UNAUTHORIZED)
if not (
request.GET.getlist("id")
or request.GET.get("query")
or request.GET.getlist("project")
or request.GET.getlist("projectSlug")
):
return Response(
{
"detail": "At least one of 'id', 'query', 'project', or 'projectSlug' must be provided."
},
status=status.HTTP_400_BAD_REQUEST,
)
validator = DetectorWorkflowMutationValidator(data=request.data)
validator.is_valid(raise_exception=True)
enabled = validator.validated_data.get("enabled", True)
queryset = self.filter_detectors(request, organization)
# If explicitly filtering by IDs and some were not found, return 400
if request.GET.getlist("id") and len(queryset) != len(set(request.GET.getlist("id"))):
return Response(
{
"detail": "Some detectors were not found or you do not have permission to update them."
},
status=status.HTTP_400_BAD_REQUEST,
)
if not queryset:
return Response(
{"detail": "No detectors found."},
status=status.HTTP_200_OK,
)
# Check if the user has edit permissions for all detectors
if not can_edit_detectors(queryset, request):
raise PermissionDenied
# We update detectors individually to ensure post_save signals are called
with transaction.atomic(router.db_for_write(Detector)):
for detector in queryset:
detector.update(enabled=enabled)
return self.paginate(
request=request,
queryset=queryset,
paginator_cls=OffsetPaginator,
on_results=lambda x: serialize(x, request.user),
order_by=["id"],
)
@extend_schema(
operation_id="Delete an Organization's Detectors",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OrganizationParams.PROJECT,
DetectorParams.QUERY,
DetectorParams.SORT,
DetectorParams.ID,
],
responses={
200: RESPONSE_SUCCESS,
204: RESPONSE_NO_CONTENT,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def delete(self, request: Request, organization: Organization) -> Response:
"""
Delete an Organization's Detectors
"""
if not request.user.is_authenticated:
return self.respond(status=status.HTTP_401_UNAUTHORIZED)
if not (
request.GET.getlist("id")
or request.GET.get("query")
or request.GET.getlist("project")
or request.GET.getlist("projectSlug")
):
return Response(
{
"detail": "At least one of 'id', 'query', 'project', or 'projectSlug' must be provided."
},
status=status.HTTP_400_BAD_REQUEST,
)
queryset = self.filter_detectors(request, organization)
# If explicitly filtering by IDs and some were not found, return 400
if request.GET.getlist("id") and len(queryset) != len(set(request.GET.getlist("id"))):
return Response(
{
"detail": "Some detectors were not found or you do not have permission to delete them."
},
status=status.HTTP_400_BAD_REQUEST,
)
if not queryset:
return Response(
{"detail": "No detectors found."},
status=status.HTTP_200_OK,
)
# Check if the user has edit permissions for all detectors
if not can_delete_detectors(queryset, request):
raise PermissionDenied
for detector in queryset:
with transaction.atomic(router.db_for_write(Detector)):
RegionScheduledDeletion.schedule(detector, days=0, actor=request.user)
create_audit_entry(
request=request,
organization=organization,
target_object=detector.id,
event=audit_log.get_event_id("DETECTOR_REMOVE"),
data=detector.get_audit_log_data(),
)
detector.update(status=ObjectStatus.PENDING_DELETION)
return Response(status=status.HTTP_204_NO_CONTENT)
| OrganizationDetectorIndexEndpoint |
python | joke2k__faker | faker/providers/internet/no_NO/__init__.py | {
"start": 46,
"end": 437
} | class ____(InternetProvider):
tlds = ("com", "com", "com", "net", "org", "no", "no", "no", "no", "no")
replacements = (
("æ", "ae"),
("Æ", "Ae"),
("ø", "oe"),
("Ø", "Oe"),
("å", "aa"),
("Å", "Aa"),
("ä", "ae"),
("Ä", "Ae"),
("ö", "oe"),
("Ö", "Oe"),
("ü", "ue"),
("Ü", "Ue"),
)
| Provider |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/emptyContainers1.py | {
"start": 1332,
"end": 1851
} | class ____:
def method1(self):
self.val1 = []
self.val2 = {}
self.val3 = []
def method2(self):
self.val1 = [3.4]
self.val2 = {"a": 1}
def method3(self):
reveal_type(self.val1, expected_text="list[float]")
reveal_type(self.val2, expected_text="dict[str, int]")
reveal_type(self.val3, expected_text="list[Unknown]")
def method4(self) -> list[int]:
# This should generate an error because of a type mismatch.
return self.val1
| A |
python | doocs__leetcode | solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/Solution.py | {
"start": 692,
"end": 1065
} | class ____:
def __init__(self, n: int, edgeList: List[List[int]]):
self.puf = PersistentUnionFind(n)
edgeList.sort(key=lambda x: x[2])
for u, v, dis in edgeList:
self.puf.union(u, v, dis)
def query(self, p: int, q: int, limit: int) -> bool:
return self.puf.find(p, limit) == self.puf.find(q, limit)
| DistanceLimitedPathsExist |
python | scipy__scipy | scipy/optimize/_shgo_lib/_vertex.py | {
"start": 6236,
"end": 7009
} | class ____(VertexCacheBase):
def __init__(self):
"""
Class for a vertex cache for a simplicial complex without an associated
field. Useful only for building and visualising a domain complex.
Parameters
----------
"""
super().__init__()
self.Vertex = VertexCube
def __getitem__(self, x, nn=None):
try:
return self.cache[x]
except KeyError:
self.index += 1
xval = self.Vertex(x, index=self.index)
# logging.info("New generated vertex at x = {}".format(x))
# NOTE: Surprisingly high performance increase if logging
# is commented out
self.cache[x] = xval
return self.cache[x]
| VertexCacheIndex |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 28703,
"end": 34538
} | class ____(ViltPreTrainedModel):
_tied_weights_keys = {
"mlm_score.decoder.weight": "vilt.embeddings.text_embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
self.vilt = ViltModel(config)
self.mlm_score = ViltMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.mlm_score.decoder
def set_output_embeddings(self, new_embeddings):
self.mlm_score.decoder = new_embeddings
self.mlm_score.bias = new_embeddings.bias
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
pixel_mask: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
image_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[MaskedLMOutput, tuple[torch.FloatTensor]]:
r"""
image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
labels (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
Labels for computing the masked language modeling loss. Indices should be in *[-100, 0, ...,
config.vocab_size]* (see *input_ids* docstring) Tokens with indices set to *-100* are ignored (masked), the
loss is only computed for the tokens with labels in *[0, ..., config.vocab_size]*
Examples:
```python
>>> from transformers import ViltProcessor, ViltForMaskedLM
>>> import requests
>>> from PIL import Image
>>> import re
>>> import torch
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "a bunch of [MASK] laying on a [MASK]."
>>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-mlm")
>>> model = ViltForMaskedLM.from_pretrained("dandelin/vilt-b32-mlm")
>>> # prepare inputs
>>> encoding = processor(image, text, return_tensors="pt")
>>> # forward pass
>>> outputs = model(**encoding)
>>> tl = len(re.findall("\[MASK\]", text))
>>> inferred_token = [text]
>>> # gradually fill in the MASK tokens, one by one
>>> with torch.no_grad():
... for i in range(tl):
... encoded = processor.tokenizer(inferred_token)
... input_ids = torch.tensor(encoded.input_ids)
... encoded = encoded["input_ids"][0][1:-1]
... outputs = model(input_ids=input_ids, pixel_values=encoding.pixel_values)
... mlm_logits = outputs.logits[0] # shape (seq_len, vocab_size)
... # only take into account text features (minus CLS and SEP token)
... mlm_logits = mlm_logits[1 : input_ids.shape[1] - 1, :]
... mlm_values, mlm_ids = mlm_logits.softmax(dim=-1).max(dim=-1)
... # only take into account text
... mlm_values[torch.tensor(encoded) != 103] = 0
... select = mlm_values.argmax().item()
... encoded[select] = mlm_ids[select].item()
... inferred_token = [processor.decode(encoded)]
>>> selected_token = ""
>>> encoded = processor.tokenizer(inferred_token)
>>> output = processor.decode(encoded.input_ids[0], skip_special_tokens=True)
>>> print(output)
a bunch of cats laying on a couch.
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.vilt(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
pixel_values=pixel_values,
pixel_mask=pixel_mask,
inputs_embeds=inputs_embeds,
image_embeds=image_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output, pooled_output = outputs[:2]
# split up final hidden states into text and image features
text_seq_len = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
text_features, _ = (sequence_output[:, :text_seq_len], sequence_output[:, text_seq_len:])
mlm_logits = self.mlm_score(text_features)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
# move labels to correct device to enable PP
labels = labels.to(mlm_logits.device)
masked_lm_loss = loss_fct(mlm_logits.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (mlm_logits,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=mlm_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| ViltForMaskedLM |
python | python-markdown__markdown | markdown/util.py | {
"start": 8997,
"end": 13943
} | class ____(Generic[_T]):
"""
A priority sorted registry.
A `Registry` instance provides two public methods to alter the data of the
registry: `register` and `deregister`. Use `register` to add items and
`deregister` to remove items. See each method for specifics.
When registering an item, a "name" and a "priority" must be provided. All
items are automatically sorted by "priority" from highest to lowest. The
"name" is used to remove ("deregister") and get items.
A `Registry` instance it like a list (which maintains order) when reading
data. You may iterate over the items, get an item and get a count (length)
of all items. You may also check that the registry contains an item.
When getting an item you may use either the index of the item or the
string-based "name". For example:
registry = Registry()
registry.register(SomeItem(), 'itemname', 20)
# Get the item by index
item = registry[0]
# Get the item by name
item = registry['itemname']
When checking that the registry contains an item, you may use either the
string-based "name", or a reference to the actual item. For example:
someitem = SomeItem()
registry.register(someitem, 'itemname', 20)
# Contains the name
assert 'itemname' in registry
# Contains the item instance
assert someitem in registry
The method `get_index_for_name` is also available to obtain the index of
an item using that item's assigned "name".
"""
def __init__(self):
self._data: dict[str, _T] = {}
self._priority: list[_PriorityItem] = []
self._is_sorted = False
def __contains__(self, item: str | _T) -> bool:
if isinstance(item, str):
# Check if an item exists by this name.
return item in self._data.keys()
# Check if this instance exists.
return item in self._data.values()
def __iter__(self) -> Iterator[_T]:
self._sort()
return iter([self._data[k] for k, p in self._priority])
@overload
def __getitem__(self, key: str | int) -> _T: # pragma: no cover
...
@overload
def __getitem__(self, key: slice) -> Registry[_T]: # pragma: no cover
...
def __getitem__(self, key: str | int | slice) -> _T | Registry[_T]:
self._sort()
if isinstance(key, slice):
data: Registry[_T] = Registry()
for k, p in self._priority[key]:
data.register(self._data[k], k, p)
return data
if isinstance(key, int):
return self._data[self._priority[key].name]
return self._data[key]
def __len__(self) -> int:
return len(self._priority)
def __repr__(self):
return '<{}({})>'.format(self.__class__.__name__, list(self))
def get_index_for_name(self, name: str) -> int:
"""
Return the index of the given name.
"""
if name in self:
self._sort()
return self._priority.index(
[x for x in self._priority if x.name == name][0]
)
raise ValueError('No item named "{}" exists.'.format(name))
def register(self, item: _T, name: str, priority: float) -> None:
"""
Add an item to the registry with the given name and priority.
Arguments:
item: The item being registered.
name: A string used to reference the item.
priority: An integer or float used to sort against all items.
If an item is registered with a "name" which already exists, the
existing item is replaced with the new item. Treat carefully as the
old item is lost with no way to recover it. The new item will be
sorted according to its priority and will **not** retain the position
of the old item.
"""
if name in self:
# Remove existing item of same name first
self.deregister(name)
self._is_sorted = False
self._data[name] = item
self._priority.append(_PriorityItem(name, priority))
def deregister(self, name: str, strict: bool = True) -> None:
"""
Remove an item from the registry.
Set `strict=False` to fail silently. Otherwise a [`ValueError`][] is raised for an unknown `name`.
"""
try:
index = self.get_index_for_name(name)
del self._priority[index]
del self._data[name]
except ValueError:
if strict:
raise
def _sort(self) -> None:
"""
Sort the registry by priority from highest to lowest.
This method is called internally and should never be explicitly called.
"""
if not self._is_sorted:
self._priority.sort(key=lambda item: item.priority, reverse=True)
self._is_sorted = True
| Registry |
python | django__django | tests/admin_utils/models.py | {
"start": 940,
"end": 1135
} | class ____(models.Model):
num = models.PositiveSmallIntegerField()
parent = models.ForeignKey("self", models.CASCADE, null=True)
def __str__(self):
return str(self.num)
| Cascade |
python | HIPS__autograd | autograd/builtins.py | {
"start": 1082,
"end": 3270
} | class ____(Box):
__slots__ = []
__getitem__ = container_take
def __len__(self):
return len(self._value)
def __iter__(self):
return self._value.__iter__()
def __contains__(self, elt):
return elt in self._value
def items(self):
return list(self.iteritems())
def keys(self):
return list(self.iterkeys())
def values(self):
return list(self.itervalues())
def iteritems(self):
return ((k, self[k]) for k in self)
def iterkeys(self):
return iter(self)
def itervalues(self):
return (self[k] for k in self)
def get(self, k, d=None):
return self[k] if k in self else d
DictBox.register(dict_)
@primitive
def container_untake(x, idx, vs):
if isinstance(idx, slice):
accum = lambda result: [elt_vs._mut_add(a, b) for elt_vs, a, b in zip(vs.shape[idx], result, x)]
else:
accum = lambda result: vs.shape[idx]._mut_add(result, x)
def mut_add(A):
return vs._subval(A, idx, accum(A[idx]))
return SparseObject(vs, mut_add)
defvjp(container_untake, lambda ans, x, idx, _: lambda g: container_take(g, idx))
defjvp(container_untake, "same")
@primitive
def sequence_extend_right(seq, *elts):
return seq + type(seq)(elts)
def grad_sequence_extend_right(argnum, ans, args, kwargs):
seq, elts = args[0], args[1:]
return lambda g: g[: len(seq)] if argnum == 0 else g[len(seq) + argnum - 1]
defvjp_argnum(sequence_extend_right, grad_sequence_extend_right)
@primitive
def sequence_extend_left(seq, *elts):
return type(seq)(elts) + seq
def grad_sequence_extend_left(argnum, ans, args, kwargs):
seq, elts = args[0], args[1:]
return lambda g: g[len(elts) :] if argnum == 0 else g[argnum - 1]
defvjp_argnum(sequence_extend_left, grad_sequence_extend_left)
@primitive
def make_sequence(seq_type, *args):
return seq_type(args)
defvjp_argnum(make_sequence, lambda argnum, *args: lambda g: g[argnum - 1])
def fwd_grad_make_sequence(argnum, g, ans, seq_type, *args, **kwargs):
return container_untake(g, argnum - 1, vspace(ans))
defjvp_argnum(make_sequence, fwd_grad_make_sequence)
| DictBox |
python | huggingface__transformers | tests/utils/import_structures/import_structure_register_with_comments.py | {
"start": 1230,
"end": 1370
} | class ____:
def __init__(self):
pass
@requires(
backends=(
"torch",
)
)
# That's a statement
def b3():
pass
| B3 |
python | sqlalchemy__sqlalchemy | test/engine/test_reconnect.py | {
"start": 44174,
"end": 45674
} | class ____(fixtures.TestBase):
__backend__ = True
def setup_test(self):
self.engine = engines.reconnecting_engine()
self.meta = MetaData()
table = Table(
"sometable",
self.meta,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
)
with self.engine.begin() as conn:
self.meta.create_all(conn)
conn.execute(
table.insert(),
[{"id": i, "name": "row %d" % i} for i in range(1, 100)],
)
def teardown_test(self):
with self.engine.begin() as conn:
self.meta.drop_all(conn)
self.engine.dispose()
def test_invalidate_on_results(self):
conn = self.engine.connect()
result = conn.exec_driver_sql(
"select * from sometable",
)
for x in range(20):
result.fetchone()
real_cursor = result.cursor
self.engine.test_shutdown()
def produce_side_effect():
# will fail because connection was closed, with an exception
# that should trigger disconnect routines
real_cursor.execute("select * from sometable")
result.cursor = Mock(
fetchone=mock.Mock(side_effect=produce_side_effect)
)
try:
_assert_invalidated(result.fetchone)
assert conn.invalidated
finally:
conn.invalidate()
| InvalidateDuringResultTest |
python | pypa__warehouse | warehouse/ip_addresses/models.py | {
"start": 442,
"end": 2317
} | class ____(db.Model):
__tablename__ = "ip_addresses"
__table_args__ = (
Index("bans_idx", "is_banned"),
CheckConstraint(
"(is_banned AND ban_reason IS NOT NULL AND ban_date IS NOT NULL)"
"OR (NOT is_banned AND ban_reason IS NULL AND ban_date IS NULL)"
),
{"comment": "Tracks IP Addresses that have modified PyPI state"},
)
def __repr__(self) -> str:
return str(self.ip_address)
def __lt__(self, other) -> bool:
return self.id < other.id
ip_address: Mapped[ipaddress.IPv4Address | ipaddress.IPv6Address] = mapped_column(
INET, unique=True, comment="Structured IP Address value"
)
hashed_ip_address: Mapped[str | None] = mapped_column(
unique=True, comment="Hash that represents an IP Address"
)
geoip_info: Mapped[dict | None] = mapped_column(
JSONB,
comment="JSON containing GeoIP data associated with an IP Address",
)
is_banned: Mapped[bool_false] = mapped_column(
comment="If True, this IP Address will be marked as banned",
)
ban_reason: Mapped[BanReason | None] = mapped_column(
comment="Reason for banning, must be in the BanReason enumeration",
)
ban_date: Mapped[datetime | None] = mapped_column(
comment="Date that IP Address was last marked as banned",
)
@validates("ip_address")
def validate_ip_address(self, key, ip_address):
# Check to see if the ip_address is valid
try:
_ = ipaddress.ip_address(ip_address)
except ValueError as e:
sentry_sdk.capture_message(f"Attempted to store invalid ip_address: {e}")
# If not, transform it into an IP in the range reserved for documentation
return "192.0.2.69" # https://datatracker.ietf.org/doc/html/rfc5737
return ip_address
| IpAddress |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 11843,
"end": 12614
} | class ____(AssetEventResponse):
"""Used in AssetEventsResult."""
@classmethod
def from_asset_event_response(cls, asset_event_response: AssetEventResponse) -> AssetEventResult:
return cls(**asset_event_response.model_dump(exclude_defaults=True))
@cached_property
def source_task_instance(self) -> AssetEventSourceTaskInstance | None:
if not (self.source_task_id and self.source_dag_id and self.source_run_id):
return None
if self.source_map_index is None:
return None
return AssetEventSourceTaskInstance(
dag_id=self.source_dag_id,
task_id=self.source_task_id,
run_id=self.source_run_id,
map_index=self.source_map_index,
)
| AssetEventResult |
python | encode__django-rest-framework | rest_framework/exceptions.py | {
"start": 4960,
"end": 5158
} | class ____(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = _('Incorrect authentication credentials.')
default_code = 'authentication_failed'
| AuthenticationFailed |
python | crytic__slither | slither/detectors/statements/mapping_deletion.py | {
"start": 637,
"end": 3837
} | class ____(AbstractDetector):
"""
Mapping deletion detector
"""
ARGUMENT = "mapping-deletion"
HELP = "Deletion on mapping containing a structure"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#deletion-on-mapping-containing-a-structure"
WIKI_TITLE = "Deletion on mapping containing a structure"
WIKI_DESCRIPTION = "A deletion in a structure containing a mapping will not delete the mapping (see the [Solidity documentation](https://solidity.readthedocs.io/en/latest/types.html##delete)). The remaining data may be used to compromise the contract."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
struct BalancesStruct{
address owner;
mapping(address => uint) balances;
}
mapping(address => BalancesStruct) public stackBalance;
function remove() internal{
delete stackBalance[msg.sender];
}
```
`remove` deletes an item of `stackBalance`.
The mapping `balances` is never deleted, so `remove` does not work as intended."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = (
"Use a lock mechanism instead of a deletion to disable structure containing a mapping."
)
@staticmethod
def detect_mapping_deletion(
contract: Contract,
) -> List[Tuple[FunctionContract, Structure, Node]]:
"""Detect deletion on structure containing a mapping
Returns:
list (function, structure, node)
"""
ret: List[Tuple[FunctionContract, Structure, Node]] = []
# pylint: disable=too-many-nested-blocks
for f in contract.functions:
for node in f.nodes:
for ir in node.irs:
if isinstance(ir, Delete):
value = ir.variable
MappingDeletionDetection.check_if_mapping(value, ret, f, node)
return ret
@staticmethod
def check_if_mapping(
value: Variable,
ret: List[Tuple[FunctionContract, Structure, Node]],
f: FunctionContract,
node: Node,
):
if isinstance(value.type, UserDefinedType) and isinstance(value.type.type, Structure):
st = value.type.type
if any(isinstance(e.type, MappingType) for e in st.elems.values()):
ret.append((f, st, node))
return
for e in st.elems.values():
MappingDeletionDetection.check_if_mapping(e, ret, f, node)
def _detect(self) -> List[Output]:
"""Detect mapping deletion
Returns:
list: {'vuln', 'filename,'contract','func','struct''}
"""
results = []
for c in self.contracts:
mapping = MappingDeletionDetection.detect_mapping_deletion(c)
for (func, struct, node) in mapping:
info: DETECTOR_INFO = [func, " deletes ", struct, " which contains a mapping:\n"]
info += ["\t-", node, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| MappingDeletionDetection |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 872653,
"end": 874284
} | class ____(sgqlc.types.Type):
"""Require all commits be made to a non-target branch and submitted
via a pull request before they can be merged.
"""
__schema__ = github_schema
__field_names__ = (
"dismiss_stale_reviews_on_push",
"require_code_owner_review",
"require_last_push_approval",
"required_approving_review_count",
"required_review_thread_resolution",
)
dismiss_stale_reviews_on_push = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="dismissStaleReviewsOnPush")
"""New, reviewable commits pushed will dismiss previous pull request
review approvals.
"""
require_code_owner_review = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requireCodeOwnerReview")
"""Require an approving review in pull requests that modify files
that have a designated code owner.
"""
require_last_push_approval = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requireLastPushApproval")
"""Whether the most recent reviewable push must be approved by
someone other than the person who pushed it.
"""
required_approving_review_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="requiredApprovingReviewCount")
"""The number of approving reviews that are required before a pull
request can be merged.
"""
required_review_thread_resolution = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requiredReviewThreadResolution")
"""All conversations on code must be resolved before a pull request
can be merged.
"""
| PullRequestParameters |
python | scrapy__scrapy | tests/AsyncCrawlerProcess/simple.py | {
"start": 63,
"end": 277
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
process = AsyncCrawlerProcess(settings={})
process.crawl(NoRequestsSpider)
process.start()
| NoRequestsSpider |
python | getsentry__sentry | tests/relay_integration/lang/java/test_plugin.py | {
"start": 31878,
"end": 32401
} | class ____ {
fun helloOther() {
otherFun()
}
private fun otherFun() {
AnotherInnerClass().helloOtherInner()
}
class AnotherInnerClass {
fun helloOtherInner() {
throw RuntimeException("thrown on purpose to test ProGuard Android source context")
}
}
}
"""
@pytest.mark.django_db(transaction=True)
@thread_leak_allowlist(reason="kafka testutils", issue=97046)
@thread_leak_allowlist(reason="sentry sdk background worker", issue=97042)
| AnotherClassInSameFile |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 47363,
"end": 62487
} | class ____(InvokeDropDDLBase):
def __init__(
self,
dialect,
connection,
checkfirst=CheckFirst.NONE,
tables=None,
**kwargs,
):
super().__init__(connection, **kwargs)
self.checkfirst = CheckFirst(checkfirst)
self.tables = tables
self.preparer = dialect.identifier_preparer
self.dialect = dialect
self.memo = {}
def visit_metadata(self, metadata):
if self.tables is not None:
tables = self.tables
else:
tables = list(metadata.tables.values())
try:
unsorted_tables = [t for t in tables if self._can_drop_table(t)]
collection = list(
reversed(
sort_tables_and_constraints(
unsorted_tables,
filter_fn=lambda constraint: (
False
if not self.dialect.supports_alter
or constraint.name is None
else None
),
)
)
)
except exc.CircularDependencyError as err2:
if not self.dialect.supports_alter:
util.warn(
"Can't sort tables for DROP; an "
"unresolvable foreign key "
"dependency exists between tables: %s; and backend does "
"not support ALTER. To restore at least a partial sort, "
"apply use_alter=True to ForeignKey and "
"ForeignKeyConstraint "
"objects involved in the cycle to mark these as known "
"cycles that will be ignored."
% (", ".join(sorted([t.fullname for t in err2.cycles])))
)
collection = [(t, ()) for t in unsorted_tables]
else:
raise exc.CircularDependencyError(
err2.args[0],
err2.cycles,
err2.edges,
msg="Can't sort tables for DROP; an "
"unresolvable foreign key "
"dependency exists between tables: %s. Please ensure "
"that the ForeignKey and ForeignKeyConstraint objects "
"involved in the cycle have "
"names so that they can be dropped using "
"DROP CONSTRAINT."
% (", ".join(sorted([t.fullname for t in err2.cycles]))),
) from err2
seq_coll = [
s
for s in metadata._sequences.values()
if self._can_drop_sequence(s)
]
event_collection = [t for (t, fks) in collection if t is not None]
with self.with_ddl_events(
metadata,
tables=event_collection,
checkfirst=self.checkfirst,
):
for table, fkcs in collection:
if table is not None:
self.traverse_single(
table,
drop_ok=True,
_is_metadata_operation=True,
_ignore_sequences=seq_coll,
)
else:
for fkc in fkcs:
self.traverse_single(fkc)
for seq in seq_coll:
self.traverse_single(seq, drop_ok=seq.column is None)
def _can_drop_table(self, table):
self.dialect.validate_identifier(table.name)
effective_schema = self.connection.schema_for_object(table)
if effective_schema:
self.dialect.validate_identifier(effective_schema)
bool_to_check = (
CheckFirst.TABLES if not table.is_view else CheckFirst.VIEWS
)
return not self.checkfirst & bool_to_check or self.dialect.has_table(
self.connection, table.name, schema=effective_schema
)
def _can_drop_index(self, index):
effective_schema = self.connection.schema_for_object(index.table)
if effective_schema:
self.dialect.validate_identifier(effective_schema)
return (
not self.checkfirst & CheckFirst.INDEXES
or self.dialect.has_index(
self.connection,
index.table.name,
index.name,
schema=effective_schema,
)
)
def _can_drop_sequence(self, sequence):
effective_schema = self.connection.schema_for_object(sequence)
return self.dialect.supports_sequences and (
(not self.dialect.sequences_optional or not sequence.optional)
and (
not self.checkfirst & CheckFirst.SEQUENCES
or self.dialect.has_sequence(
self.connection, sequence.name, schema=effective_schema
)
)
)
def visit_index(self, index, drop_ok=False):
if not drop_ok and not self._can_drop_index(index):
return
with self.with_ddl_events(index):
DropIndex(index)(index, self.connection)
def visit_table(
self,
table,
drop_ok=False,
_is_metadata_operation=False,
_ignore_sequences=(),
):
if not drop_ok and not self._can_drop_table(table):
return
with self.with_ddl_events(
table,
checkfirst=self.checkfirst,
_is_metadata_operation=_is_metadata_operation,
):
if table._dropper_ddl is not None:
table_dropper_ddl = table._dropper_ddl
else:
table_dropper_ddl = DropTable(table)
table_dropper_ddl._invoke_with(self.connection)
# traverse client side defaults which may refer to server-side
# sequences. noting that some of these client side defaults may
# also be set up as server side defaults
# (see https://docs.sqlalchemy.org/en/
# latest/core/defaults.html
# #associating-a-sequence-as-the-server-side-
# default), so have to be dropped after the table is dropped.
for column in table.columns:
if (
column.default is not None
and column.default not in _ignore_sequences
):
self.traverse_single(column.default)
def visit_foreign_key_constraint(self, constraint):
if not self.dialect.supports_alter:
return
with self.with_ddl_events(constraint):
DropConstraint(constraint)._invoke_with(self.connection)
def visit_sequence(self, sequence, drop_ok=False):
if not drop_ok and not self._can_drop_sequence(sequence):
return
with self.with_ddl_events(sequence):
DropSequence(sequence)._invoke_with(self.connection)
def sort_tables(
tables: Iterable[TableClause],
skip_fn: Optional[Callable[[ForeignKeyConstraint], bool]] = None,
extra_dependencies: Optional[
typing_Sequence[Tuple[TableClause, TableClause]]
] = None,
) -> List[Table]:
"""Sort a collection of :class:`_schema.Table` objects based on
dependency.
This is a dependency-ordered sort which will emit :class:`_schema.Table`
objects such that they will follow their dependent :class:`_schema.Table`
objects.
Tables are dependent on another based on the presence of
:class:`_schema.ForeignKeyConstraint`
objects as well as explicit dependencies
added by :meth:`_schema.Table.add_is_dependent_on`.
.. warning::
The :func:`._schema.sort_tables` function cannot by itself
accommodate automatic resolution of dependency cycles between
tables, which are usually caused by mutually dependent foreign key
constraints. When these cycles are detected, the foreign keys
of these tables are omitted from consideration in the sort.
A warning is emitted when this condition occurs, which will be an
exception raise in a future release. Tables which are not part
of the cycle will still be returned in dependency order.
To resolve these cycles, the
:paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
applied to those constraints which create a cycle. Alternatively,
the :func:`_schema.sort_tables_and_constraints` function will
automatically return foreign key constraints in a separate
collection when cycles are detected so that they may be applied
to a schema separately.
:param tables: a sequence of :class:`_schema.Table` objects.
:param skip_fn: optional callable which will be passed a
:class:`_schema.ForeignKeyConstraint` object; if it returns True, this
constraint will not be considered as a dependency. Note this is
**different** from the same parameter in
:func:`.sort_tables_and_constraints`, which is
instead passed the owning :class:`_schema.ForeignKeyConstraint` object.
:param extra_dependencies: a sequence of 2-tuples of tables which will
also be considered as dependent on each other.
.. seealso::
:func:`.sort_tables_and_constraints`
:attr:`_schema.MetaData.sorted_tables` - uses this function to sort
"""
if skip_fn is not None:
fixed_skip_fn = skip_fn
def _skip_fn(fkc):
for fk in fkc.elements:
if fixed_skip_fn(fk):
return True
else:
return None
else:
_skip_fn = None # type: ignore
return [
t
for (t, fkcs) in sort_tables_and_constraints(
tables,
filter_fn=_skip_fn,
extra_dependencies=extra_dependencies,
_warn_for_cycles=True,
)
if t is not None
]
@util.preload_module("sqlalchemy.sql.schema")
def sort_tables_and_constraints(
tables, filter_fn=None, extra_dependencies=None, _warn_for_cycles=False
):
"""Sort a collection of :class:`_schema.Table` /
:class:`_schema.ForeignKeyConstraint`
objects.
This is a dependency-ordered sort which will emit tuples of
``(Table, [ForeignKeyConstraint, ...])`` such that each
:class:`_schema.Table` follows its dependent :class:`_schema.Table`
objects.
Remaining :class:`_schema.ForeignKeyConstraint`
objects that are separate due to
dependency rules not satisfied by the sort are emitted afterwards
as ``(None, [ForeignKeyConstraint ...])``.
Tables are dependent on another based on the presence of
:class:`_schema.ForeignKeyConstraint` objects, explicit dependencies
added by :meth:`_schema.Table.add_is_dependent_on`,
as well as dependencies
stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn`
and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies`
parameters.
:param tables: a sequence of :class:`_schema.Table` objects.
:param filter_fn: optional callable which will be passed a
:class:`_schema.ForeignKeyConstraint` object,
and returns a value based on
whether this constraint should definitely be included or excluded as
an inline constraint, or neither. If it returns False, the constraint
will definitely be included as a dependency that cannot be subject
to ALTER; if True, it will **only** be included as an ALTER result at
the end. Returning None means the constraint is included in the
table-based result unless it is detected as part of a dependency cycle.
:param extra_dependencies: a sequence of 2-tuples of tables which will
also be considered as dependent on each other.
.. seealso::
:func:`.sort_tables`
"""
Table = util.preloaded.sql_schema.Table
fixed_dependencies = set()
mutable_dependencies = set()
if extra_dependencies is not None:
fixed_dependencies.update(extra_dependencies)
remaining_fkcs = set()
for table in tables:
for fkc in table.foreign_key_constraints:
if fkc.use_alter is True:
remaining_fkcs.add(fkc)
continue
if filter_fn:
filtered = filter_fn(fkc)
if filtered is True:
remaining_fkcs.add(fkc)
continue
dependent_on = fkc.referred_table
if dependent_on is not table:
mutable_dependencies.add((dependent_on, table))
if isinstance(table._creator_ddl, _TableViaSelect):
selectable = table._creator_ddl.selectable
for selected_table in sql_util.find_tables(
selectable,
check_columns=True,
include_aliases=True,
include_joins=True,
include_selects=True,
include_crud=True,
):
if (
isinstance(selected_table, Table)
and selected_table.metadata is table.metadata
):
fixed_dependencies.add((selected_table, table))
fixed_dependencies.update(
(parent, table) for parent in table._extra_dependencies
)
try:
candidate_sort = list(
topological.sort(
fixed_dependencies.union(mutable_dependencies),
tables,
)
)
except exc.CircularDependencyError as err:
if _warn_for_cycles:
util.warn(
"Cannot correctly sort tables; there are unresolvable cycles "
'between tables "%s", which is usually caused by mutually '
"dependent foreign key constraints. Foreign key constraints "
"involving these tables will not be considered; this warning "
"may raise an error in a future release."
% (", ".join(sorted(t.fullname for t in err.cycles)),)
)
for edge in err.edges:
if edge in mutable_dependencies:
table = edge[1]
if table not in err.cycles:
continue
can_remove = [
fkc
for fkc in table.foreign_key_constraints
if filter_fn is None or filter_fn(fkc) is not False
]
remaining_fkcs.update(can_remove)
for fkc in can_remove:
dependent_on = fkc.referred_table
if dependent_on is not table:
mutable_dependencies.discard((dependent_on, table))
candidate_sort = list(
topological.sort(
fixed_dependencies.union(mutable_dependencies),
tables,
)
)
return [
(table, table.foreign_key_constraints.difference(remaining_fkcs))
for table in candidate_sort
] + [(None, list(remaining_fkcs))]
| SchemaDropper |
python | tornadoweb__tornado | tornado/test/testing_test.py | {
"start": 2618,
"end": 3608
} | class ____(AsyncHTTPTestCase):
def setUp(self):
super().setUp()
# Bind a second port.
sock, port = bind_unused_port()
app = Application()
server = HTTPServer(app, **self.get_httpserver_options())
server.add_socket(sock)
self.second_port = port
self.second_server = server
def get_app(self):
return Application()
def test_fetch_segment(self):
path = "/path"
response = self.fetch(path)
self.assertEqual(response.request.url, self.get_url(path))
def test_fetch_full_http_url(self):
# Ensure that self.fetch() recognizes absolute urls and does
# not transform them into references to our main test server.
path = "http://127.0.0.1:%d/path" % self.second_port
response = self.fetch(path)
self.assertEqual(response.request.url, path)
def tearDown(self):
self.second_server.stop()
super().tearDown()
| AsyncHTTPTestCaseTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/noreturn1.py | {
"start": 958,
"end": 1411
} | class ____:
def __call__(self) -> NoReturn: ...
def func10() -> NoReturn:
C()()
@overload
def func11() -> NoReturn: ...
@overload
def func11(x: int) -> None: ...
def func11(x: int = 0) -> NoReturn | None: ...
def func12() -> NoReturn:
func11()
def func13() -> NoReturn:
# This should generate an error.
func11(0)
def func14(x: int) -> NoReturn: ...
def func15():
# This should generate an error.
return func14()
| C |
python | graphql-python__graphene | graphene/relay/connection.py | {
"start": 1248,
"end": 2367
} | class ____(ObjectType):
class Meta:
description = (
"The Relay compliant `PageInfo` type, containing data necessary to"
" paginate this connection."
)
has_next_page = Boolean(
required=True,
name="hasNextPage",
description="When paginating forwards, are there more items?",
)
has_previous_page = Boolean(
required=True,
name="hasPreviousPage",
description="When paginating backwards, are there more items?",
)
start_cursor = String(
name="startCursor",
description="When paginating backwards, the cursor to continue.",
)
end_cursor = String(
name="endCursor",
description="When paginating forwards, the cursor to continue.",
)
# noinspection PyPep8Naming
def page_info_adapter(startCursor, endCursor, hasPreviousPage, hasNextPage):
"""Adapter for creating PageInfo instances"""
return PageInfo(
start_cursor=startCursor,
end_cursor=endCursor,
has_previous_page=hasPreviousPage,
has_next_page=hasNextPage,
)
| PageInfo |
python | sympy__sympy | sympy/testing/runtests.py | {
"start": 50843,
"end": 59736
} | class ____:
def __init__(self, reporter, normal):
self._count = 0
self._root_dir = get_sympy_dir()
self._reporter = reporter
self._reporter.root_dir(self._root_dir)
self._normal = normal
self._testfiles = []
def test(self):
"""
Runs the tests and returns True if all tests pass, otherwise False.
"""
self._reporter.start()
for f in self._testfiles:
try:
self.test_file(f)
except KeyboardInterrupt:
print(" interrupted by user")
self._reporter.finish()
raise
return self._reporter.finish()
def test_file(self, filename):
clear_cache()
from io import StringIO
import sympy.interactive.printing as interactive_printing
from sympy.printing.pretty.pretty import pprint_use_unicode
from sympy.printing.pretty import stringpict
rel_name = filename[len(self._root_dir) + 1:]
dirname, file = os.path.split(filename)
module = rel_name.replace(os.sep, '.')[:-3]
if rel_name.startswith("examples"):
# Examples files do not have __init__.py files,
# So we have to temporarily extend sys.path to import them
sys.path.insert(0, dirname)
module = file[:-3] # remove ".py"
try:
module = pdoctest._normalize_module(module)
tests = SymPyDocTestFinder().find(module)
except (SystemExit, KeyboardInterrupt):
raise
except ImportError:
self._reporter.import_error(filename, sys.exc_info())
return
finally:
if rel_name.startswith("examples"):
del sys.path[0]
tests = [test for test in tests if len(test.examples) > 0]
# By default tests are sorted by alphabetical order by function name.
# We sort by line number so one can edit the file sequentially from
# bottom to top. However, if there are decorated functions, their line
# numbers will be too large and for now one must just search for these
# by text and function name.
tests.sort(key=lambda x: -x.lineno)
if not tests:
return
self._reporter.entering_filename(filename, len(tests))
for test in tests:
assert len(test.examples) != 0
if self._reporter._verbose:
self._reporter.write("\n{} ".format(test.name))
# check if there are external dependencies which need to be met
if '_doctest_depends_on' in test.globs:
try:
self._check_dependencies(**test.globs['_doctest_depends_on'])
except DependencyError as e:
self._reporter.test_skip(v=str(e))
continue
runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2,
optionflags=pdoctest.ELLIPSIS |
pdoctest.NORMALIZE_WHITESPACE |
pdoctest.IGNORE_EXCEPTION_DETAIL)
runner._checker = SymPyOutputChecker()
old = sys.stdout
new = old if self._reporter._verbose==2 else StringIO()
sys.stdout = new
# If the testing is normal, the doctests get importing magic to
# provide the global namespace. If not normal (the default) then
# then must run on their own; all imports must be explicit within
# a function's docstring. Once imported that import will be
# available to the rest of the tests in a given function's
# docstring (unless clear_globs=True below).
if not self._normal:
test.globs = {}
# if this is uncommented then all the test would get is what
# comes by default with a "from sympy import *"
#exec('from sympy import *') in test.globs
old_displayhook = sys.displayhook
use_unicode_prev, wrap_line_prev = setup_pprint()
try:
f, t = runner.run(test,
out=new.write, clear_globs=False)
except KeyboardInterrupt:
raise
finally:
sys.stdout = old
if f > 0:
self._reporter.doctest_fail(test.name, new.getvalue())
else:
self._reporter.test_pass()
sys.displayhook = old_displayhook
interactive_printing.NO_GLOBAL = False
pprint_use_unicode(use_unicode_prev)
stringpict._GLOBAL_WRAP_LINE = wrap_line_prev
self._reporter.leaving_filename()
def get_test_files(self, dir, pat='*.py', init_only=True):
r"""
Returns the list of \*.py files (default) from which docstrings
will be tested which are at or below directory ``dir``. By default,
only those that have an __init__.py in their parent directory
and do not start with ``test_`` will be included.
"""
def importable(x):
"""
Checks if given pathname x is an importable module by checking for
__init__.py file.
Returns True/False.
Currently we only test if the __init__.py file exists in the
directory with the file "x" (in theory we should also test all the
parent dirs).
"""
init_py = os.path.join(os.path.dirname(x), "__init__.py")
return os.path.exists(init_py)
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
g = []
for path, folders, files in os.walk(dir):
g.extend([os.path.join(path, f) for f in files
if not f.startswith('test_') and fnmatch(f, pat)])
if init_only:
# skip files that are not importable (i.e. missing __init__.py)
g = [x for x in g if importable(x)]
return [os.path.normcase(gi) for gi in g]
def _check_dependencies(self,
executables=(),
modules=(),
disable_viewers=(),
python_version=(3, 5),
ground_types=None):
"""
Checks if the dependencies for the test are installed.
Raises ``DependencyError`` it at least one dependency is not installed.
"""
for executable in executables:
if not shutil.which(executable):
raise DependencyError("Could not find %s" % executable)
for module in modules:
if module == 'matplotlib':
matplotlib = import_module(
'matplotlib',
import_kwargs={'fromlist':
['pyplot', 'cm', 'collections']},
min_module_version='1.0.0', catch=(RuntimeError,))
if matplotlib is None:
raise DependencyError("Could not import matplotlib")
else:
if not import_module(module):
raise DependencyError("Could not import %s" % module)
if disable_viewers:
tempdir = tempfile.mkdtemp()
os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
vw = ('#!/usr/bin/env python3\n'
'import sys\n'
'if len(sys.argv) <= 1:\n'
' exit("wrong number of args")\n')
for viewer in disable_viewers:
Path(os.path.join(tempdir, viewer)).write_text(vw)
# make the file executable
os.chmod(os.path.join(tempdir, viewer),
stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
if python_version:
if sys.version_info < python_version:
raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
if ground_types is not None:
if GROUND_TYPES not in ground_types:
raise DependencyError("Requires ground_types in " + str(ground_types))
if 'pyglet' in modules:
# monkey-patch pyglet s.t. it does not open a window during
# doctesting
import pyglet
class DummyWindow:
def __init__(self, *args, **kwargs):
self.has_exit = True
self.width = 600
self.height = 400
def set_vsync(self, x):
pass
def switch_to(self):
pass
def push_handlers(self, x):
pass
def close(self):
pass
pyglet.window.Window = DummyWindow
| SymPyDocTests |
python | pypa__setuptools | setuptools/_vendor/typeguard/_transformer.py | {
"start": 2005,
"end": 8228
} | class ____:
node: Module | ClassDef | FunctionDef | AsyncFunctionDef | None
parent: TransformMemo | None
path: tuple[str, ...]
joined_path: Constant = field(init=False)
return_annotation: expr | None = None
yield_annotation: expr | None = None
send_annotation: expr | None = None
is_async: bool = False
local_names: set[str] = field(init=False, default_factory=set)
imported_names: dict[str, str] = field(init=False, default_factory=dict)
ignored_names: set[str] = field(init=False, default_factory=set)
load_names: defaultdict[str, dict[str, Name]] = field(
init=False, default_factory=lambda: defaultdict(dict)
)
has_yield_expressions: bool = field(init=False, default=False)
has_return_expressions: bool = field(init=False, default=False)
memo_var_name: Name | None = field(init=False, default=None)
should_instrument: bool = field(init=False, default=True)
variable_annotations: dict[str, expr] = field(init=False, default_factory=dict)
configuration_overrides: dict[str, Any] = field(init=False, default_factory=dict)
code_inject_index: int = field(init=False, default=0)
def __post_init__(self) -> None:
elements: list[str] = []
memo = self
while isinstance(memo.node, (ClassDef, FunctionDef, AsyncFunctionDef)):
elements.insert(0, memo.node.name)
if not memo.parent:
break
memo = memo.parent
if isinstance(memo.node, (FunctionDef, AsyncFunctionDef)):
elements.insert(0, "<locals>")
self.joined_path = Constant(".".join(elements))
# Figure out where to insert instrumentation code
if self.node:
for index, child in enumerate(self.node.body):
if isinstance(child, ImportFrom) and child.module == "__future__":
# (module only) __future__ imports must come first
continue
elif (
isinstance(child, Expr)
and isinstance(child.value, Constant)
and isinstance(child.value.value, str)
):
continue # docstring
self.code_inject_index = index
break
def get_unused_name(self, name: str) -> str:
memo: TransformMemo | None = self
while memo is not None:
if name in memo.local_names:
memo = self
name += "_"
else:
memo = memo.parent
self.local_names.add(name)
return name
def is_ignored_name(self, expression: expr | Expr | None) -> bool:
top_expression = (
expression.value if isinstance(expression, Expr) else expression
)
if isinstance(top_expression, Attribute) and isinstance(
top_expression.value, Name
):
name = top_expression.value.id
elif isinstance(top_expression, Name):
name = top_expression.id
else:
return False
memo: TransformMemo | None = self
while memo is not None:
if name in memo.ignored_names:
return True
memo = memo.parent
return False
def get_memo_name(self) -> Name:
if not self.memo_var_name:
self.memo_var_name = Name(id="memo", ctx=Load())
return self.memo_var_name
def get_import(self, module: str, name: str) -> Name:
if module in self.load_names and name in self.load_names[module]:
return self.load_names[module][name]
qualified_name = f"{module}.{name}"
if name in self.imported_names and self.imported_names[name] == qualified_name:
return Name(id=name, ctx=Load())
alias = self.get_unused_name(name)
node = self.load_names[module][name] = Name(id=alias, ctx=Load())
self.imported_names[name] = qualified_name
return node
def insert_imports(self, node: Module | FunctionDef | AsyncFunctionDef) -> None:
"""Insert imports needed by injected code."""
if not self.load_names:
return
# Insert imports after any "from __future__ ..." imports and any docstring
for modulename, names in self.load_names.items():
aliases = [
alias(orig_name, new_name.id if orig_name != new_name.id else None)
for orig_name, new_name in sorted(names.items())
]
node.body.insert(self.code_inject_index, ImportFrom(modulename, aliases, 0))
def name_matches(self, expression: expr | Expr | None, *names: str) -> bool:
if expression is None:
return False
path: list[str] = []
top_expression = (
expression.value if isinstance(expression, Expr) else expression
)
if isinstance(top_expression, Subscript):
top_expression = top_expression.value
elif isinstance(top_expression, Call):
top_expression = top_expression.func
while isinstance(top_expression, Attribute):
path.insert(0, top_expression.attr)
top_expression = top_expression.value
if not isinstance(top_expression, Name):
return False
if top_expression.id in self.imported_names:
translated = self.imported_names[top_expression.id]
elif hasattr(builtins, top_expression.id):
translated = "builtins." + top_expression.id
else:
translated = top_expression.id
path.insert(0, translated)
joined_path = ".".join(path)
if joined_path in names:
return True
elif self.parent:
return self.parent.name_matches(expression, *names)
else:
return False
def get_config_keywords(self) -> list[keyword]:
if self.parent and isinstance(self.parent.node, ClassDef):
overrides = self.parent.configuration_overrides.copy()
else:
overrides = {}
overrides.update(self.configuration_overrides)
return [keyword(key, value) for key, value in overrides.items()]
| TransformMemo |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/toys/error_monster.py | {
"start": 342,
"end": 1468
} | class ____(IOManager):
def __init__(self, throw_input, throw_output):
self._values = {}
self._throw_input = throw_input
self._throw_output = throw_output
def handle_output(self, context, obj):
if self._throw_output:
raise ExampleException("throwing up trying to handle output")
keys = tuple(context.get_identifier())
self._values[keys] = obj
def load_input(self, context):
if self._throw_input:
raise ExampleException("throwing up trying to load input")
keys = tuple(context.upstream_output.get_identifier()) # pyright: ignore[reportOptionalMemberAccess]
return self._values[keys]
@io_manager(
config_schema={
"throw_in_load_input": Field(bool, is_required=False, default_value=False),
"throw_in_handle_output": Field(bool, is_required=False, default_value=False),
}
)
def errorable_io_manager(init_context):
return ErrorableIOManager(
init_context.resource_config["throw_in_load_input"],
init_context.resource_config["throw_in_handle_output"],
)
| ErrorableIOManager |
python | doocs__leetcode | solution/3000-3099/3094.Guess the Number Using Bitwise Questions II/Solution.py | {
"start": 69,
"end": 317
} | class ____:
def findNumber(self) -> int:
n = 0
for i in range(32):
count1 = commonBits(1 << i)
count2 = commonBits(1 << i)
if count1 > count2:
n |= 1 << i
return n
| Solution |
python | langchain-ai__langchain | libs/partners/mistralai/tests/integration_tests/test_standard.py | {
"start": 312,
"end": 896
} | class ____(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[BaseChatModel]:
return ChatMistralAI
@property
def chat_model_params(self) -> dict:
return {"model": "mistral-large-latest", "temperature": 0}
@property
def supports_json_mode(self) -> bool:
return True
@pytest.mark.xfail(reason=("MistralAI inconsistently fails to return valid fields"))
def test_structured_output_pydantic_2_v1(self, model: BaseChatModel) -> None:
super().test_structured_output_pydantic_2_v1(model)
| TestMistralStandard |
python | streamlit__streamlit | lib/streamlit/delta_generator_singletons.py | {
"start": 1224,
"end": 4649
} | class ____:
"""Used to initialize the DeltaGenerator classes and store them as singletons.
This module allows us to avoid circular imports between DeltaGenerator and elements,
because elements can import this singleton module instead of DeltaGenerator directly.
"""
_instance: DeltaGeneratorSingleton | None = None
@classmethod
def instance(cls) -> DeltaGeneratorSingleton:
"""Return the singleton DeltaGeneratorSingleton instance. Raise an Error if the
DeltaGeneratorSingleton hasn't been created yet.
"""
if cls._instance is None:
raise RuntimeError("DeltaGeneratorSingleton hasn't been created!")
return cls._instance
def __init__(
self,
delta_generator_cls: type[DeltaGenerator],
status_container_cls: type[StatusContainer],
dialog_container_cls: type[Dialog],
) -> None:
"""Registers and initializes all delta-generator classes.
Parameters
----------
delta_generator_cls : type[DeltaGenerator]
The main DeltaGenerator class.
status_container_cls : type[StatusContainer]
The delta-generator class that is used as return value for `st.status`.
dialog_container_cls : type[Dialog]
The delta-generator class used is used as return value for `st.dialog`.
Raises
------
RuntimeError
If the DeltaGeneratorSingleton instance already exists.
"""
if DeltaGeneratorSingleton._instance is not None:
raise RuntimeError("DeltaGeneratorSingleton instance already exists!")
DeltaGeneratorSingleton._instance = self
self._main_dg = delta_generator_cls(root_container=_RootContainer.MAIN)
self._sidebar_dg = delta_generator_cls(
root_container=_RootContainer.SIDEBAR, parent=self._main_dg
)
self._event_dg = delta_generator_cls(
root_container=_RootContainer.EVENT, parent=self._main_dg
)
self._bottom_dg = delta_generator_cls(
root_container=_RootContainer.BOTTOM, parent=self._main_dg
)
self._status_container_cls = status_container_cls
self._dialog_container_cls = dialog_container_cls
@property
def main_dg(self) -> DeltaGenerator:
return self._main_dg
@property
def sidebar_dg(self) -> DeltaGenerator:
return self._sidebar_dg
@property
def event_dg(self) -> DeltaGenerator:
return self._event_dg
@property
def bottom_dg(self) -> DeltaGenerator:
return self._bottom_dg
@property
def status_container_cls(
self,
) -> type[StatusContainer]:
"""Stub for StatusContainer. Since StatusContainer inherits from DeltaGenerator,
this is used to avoid circular imports.
"""
return self._status_container_cls
@property
def dialog_container_cls(self) -> type[Dialog]:
"""Stub for Dialog. Since Dialog inherits from DeltaGenerator,
this is used to avoid circular imports.
"""
return self._dialog_container_cls
def get_dg_singleton_instance() -> DeltaGeneratorSingleton:
"""Return the DeltaGeneratorSingleton instance. Raise an Error if the
DeltaGeneratorSingleton hasn't been created yet.
"""
return DeltaGeneratorSingleton.instance()
_T = TypeVar("_T")
| DeltaGeneratorSingleton |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/req/req_file.py | {
"start": 9673,
"end": 13417
} | class ____:
def __init__(
self,
session: "PipSession",
line_parser: LineParser,
) -> None:
self._session = session
self._line_parser = line_parser
def parse(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
"""Parse a given file, yielding parsed lines."""
yield from self._parse_and_recurse(filename, constraint)
def _parse_and_recurse(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
for line in self._parse_file(filename, constraint):
if not line.is_requirement and (
line.opts.requirements or line.opts.constraints
):
# parse a nested requirements file
if line.opts.requirements:
req_path = line.opts.requirements[0]
nested_constraint = False
else:
req_path = line.opts.constraints[0]
nested_constraint = True
# original file is over http
if SCHEME_RE.search(filename):
# do a url join so relative paths work
req_path = urllib.parse.urljoin(filename, req_path)
# original file and nested file are paths
elif not SCHEME_RE.search(req_path):
# do a join so relative paths work
req_path = os.path.join(
os.path.dirname(filename),
req_path,
)
yield from self._parse_and_recurse(req_path, nested_constraint)
else:
yield line
def _parse_file(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
_, content = get_file_content(filename, self._session)
lines_enum = preprocess(content)
for line_number, line in lines_enum:
try:
args_str, opts = self._line_parser(line)
except OptionParsingError as e:
# add offending line
msg = f"Invalid requirement: {line}\n{e.msg}"
raise RequirementsFileParseError(msg)
yield ParsedLine(
filename,
line_number,
args_str,
opts,
constraint,
)
def get_line_parser(finder: Optional["PackageFinder"]) -> LineParser:
def parse_line(line: str) -> Tuple[str, Values]:
# Build new parser for each line since it accumulates appendable
# options.
parser = build_parser()
defaults = parser.get_default_values()
defaults.index_url = None
if finder:
defaults.format_control = finder.format_control
args_str, options_str = break_args_options(line)
try:
options = shlex.split(options_str)
except ValueError as e:
raise OptionParsingError(f"Could not split options: {options_str}") from e
opts, _ = parser.parse_args(options, defaults)
return args_str, opts
return parse_line
def break_args_options(line: str) -> Tuple[str, str]:
"""Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
"""
tokens = line.split(" ")
args = []
options = tokens[:]
for token in tokens:
if token.startswith("-") or token.startswith("--"):
break
else:
args.append(token)
options.pop(0)
return " ".join(args), " ".join(options)
| RequirementsFileParser |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 6809,
"end": 7209
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
n_missing = metafeatures.get_value("NumberOfInstancesWithMissingValues")
n_total = float(metafeatures["NumberOfInstances"](X, y, logger).value)
return float(n_missing / n_total)
@metafeatures.define("NumberOfFeaturesWithMissingValues", dependency="MissingValues")
| PercentageOfInstancesWithMissingValues |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 10535,
"end": 11788
} | class ____(list):
def __contains__(self, value):
if not isinstance(value, list):
return list.__contains__(self, value)
len_value = len(value)
len_self = len(self)
if len_value > len_self:
return False
for i in range(0, len_self - len_value + 1):
sub_list = self[i:i+len_value]
if sub_list == value:
return True
return False
def __repr__(self):
return pprint.pformat(list(self))
def _check_and_set_parent(parent, value, name, new_name):
if not _is_instance_mock(value):
return False
if ((value._mock_name or value._mock_new_name) or
(value._mock_parent is not None) or
(value._mock_new_parent is not None)):
return False
_parent = parent
while _parent is not None:
# setting a mock (value) as a child or return value of itself
# should not modify the mock
if _parent is value:
return False
_parent = _parent._mock_new_parent
if new_name:
value._mock_new_parent = parent
value._mock_new_name = new_name
if name:
value._mock_parent = parent
value._mock_name = name
return True
| _CallList |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-orchestrate/test_flow_complex_topology.py | {
"start": 628,
"end": 1386
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
docs.texts = ['foo' for _ in docs]
def test_flow_external_executor_with_gateway():
external_gateway_port = helper.random_port()
def serve_exec(**kwargs):
FooExec.serve(**kwargs)
e = multiprocessing.Event()
t = multiprocessing.Process(
name='serve-exec',
target=serve_exec,
kwargs={'port': external_gateway_port, 'stop_event': e},
)
t.start()
time.sleep(5) # allow exec to start
with Flow().add(
name='external_gateway_exec', external=True, port=external_gateway_port
) as f:
docs = f.search(Document())
assert docs.texts == ['foo']
e.set()
t.terminate()
t.join()
| FooExec |
python | getsentry__sentry | src/sentry/integrations/bitbucket/integration.py | {
"start": 9919,
"end": 10728
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
with IntegrationPipelineViewEvent(
IntegrationPipelineViewType.VERIFY_INSTALLATION,
IntegrationDomain.SOURCE_CODE_MANAGEMENT,
BitbucketIntegrationProvider.key,
).capture() as lifecycle:
try:
integration = get_integration_from_request(
request, BitbucketIntegrationProvider.key
)
except AtlassianConnectValidationError as e:
lifecycle.record_failure(str(e))
return pipeline.error("Unable to verify installation.")
pipeline.bind_state("external_id", integration.external_id)
return pipeline.next_step()
| VerifyInstallation |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/data_partitioner.py | {
"start": 385,
"end": 1325
} | class ____(enum.Enum):
"""SQL supported date parts for most dialects."""
YEAR = "year"
MONTH = "month"
WEEK = "week"
DAY = "day"
HOUR = "hour"
MINUTE = "minute"
SECOND = "second"
@override
def __eq__(self, other: str | DatePart): # type: ignore[override] # expects `object`
if isinstance(other, str):
return self.value.lower() == other.lower()
return self.value.lower() == other.value.lower()
@override
def __hash__(self: DatePart):
return hash(self.value)
@classmethod
def to_yaml(cls, representer, node):
"""
Method allows for yaml-encodable representation of ENUM, using internal methods of ruamel.
pattern was found in the following stackoverflow thread:
https://stackoverflow.com/questions/48017317/can-ruamel-yaml-encode-an-enum
"""
return representer.represent_str(data=node.value)
| DatePart |
python | django__django | tests/utils_tests/test_safestring.py | {
"start": 307,
"end": 518
} | class ____(str):
def __html__(self):
# Implement specific and wrong escaping in order to be able to detect
# when it runs.
return self.replace("<", "<<").replace(">", ">>")
| customescape |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 1858,
"end": 1913
} | class ____(ModelOutput):
...
@dataclass
| AltCLIPOutput |
python | astropy__astropy | astropy/utils/tests/test_decorators.py | {
"start": 3985,
"end": 4050
} | class ____(type):
metaclass_attr = 1
@deprecated("100.0")
| TMeta |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 1324,
"end": 1738
} | class ____(BaseConfig):
previous_connector_version: str = Field(
regex=SEMVER_REGEX, default="latest", description="Previous connector version to use for backward compatibility tests."
)
disable_for_version: Optional[str] = Field(
regex=SEMVER_REGEX, default=None, description="Disable backward compatibility tests for a specific connector version."
)
| BackwardCompatibilityTestsConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/datastore.py | {
"start": 1454,
"end": 1665
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Datastore Entities Link."""
name = "Entities"
key = "entities_conf"
format_str = DATASTORE_ENTITIES_LINK
| CloudDatastoreEntitiesLink |
python | tornadoweb__tornado | tornado/test/netutil_test.py | {
"start": 2107,
"end": 2459
} | class ____(_ResolverErrorTestMixin):
def setUp(self):
super().setUp()
self.resolver = BlockingResolver()
self.real_getaddrinfo = socket.getaddrinfo
socket.getaddrinfo = _failing_getaddrinfo
def tearDown(self):
socket.getaddrinfo = self.real_getaddrinfo
super().tearDown()
| BlockingResolverErrorTest |
python | tensorflow__tensorflow | tensorflow/python/saved_model/load.py | {
"start": 4887,
"end": 7157
} | class ____(function.ConcreteFunction):
"""A class wraps a concrete function to handle different distributed contexts.
The reason for wrapping a concrete function is because the _captured_inputs
fields used for in-replica context and cross-replica context are different.
When `load()` is called from within a tf.distribute.strategy scope, the
captured inputs are distributed variables. When using these distributed
variables during calling the function, we need different approaches when it is
in-replica and when it is not in-replica. When it is in replica, naturally we
should use the corresponding component of the distributed variable; when it is
not in-replica, calling the function should mean that it is constructing a
graph that is not actually going to be used. A typical use case is when
constructing a functional model. In this case, return a placeholder with a
control dependency to ensure that is never accessed.
"""
def __init__(self, concrete_function):
# Shallow copy the concrete_function
self.__dict__.update(vars(concrete_function))
def _call_flat(self, args, captured_inputs):
def get_handle(x):
return x.handle if distribute_utils.is_distributed_variable(x) else x
def get_unused_handle(x):
return _unused_handle() if distribute_utils.is_distributed_variable(x) \
else x
if (distribute_lib.get_replica_context() is not None or
values_util.is_saving_non_distributed()):
# If we're in the replica context or are saving a non-distributed version
# of the model, we resolve the captured variables to the corresponding
# resource handle. In both situation we call var.handle, but it has
# different behavior. In the replica context, var.handle resolves the
# replica local variable handle if the variable is replicated. When saving
# a non-distributed version of the model, var.handle resolves to the
# primary variable handle, since we only save one copy of a replicated
# variable.
captured_inputs = list(map(get_handle, captured_inputs))
else: # cross-replica context
captured_inputs = list(map(get_unused_handle, captured_inputs))
return super()._call_flat(args, captured_inputs)
| _WrapperFunction |
python | numpy__numpy | numpy/_core/tests/test_conversion_utils.py | {
"start": 228,
"end": 2533
} | class ____:
allow_bytes = True
case_insensitive = True
exact_match = False
warn = True
def _check_value_error(self, val):
pattern = fr'\(got {re.escape(repr(val))}\)'
with pytest.raises(ValueError, match=pattern) as exc:
self.conv(val)
def _check_conv_assert_warn(self, val, expected):
if self.warn:
with assert_raises(ValueError) as exc:
assert self.conv(val) == expected
else:
assert self.conv(val) == expected
def _check(self, val, expected):
"""Takes valid non-deprecated inputs for converters,
runs converters on inputs, checks correctness of outputs,
warnings and errors"""
assert self.conv(val) == expected
if self.allow_bytes:
assert self.conv(val.encode('ascii')) == expected
else:
with pytest.raises(TypeError):
self.conv(val.encode('ascii'))
if len(val) != 1:
if self.exact_match:
self._check_value_error(val[:1])
self._check_value_error(val + '\0')
else:
self._check_conv_assert_warn(val[:1], expected)
if self.case_insensitive:
if val != val.lower():
self._check_conv_assert_warn(val.lower(), expected)
if val != val.upper():
self._check_conv_assert_warn(val.upper(), expected)
else:
if val != val.lower():
self._check_value_error(val.lower())
if val != val.upper():
self._check_value_error(val.upper())
def test_wrong_type(self):
# common cases which apply to all the below
with pytest.raises(TypeError):
self.conv({})
with pytest.raises(TypeError):
self.conv([])
def test_wrong_value(self):
# nonsense strings
self._check_value_error('')
self._check_value_error('\N{greek small letter pi}')
if self.allow_bytes:
self._check_value_error(b'')
# bytes which can't be converted to strings via utf8
self._check_value_error(b"\xFF")
if self.exact_match:
self._check_value_error("there's no way this is supported")
| StringConverterTestCase |
python | getsentry__sentry | tests/sentry/integrations/bitbucket_server/test_webhook.py | {
"start": 3723,
"end": 8430
} | class ____(WebhookTestBase):
method = "post"
def test_missing_integration(self) -> None:
self.create_repository()
self.get_error_response(
self.organization.id,
self.integration.id,
raw_data=REFS_CHANGED_EXAMPLE,
extra_headers=dict(HTTP_X_EVENT_KEY="repo:refs_changed"),
status_code=404,
)
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_simple(self, mock_record: MagicMock) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration.add_organization(self.organization, default_auth_id=self.identity.id)
self.create_repository()
self.send_webhook()
assert_success_metric(mock_record)
@patch("sentry.integrations.bitbucket_server.client.BitbucketServerClient.get_commits")
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_webhook_error_metric(
self, mock_record: MagicMock, mock_get_commits: MagicMock
) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration.add_organization(self.organization, default_auth_id=self.identity.id)
self.create_repository()
error = Exception("error")
mock_get_commits.side_effect = error
self.get_error_response(
self.organization.id,
self.integration.id,
raw_data={
"changes": [{"fromHash": "hash1", "toHash": "hash2"}],
"repository": {
"id": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}",
"project": {"key": "my-project"},
"slug": "breaking-changes",
},
},
extra_headers=dict(HTTP_X_EVENT_KEY="repo:refs_changed"),
status_code=500,
)
assert_failure_metric(mock_record, error)
@responses.activate
def test_get_commits_error(self) -> None:
responses.add(
responses.GET,
"https://api.bitbucket.org/rest/api/1.0/projects/my-project/repos/marcos/commits",
json={"error": "unauthorized"},
status=401,
)
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration.add_organization(self.organization, default_auth_id=self.identity.id)
self.create_repository()
payload = {
"changes": [
{
"fromHash": "hash1",
"ref": {
"displayId": "displayId",
"id": "id",
"type": "'BRANCH'",
},
"refId": "refId",
"toHash": "hash2",
"type": "UPDATE",
}
],
"repository": {
"id": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}",
"project": {"key": "my-project"},
"slug": "marcos",
},
}
self.get_error_response(
self.organization.id,
self.integration.id,
raw_data=orjson.dumps(payload),
extra_headers=dict(HTTP_X_EVENT_KEY="repo:refs_changed"),
status_code=400,
)
@responses.activate
def test_handle_unreachable_host(self) -> None:
responses.add(
responses.GET,
"https://api.bitbucket.org/rest/api/1.0/projects/my-project/repos/marcos/commits",
body=ConnectionError("Unable to reach host: https://api.bitbucket.org"),
)
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration.add_organization(self.organization, default_auth_id=self.identity.id)
self.create_repository()
payload = {
"changes": [
{
"fromHash": "hash1",
"ref": {
"displayId": "displayId",
"id": "id",
"type": "'BRANCH'",
},
"refId": "refId",
"toHash": "hash2",
"type": "UPDATE",
}
],
"repository": {
"id": "{b128e0f6-196a-4dde-b72d-f42abc6dc239}",
"project": {"key": "my-project"},
"slug": "marcos",
},
}
self.get_error_response(
self.organization.id,
self.integration.id,
raw_data=orjson.dumps(payload),
extra_headers=dict(HTTP_X_EVENT_KEY="repo:refs_changed"),
status_code=400,
)
| RefsChangedWebhookTest |
python | pypa__warehouse | warehouse/subscriptions/services.py | {
"start": 13946,
"end": 26015
} | class ____:
def __init__(self, db_session):
self.db = db_session
def get_subscription(self, id):
"""
Get a subscription by id
"""
return self.db.get(StripeSubscription, id)
def find_subscriptionid(self, subscription_id):
"""
Find the unique subscription identifier for the subscription,
by the payment service provider subscription id or None
"""
try:
(id,) = (
self.db.query(StripeSubscription.id)
.filter(
StripeSubscription.subscription_id == subscription_id,
)
.one()
)
except NoResultFound:
return
return id
def add_subscription(
self, customer_id, subscription_id, subscription_item_id, billing_email
):
"""
Attempts to create a subscription object for the organization
with the specified customer ID and subscription ID
"""
# Get default subscription price.
subscription_price = self.get_or_create_default_subscription_price()
# Get the stripe customer.
stripe_customer = self.get_stripe_customer(
self.find_stripe_customer_id(customer_id)
)
# Set the billing email
stripe_customer.billing_email = billing_email
# Add new subscription.
subscription = StripeSubscription(
stripe_customer_id=stripe_customer.id,
subscription_id=subscription_id,
subscription_price_id=subscription_price.id,
status=StripeSubscriptionStatus.Active, # default active subscription
)
# Get the organization stripe customer.
organization_stripe_customer = (
self.db.query(OrganizationStripeCustomer)
.filter(OrganizationStripeCustomer.stripe_customer_id == stripe_customer.id)
.one()
)
# Link to organization.
organization_subscription = OrganizationStripeSubscription(
organization=organization_stripe_customer.organization,
subscription=subscription,
)
self.db.add(subscription)
self.db.add(organization_subscription)
self.db.flush() # flush db now so we have acccess to subscription.id
# Create new subscription item.
subscription_item = StripeSubscriptionItem(
subscription_item_id=subscription_item_id,
subscription_id=subscription.id,
subscription_price_id=subscription_price.id,
quantity=len(organization_stripe_customer.organization.users),
)
self.db.add(subscription_item)
return subscription
def update_subscription_status(self, id, status):
"""
Update the status of a subscription object by subscription.id
"""
self.db.query(StripeSubscription).filter(
StripeSubscription.id == id,
).update({StripeSubscription.status: status})
def delete_subscription(self, id):
"""
Delete a subscription by ID
"""
subscription = self.get_subscription(id)
# Delete link to organization
self.db.query(OrganizationStripeSubscription).filter_by(
subscription=subscription
).delete()
# Delete subscription items
self.db.query(StripeSubscriptionItem).filter_by(
subscription=subscription
).delete()
self.db.delete(subscription)
def get_subscriptions_by_customer(self, customer_id):
"""
Get a list of subscriptions tied to the given customer ID
"""
stripe_customer_id = self.find_stripe_customer_id(customer_id)
return (
self.db.query(StripeSubscription)
.filter(StripeSubscription.stripe_customer_id == stripe_customer_id)
.all()
)
def get_stripe_customer(self, stripe_customer_id):
"""
Get a stripe customer by id
"""
return self.db.get(StripeCustomer, stripe_customer_id)
def find_stripe_customer_id(self, customer_id):
"""
Get the stripe customer UUID tied to the given customer ID
"""
try:
(id,) = (
self.db.query(StripeCustomer.id)
.filter(
StripeCustomer.customer_id == customer_id,
)
.one()
)
except NoResultFound:
return
return id
def delete_customer(self, customer_id):
"""
Deletes a customer and all associated subscription data
"""
subscriptions = self.get_subscriptions_by_customer(customer_id)
for subscription in subscriptions:
self.delete_subscription(subscription.id)
stripe_customer_id = self.find_stripe_customer_id(customer_id)
# Delete OrganizationStripeCustomer association
self.db.query(OrganizationStripeCustomer).filter(
OrganizationStripeCustomer.stripe_customer_id == stripe_customer_id
).delete()
# Delete StripeCustomer object
self.db.query(StripeCustomer).filter(
StripeCustomer.id == stripe_customer_id
).delete()
def add_stripe_customer(self, customer_id):
"""
Create a StripeCustomer object to associate to the Stripe customer ID
"""
stripe_customer = StripeCustomer(
customer_id=customer_id,
)
self.db.add(stripe_customer)
self.db.flush() # flush db now so we have access to stripe_customer.id
return stripe_customer
def update_customer_email(self, customer_id, billing_email):
"""
Update the customer's billing email
"""
stripe_customer_id = self.find_stripe_customer_id(customer_id)
self.db.query(StripeCustomer).filter(
StripeCustomer.id == stripe_customer_id,
).update({StripeCustomer.billing_email: billing_email})
def get_subscription_product(self, subscription_product_id):
"""
Get a product by subscription product id
"""
return self.db.get(StripeSubscriptionProduct, subscription_product_id)
def get_subscription_products(self):
"""
Get a list of all products
"""
return (
self.db.query(StripeSubscriptionProduct)
.order_by(StripeSubscriptionProduct.product_name)
.all()
)
def find_subscription_productid(self, search_term):
"""
Find the unique product identifier for the product name,
product id or None if nothing is found
"""
try:
(subscription_product_id,) = (
self.db.query(StripeSubscriptionProduct.id)
.filter(
or_(
StripeSubscriptionProduct.product_name == search_term,
StripeSubscriptionProduct.product_id == search_term,
)
)
.one()
)
except NoResultFound:
return
return subscription_product_id
def add_subscription_product(self, product_name, description, product_id, tax_code):
"""
Add a subscription product
"""
subscription_product = StripeSubscriptionProduct(
product_name=product_name,
description=description,
product_id=product_id,
tax_code=tax_code,
)
self.db.add(subscription_product)
self.db.flush() # flush db now so we have access to subscription_product.id
return subscription_product
def update_subscription_product(self, subscription_product_id, **changes):
"""
Accepts a subscription product object
and attempts an update with those attributes
"""
subscription_product = self.get_subscription_product(subscription_product_id)
for attr, value in changes.items():
setattr(subscription_product, attr, value)
return subscription_product
def delete_subscription_product(self, subscription_product_id):
"""
Delete a subscription product
"""
subscription_product = self.get_subscription_product(subscription_product_id)
self.db.delete(subscription_product)
def get_or_create_default_subscription_price(self):
"""
Get the default subscription price or initialize one if nothing is found
"""
try:
subscription_price = (
self.db.query(StripeSubscriptionPrice)
.filter(StripeSubscriptionPrice.is_active)
.one()
)
except NoResultFound:
subscription_product = self.add_subscription_product(
product_name="PyPI",
description="Organization account for companies",
product_id=None,
# See Stripe docs for tax codes. https://stripe.com/docs/tax/tax-categories # noqa: E501
tax_code="txcd_10103001", # Software as a service (SaaS) - business use
)
subscription_price = self.add_subscription_price(
price_id=None,
currency="usd",
subscription_product_id=subscription_product.id,
unit_amount=500,
recurring=StripeSubscriptionPriceInterval.Month,
tax_behavior="inclusive",
)
return subscription_price
def get_subscription_price(self, subscription_price_id):
"""
Get a subscription price by id
"""
return self.db.get(StripeSubscriptionPrice, subscription_price_id)
def get_subscription_prices(self):
"""
Get a list of all subscription prices
"""
return (
self.db.query(StripeSubscriptionPrice)
.order_by(StripeSubscriptionPrice.id)
.all()
)
def find_subscription_priceid(self, search_term):
"""
Find the unique price identifier for the price id,
subscription product id or None if nothing is found
"""
try:
(subscription_price_id,) = (
self.db.query(StripeSubscriptionPrice.id)
.filter(
StripeSubscriptionPrice.price_id == search_term,
)
.one()
)
except NoResultFound:
return
return subscription_price_id
def add_subscription_price(
self,
price_id,
currency,
subscription_product_id,
unit_amount,
recurring,
tax_behavior,
):
"""
Add a subscription price
"""
subscription_price = StripeSubscriptionPrice(
price_id=price_id,
currency=currency,
subscription_product_id=subscription_product_id,
unit_amount=unit_amount,
recurring=recurring,
tax_behavior=tax_behavior,
)
self.db.add(subscription_price)
self.db.flush() # flush db now so we have access to subscription_price.id
return subscription_price
def update_subscription_price(self, subscription_price_id, **changes):
"""
Accepts a subscription price object
and attempts an update with those attributes
"""
subscription_price = self.get_subscription_price(subscription_price_id)
for attr, value in changes.items():
setattr(subscription_price, attr, value)
return subscription_price
def delete_subscription_price(self, subscription_price_id):
"""
Delete a subscription price
"""
subscription_price = self.get_subscription_price(subscription_price_id)
self.db.delete(subscription_price)
def subscription_factory(context, request):
return StripeSubscriptionService(request.db)
| StripeSubscriptionService |
python | django__django | django/contrib/gis/geos/collections.py | {
"start": 3671,
"end": 3991
} | class ____(GeometryCollection):
_allowed = Polygon
_typeid = 6
# Setting the allowed types here since GeometryCollection is defined before
# its subclasses.
GeometryCollection._allowed = (
Point,
LineString,
LinearRing,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
)
| MultiPolygon |
python | ansible__ansible | test/units/playbook/test_helpers.py | {
"start": 1162,
"end": 3512
} | class ____(object):
def _setup(self):
# This is not a very good mixin, lots of side effects
self.fake_loader = DictDataLoader({'include_test.yml': "",
'other_include_test.yml': ""})
self.mock_tqm = MagicMock(name='MockTaskQueueManager')
self.mock_play = MagicMock(name='MockPlay')
self.mock_play._attributes = []
self.mock_play._collections = None
self.mock_iterator = MagicMock(name='MockIterator')
self.mock_iterator._play = self.mock_play
self.mock_inventory = MagicMock(name='MockInventory')
self.mock_inventory._hosts_cache = dict()
# TODO: can we use a real VariableManager?
self.mock_variable_manager = MagicMock(name='MockVariableManager')
self.mock_variable_manager.get_vars.return_value = dict()
self.mock_block = MagicMock(name='MockBlock')
# On macOS /etc is actually /private/etc, tests fail when performing literal /etc checks
self.fake_role_loader = DictDataLoader({os.path.join(os.path.realpath("/etc"), "ansible/roles/bogus_role/tasks/main.yml"): """
- shell: echo 'hello world'
"""})
self._test_data_path = os.path.dirname(__file__)
self.fake_include_loader = DictDataLoader({"/dev/null/includes/test_include.yml": """
- include_tasks: other_test_include.yml
- shell: echo 'hello world'
""",
"/dev/null/includes/static_test_include.yml": """
- include_tasks: other_test_include.yml
- shell: echo 'hello static world'
""",
"/dev/null/includes/other_test_include.yml": """
- debug:
msg: other_test_include_debug
"""})
@pytest.mark.usefixtures('collection_loader')
| MixinForMocks |
python | sympy__sympy | sympy/tensor/indexed.py | {
"start": 11522,
"end": 18614
} | class ____(Expr, NotIterable):
"""Represent the base or stem of an indexed object
The IndexedBase class represent an array that contains elements. The main purpose
of this class is to allow the convenient creation of objects of the Indexed
class. The __getitem__ method of IndexedBase returns an instance of
Indexed. Alone, without indices, the IndexedBase class can be used as a
notation for e.g. matrix equations, resembling what you could do with the
Symbol class. But, the IndexedBase class adds functionality that is not
available for Symbol instances:
- An IndexedBase object can optionally store shape information. This can
be used in to check array conformance and conditions for numpy
broadcasting. (TODO)
- An IndexedBase object implements syntactic sugar that allows easy symbolic
representation of array operations, using implicit summation of
repeated indices.
- The IndexedBase object symbolizes a mathematical structure equivalent
to arrays, and is recognized as such for code generation and automatic
compilation and wrapping.
>>> from sympy.tensor import IndexedBase, Idx
>>> from sympy import symbols
>>> A = IndexedBase('A'); A
A
>>> type(A)
<class 'sympy.tensor.indexed.IndexedBase'>
When an IndexedBase object receives indices, it returns an array with named
axes, represented by an Indexed object:
>>> i, j = symbols('i j', integer=True)
>>> A[i, j, 2]
A[i, j, 2]
>>> type(A[i, j, 2])
<class 'sympy.tensor.indexed.Indexed'>
The IndexedBase constructor takes an optional shape argument. If given,
it overrides any shape information in the indices. (But not the index
ranges!)
>>> m, n, o, p = symbols('m n o p', integer=True)
>>> i = Idx('i', m)
>>> j = Idx('j', n)
>>> A[i, j].shape
(m, n)
>>> B = IndexedBase('B', shape=(o, p))
>>> B[i, j].shape
(o, p)
Assumptions can be specified with keyword arguments the same way as for Symbol:
>>> A_real = IndexedBase('A', real=True)
>>> A_real.is_real
True
>>> A != A_real
True
Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase:
>>> I = symbols('I', integer=True)
>>> C_inherit = IndexedBase(I)
>>> C_explicit = IndexedBase('I', integer=True)
>>> C_inherit == C_explicit
True
"""
is_symbol = True
is_Atom = True
@staticmethod
def _set_assumptions(obj, assumptions):
"""Set assumptions on obj, making sure to apply consistent values."""
tmp_asm_copy = assumptions.copy()
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
assumptions['commutative'] = is_commutative
obj._assumptions = StdFactKB(assumptions)
obj._assumptions._generator = tmp_asm_copy # Issue #8873
def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args):
from sympy.matrices.matrixbase import MatrixBase
from sympy.tensor.array.ndim_array import NDimArray
assumptions, kw_args = _filter_assumptions(kw_args)
if isinstance(label, str):
label = Symbol(label, **assumptions)
elif isinstance(label, Symbol):
assumptions = label._merge(assumptions)
elif isinstance(label, (MatrixBase, NDimArray)):
return label
elif isinstance(label, Iterable):
return _sympify(label)
else:
label = _sympify(label)
if is_sequence(shape):
shape = Tuple(*shape)
elif shape is not None:
shape = Tuple(shape)
if shape is not None:
obj = Expr.__new__(cls, label, shape)
else:
obj = Expr.__new__(cls, label)
obj._shape = shape
obj._offset = offset
obj._strides = strides
obj._name = str(label)
IndexedBase._set_assumptions(obj, assumptions)
return obj
@property
def name(self):
return self._name
def _hashable_content(self):
return super()._hashable_content() + tuple(sorted(self.assumptions0.items()))
@property
def assumptions0(self):
return {k: v for k, v in self._assumptions.items() if v is not None}
def __getitem__(self, indices, **kw_args):
if is_sequence(indices):
# Special case needed because M[*my_tuple] is a syntax error.
if self.shape and len(self.shape) != len(indices):
raise IndexException("Rank mismatch.")
return Indexed(self, *indices, **kw_args)
else:
if self.shape and len(self.shape) != 1:
raise IndexException("Rank mismatch.")
return Indexed(self, indices, **kw_args)
@property
def shape(self):
"""Returns the shape of the ``IndexedBase`` object.
Examples
========
>>> from sympy import IndexedBase, Idx
>>> from sympy.abc import x, y
>>> IndexedBase('A', shape=(x, y)).shape
(x, y)
Note: If the shape of the ``IndexedBase`` is specified, it will override
any shape information given by the indices.
>>> A = IndexedBase('A', shape=(x, y))
>>> B = IndexedBase('B')
>>> i = Idx('i', 2)
>>> j = Idx('j', 1)
>>> A[i, j].shape
(x, y)
>>> B[i, j].shape
(2, 1)
"""
return self._shape
@property
def strides(self):
"""Returns the strided scheme for the ``IndexedBase`` object.
Normally this is a tuple denoting the number of
steps to take in the respective dimension when traversing
an array. For code generation purposes strides='C' and
strides='F' can also be used.
strides='C' would mean that code printer would unroll
in row-major order and 'F' means unroll in column major
order.
"""
return self._strides
@property
def offset(self):
"""Returns the offset for the ``IndexedBase`` object.
This is the value added to the resulting index when the
2D Indexed object is unrolled to a 1D form. Used in code
generation.
Examples
==========
>>> from sympy.printing import ccode
>>> from sympy.tensor import IndexedBase, Idx
>>> from sympy import symbols
>>> l, m, n, o = symbols('l m n o', integer=True)
>>> A = IndexedBase('A', strides=(l, m, n), offset=o)
>>> i, j, k = map(Idx, 'ijk')
>>> ccode(A[i, j, k])
'A[l*i + m*j + n*k + o]'
"""
return self._offset
@property
def label(self):
"""Returns the label of the ``IndexedBase`` object.
Examples
========
>>> from sympy import IndexedBase
>>> from sympy.abc import x, y
>>> IndexedBase('A', shape=(x, y)).label
A
"""
return self.args[0]
def _sympystr(self, p):
return p.doprint(self.label)
| IndexedBase |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 18237,
"end": 18514
} | class ____(HashError):
"""A requirement had a hash specified but was not pinned to a specific
version."""
order = 3
head = (
"In --require-hashes mode, all requirements must have their "
"versions pinned with ==. These do not:"
)
| HashUnpinned |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 121763,
"end": 123626
} | class ____(GeneratedAirbyteSource):
class SignInViaPipedriveOAuth:
@public
def __init__(self, client_id: str, client_secret: str, refresh_token: str):
self.auth_type = "Client"
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client_secret, "client_secret")
self.refresh_token = check.str_param(refresh_token, "refresh_token")
class APIKeyAuthentication:
@public
def __init__(self, api_token: str):
self.auth_type = "Token"
self.api_token = check.str_param(api_token, "api_token")
@public
def __init__(
self,
name: str,
authorization: Union[
"PipedriveSource.SignInViaPipedriveOAuth", "PipedriveSource.APIKeyAuthentication"
],
replication_start_date: str,
):
"""Airbyte Source for Pipedrive.
Documentation can be found at https://docs.airbyte.com/integrations/sources/pipedrive
Args:
name (str): The name of the destination.
authorization (Union[PipedriveSource.SignInViaPipedriveOAuth, PipedriveSource.APIKeyAuthentication]): Choose one of the possible authorization method
replication_start_date (str): UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated. When specified and not None, then stream will behave as incremental
"""
self.authorization = check.inst_param(
authorization,
"authorization",
(PipedriveSource.SignInViaPipedriveOAuth, PipedriveSource.APIKeyAuthentication),
)
self.replication_start_date = check.str_param(
replication_start_date, "replication_start_date"
)
super().__init__("Pipedrive", name)
| PipedriveSource |
python | getsentry__sentry | tests/sentry/prevent/endpoints/test_organization_github_repos.py | {
"start": 49,
"end": 8075
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-prevent-github-repos"
method = "get"
def setUp(self):
self.organization = self.create_organization()
self.user = self.create_user()
self.create_member(organization=self.organization, user=self.user)
def test_get_prevent_github_repos_empty(self):
"""Test that the endpoint returns empty orgRepos when no GitHub integrations exist"""
self.login_as(user=self.user)
response = self.get_success_response(self.organization.slug)
assert response.data == {"orgRepos": []}
def test_get_prevent_github_repos_with_integration(self):
"""Test that the endpoint returns GitHub org data when integrations exist"""
self.login_as(user=self.user)
# Create a GitHub integration
integration = self.create_integration(
organization=self.organization,
provider="github",
name="test-github-org",
external_id="123456",
metadata={
"account_id": "987654",
"icon": "https://avatars.githubusercontent.com/u/123456",
"domain_name": "github.com/test-github-org",
},
)
# Create a project for the repository
project = self.create_project(organization=self.organization)
# Create a repository linked to this integration
self.create_repo(
project=project,
name="test-github-org/test-repo",
provider="integrations:github",
integration_id=integration.id,
external_id="111222",
)
response = self.get_success_response(self.organization.slug)
assert len(response.data["orgRepos"]) == 1
github_org = response.data["orgRepos"][0]
assert github_org["githubOrganizationId"] == "987654"
assert github_org["name"] == "test-github-org"
assert len(github_org["repos"]) == 1
repo_data = github_org["repos"][0]
assert repo_data["name"] == "test-repo"
assert repo_data["fullName"] == "test-github-org/test-repo"
assert repo_data["id"] == "111222"
def test_get_prevent_github_repos_multiple_orgs(self):
"""Test that multiple GitHub orgs are handled"""
self.login_as(user=self.user)
# Create two GitHub integrations
integration1 = self.create_integration(
organization=self.organization,
provider="github",
name="github-org-1",
external_id="123456",
metadata={"account_id": "987654"},
)
integration2 = self.create_integration(
organization=self.organization,
provider="github",
name="github-org-2",
external_id="789012",
metadata={"account_id": "345678"},
)
# Create projects and repos for both integrations
project = self.create_project(organization=self.organization)
self.create_repo(
project=project,
name="github-org-1/repo1",
provider="integrations:github",
integration_id=integration1.id,
external_id="111",
)
self.create_repo(
project=project,
name="github-org-2/repo2",
provider="integrations:github",
integration_id=integration2.id,
external_id="222",
)
response = self.get_success_response(self.organization.slug)
# Should return both GitHub orgs
assert len(response.data["orgRepos"]) == 2
# Verify both orgs have their respective repos
orgs_by_name = {org["name"]: org for org in response.data["orgRepos"]}
assert "github-org-1" in orgs_by_name
assert len(orgs_by_name["github-org-1"]["repos"]) == 1
assert orgs_by_name["github-org-1"]["repos"][0]["name"] == "repo1"
assert orgs_by_name["github-org-1"]["repos"][0]["id"] == "111"
assert "github-org-2" in orgs_by_name
assert len(orgs_by_name["github-org-2"]["repos"]) == 1
assert orgs_by_name["github-org-2"]["repos"][0]["name"] == "repo2"
assert orgs_by_name["github-org-2"]["repos"][0]["id"] == "222"
def test_get_prevent_github_repos_multiple_repos_same_org(self):
"""Test that multiple repositories for the same GitHub organization are all returned"""
self.login_as(user=self.user)
# Create one GitHub integration
integration = self.create_integration(
organization=self.organization,
provider="github",
name="github-org",
external_id="123456",
metadata={"account_id": "987654"},
)
# Create a project and multiple repos for the same integration
project = self.create_project(organization=self.organization)
self.create_repo(
project=project,
name="github-org/repo1",
provider="integrations:github",
integration_id=integration.id,
external_id="111",
)
self.create_repo(
project=project,
name="github-org/repo2",
provider="integrations:github",
integration_id=integration.id,
external_id="222",
)
self.create_repo(
project=project,
name="github-org/repo3",
provider="integrations:github",
integration_id=integration.id,
external_id="333",
)
response = self.get_success_response(self.organization.slug)
# Should return one GitHub org with three repos
assert len(response.data["orgRepos"]) == 1
github_org = response.data["orgRepos"][0]
assert github_org["name"] == "github-org"
assert len(github_org["repos"]) == 3
# Verify all three repos are present
repo_names = {repo["name"] for repo in github_org["repos"]}
assert repo_names == {"repo1", "repo2", "repo3"}
def test_get_prevent_github_repos_no_repos(self):
"""Test that the endpoint gracefully handles missing repos if integration exists but there are no repos"""
self.login_as(user=self.user)
# Create a GitHub integration but no repos
self.create_integration(
organization=self.organization,
provider="github",
name="test-github-org",
external_id="123456",
metadata={"account_id": "987654"},
)
response = self.get_success_response(self.organization.slug)
assert response.data == {"orgRepos": []}
def test_get_prevent_github_repos_seer_integration_account_id_is_number(self):
"""Test that the endpoint returns the correct orgRepos when account_id is a number"""
self.login_as(user=self.user)
integration = self.create_integration(
organization=self.organization,
provider="github",
name="test-github-org",
external_id="123456",
metadata={"account_id": 987654},
)
project = self.create_project(organization=self.organization)
self.create_repo(
project=project,
name="test-github-org/test-repo",
provider="integrations:github",
integration_id=integration.id,
external_id="111222",
)
response = self.get_success_response(self.organization.slug)
assert response.data == {
"orgRepos": [
{
"githubOrganizationId": "987654",
"name": "test-github-org",
"repos": [
{
"id": "111222",
"name": "test-repo",
"fullName": "test-github-org/test-repo",
}
],
}
]
}
| OrganizationPreventGitHubReposTest |
python | imageio__imageio | imageio/plugins/pillowmulti.py | {
"start": 247,
"end": 398
} | class ____(PillowFormat):
_modes = "i" # arg, why bother; people should use the tiffile version
_description = "TIFF format (Pillow)"
| TIFFFormat |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 24206,
"end": 24435
} | class ____:
"""Stores information about where a resource is used in a job."""
job_name: str
node_handles: list[NodeHandle]
@whitelist_for_serdes(storage_name="ExternalResourceData")
@record_custom
| ResourceJobUsageEntry |
python | huggingface__transformers | src/transformers/models/idefics/vision.py | {
"start": 12243,
"end": 12932
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIP->IdeficsVision
| IdeficsVisionMLP |
python | bottlepy__bottle | test/test_wsgi.py | {
"start": 7216,
"end": 7443
} | class ____:
def __init__(self, body):
self.body = body
self.close_events = []
def __iter__(self):
return iter(self.body)
def close(self):
self.close_events.append(True)
| CloseableBody |
python | ansible__ansible | lib/ansible/module_utils/_internal/_messages.py | {
"start": 3404,
"end": 3605
} | class ____(SummaryBase):
"""Warning summary with details (possibly derived from an exception __cause__ chain) and an optional traceback."""
@_dataclasses.dataclass(**_dataclass_kwargs)
| WarningSummary |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 5399,
"end": 7325
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, height, width, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
fpn_hidden_states (`tuple(torch.FloatTensor)`):
Tuple of `torch.FloatTensor` (one for each feature level, from high to low resolution) of shape
`(batch_size, hidden_size, height, width)`. Feature maps from the Feature Pyramid Network neck.
fpn_position_encoding (`tuple(torch.FloatTensor)`):
Tuple of `torch.FloatTensor` (one for each feature level, from high to low resolution) of shape
`(batch_size, hidden_size, height, width)`. Positional encodings corresponding to the `fpn_hidden_states`.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each stage) of shape `(batch_size, height, width, hidden_size)`. Hidden-states of the
model at the output of each stage.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
fpn_hidden_states: Optional[torch.FloatTensor] = None
fpn_position_encoding: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
| EdgeTamVideoVisionEncoderOutput |
python | ray-project__ray | python/ray/serve/tests/test_config_files/max_replicas_per_node.py | {
"start": 42,
"end": 119
} | class ____:
def __call__(self, *args):
return "hi"
app = D.bind()
| D |
python | ansible__ansible | lib/ansible/module_utils/facts/network/openbsd.py | {
"start": 845,
"end": 1439
} | class ____(GenericBsdIfconfigNetwork):
"""
This is the OpenBSD Network Class.
It uses the GenericBsdIfconfigNetwork.
"""
platform = 'OpenBSD'
# OpenBSD 'ifconfig -a' does not have information about aliases
def get_interfaces_info(self, ifconfig_path, ifconfig_options='-aA'):
return super(OpenBSDNetwork, self).get_interfaces_info(ifconfig_path, ifconfig_options)
# Return macaddress instead of lladdr
def parse_lladdr_line(self, words, current_if, ips):
current_if['macaddress'] = words[1]
current_if['type'] = 'ether'
| OpenBSDNetwork |
python | django__django | tests/queries/models.py | {
"start": 1160,
"end": 1376
} | class ____(models.Model):
name = models.CharField(max_length=10)
tag = models.ForeignKey(Tag, models.CASCADE)
notes = models.ManyToManyField(Note)
def __str__(self):
return self.name
| Annotation |
python | numba__numba | numba/tests/test_pythonapi.py | {
"start": 2673,
"end": 3935
} | class ____(unittest.TestCase):
def test_empty_args(self):
def callme(**kwargs):
print("callme", kwargs)
@intrinsic
def py_call(tyctx):
def codegen(context, builder, sig, args):
pyapi = context.get_python_api(builder)
gil = pyapi.gil_ensure()
num = pyapi.long_from_longlong(
context.get_constant(types.intp, 0xCAFE)
)
kwds = pyapi.dict_pack({"key": num}.items())
fn_print = pyapi.unserialize(pyapi.serialize_object(callme))
# segfault: https://github.com/numba/numba/issues/5871
res = pyapi.call(fn_print, None, kwds)
pyapi.decref(res)
pyapi.decref(fn_print)
pyapi.decref(kwds)
pyapi.decref(num)
pyapi.gil_release(gil)
return res
return types.none(), codegen
@njit
def foo():
py_call()
with captured_stdout() as out:
foo()
d = {"key": 0xCAFE}
expected = f"callme {d}\n"
self.assertEqual(out.getvalue(), expected)
if __name__ == '__main__':
unittest.main()
| PythonAPIEmptyArgs |
python | openai__openai-python | src/openai/types/realtime/realtime_mcphttp_error_param.py | {
"start": 225,
"end": 377
} | class ____(TypedDict, total=False):
code: Required[int]
message: Required[str]
type: Required[Literal["http_error"]]
| RealtimeMcphttpErrorParam |
python | pydata__xarray | xarray/groupers.py | {
"start": 16154,
"end": 26178
} | class ____(Resampler):
"""
Grouper object specialized to resampling the time coordinate.
Attributes
----------
freq : str, datetime.timedelta, pandas.Timestamp, or pandas.DateOffset
Frequency to resample to. See `Pandas frequency
aliases <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`_
for a list of possible values.
closed : {"left", "right"}, optional
Side of each interval to treat as closed.
label : {"left", "right"}, optional
Side of each interval to use for labeling.
origin : {'epoch', 'start', 'start_day', 'end', 'end_day'}, pandas.Timestamp, datetime.datetime, numpy.datetime64, or cftime.datetime, default 'start_day'
The datetime on which to adjust the grouping. The timezone of origin
must match the timezone of the index.
If a datetime is not used, these values are also supported:
- 'epoch': `origin` is 1970-01-01
- 'start': `origin` is the first value of the timeseries
- 'start_day': `origin` is the first day at midnight of the timeseries
- 'end': `origin` is the last value of the timeseries
- 'end_day': `origin` is the ceiling midnight of the last day
offset : pd.Timedelta, datetime.timedelta, or str, default is None
An offset timedelta added to the origin.
"""
freq: ResampleCompatible
closed: SideOptions | None = field(default=None)
label: SideOptions | None = field(default=None)
origin: str | DatetimeLike = field(default="start_day")
offset: pd.Timedelta | datetime.timedelta | str | None = field(default=None)
index_grouper: CFTimeGrouper | pd.Grouper = field(init=False, repr=False)
group_as_index: pd.Index = field(init=False, repr=False)
def reset(self) -> Self:
return type(self)(
freq=self.freq,
closed=self.closed,
label=self.label,
origin=self.origin,
offset=self.offset,
)
def _init_properties(self, group: T_Group) -> None:
group_as_index = safe_cast_to_index(group)
offset = self.offset
if not group_as_index.is_monotonic_increasing:
# TODO: sort instead of raising an error
raise ValueError("Index must be monotonic for resampling")
if isinstance(group_as_index, CFTimeIndex):
self.index_grouper = CFTimeGrouper(
freq=self.freq,
closed=self.closed,
label=self.label,
origin=self.origin,
offset=offset,
)
else:
if isinstance(self.freq, BaseCFTimeOffset):
raise ValueError(
"'BaseCFTimeOffset' resample frequencies are only supported "
"when resampling a 'CFTimeIndex'"
)
self.index_grouper = pd.Grouper(
# TODO remove once requiring pandas >= 2.2
freq=_new_to_legacy_freq(self.freq),
closed=self.closed,
label=self.label,
origin=self.origin,
offset=offset,
)
self.group_as_index = group_as_index
def _get_index_and_items(self) -> tuple[pd.Index, pd.Series, np.ndarray]:
first_items, codes = self.first_items()
full_index = first_items.index
if first_items.isnull().any():
first_items = first_items.dropna()
full_index = full_index.rename("__resample_dim__")
return full_index, first_items, codes
def first_items(self) -> tuple[pd.Series, np.ndarray]:
if isinstance(self.index_grouper, CFTimeGrouper):
return self.index_grouper.first_items(
cast(CFTimeIndex, self.group_as_index)
)
else:
s = pd.Series(np.arange(self.group_as_index.size), self.group_as_index)
grouped = s.groupby(self.index_grouper)
first_items = grouped.first()
counts = grouped.count()
# This way we generate codes for the final output index: full_index.
# So for _flox_reduce we avoid one reindex and copy by avoiding
# _maybe_reindex
codes = np.repeat(np.arange(len(first_items)), counts)
return first_items, codes
def factorize(self, group: T_Group) -> EncodedGroups:
self._init_properties(group)
full_index, first_items, codes_ = self._get_index_and_items()
sbins = first_items.values.astype(np.int64)
group_indices: GroupIndices = tuple(
list(itertools.starmap(slice, pairwise(sbins))) + [slice(sbins[-1], None)]
)
unique_coord = Variable(
dims=group.name, data=first_items.index, attrs=group.attrs
)
codes = group.copy(data=codes_.reshape(group.shape), deep=False)
return EncodedGroups(
codes=codes,
group_indices=group_indices,
full_index=full_index,
unique_coord=unique_coord,
coords=coordinates_from_variable(unique_coord),
)
def compute_chunks(self, variable: Variable, *, dim: Hashable) -> tuple[int, ...]:
"""
Compute chunk sizes for this time resampler.
This method is used during chunking operations to determine appropriate
chunk sizes for the given variable when using this resampler.
Parameters
----------
name : Hashable
The name of the dimension being chunked.
variable : Variable
The variable being chunked.
Returns
-------
tuple[int, ...]
A tuple of chunk sizes for the dimension.
"""
if not _contains_datetime_like_objects(variable):
raise ValueError(
f"Computing chunks with {type(self)!r} only supported for datetime variables. "
f"Received variable with dtype {variable.dtype!r} instead."
)
chunks = (
DataArray(
np.ones(variable.shape, dtype=int),
dims=(dim,),
coords={dim: variable},
)
.resample({dim: self})
.sum()
)
# When bins (binning) or time periods are missing (resampling)
# we can end up with NaNs. Drop them.
if chunks.dtype.kind == "f":
chunks = chunks.dropna(dim).astype(int)
chunks_tuple: tuple[int, ...] = tuple(chunks.data.tolist())
return chunks_tuple
def _factorize_given_labels(data: np.ndarray, labels: np.ndarray) -> np.ndarray:
# Copied from flox
sorter = np.argsort(labels)
is_sorted = array_all(sorter == np.arange(sorter.size))
codes = np.searchsorted(labels, data, sorter=sorter)
mask = ~np.isin(data, labels) | isnull(data) | (codes == len(labels))
# codes is the index in to the sorted array.
# if we didn't want sorting, unsort it back
if not is_sorted:
codes[codes == len(labels)] = -1
codes = sorter[(codes,)]
codes[mask] = -1
return codes
def unique_value_groups(
ar, sort: bool = True
) -> tuple[np.ndarray | pd.Index, np.ndarray]:
"""Group an array by its unique values.
Parameters
----------
ar : array-like
Input array. This will be flattened if it is not already 1-D.
sort : bool, default: True
Whether or not to sort unique values.
Returns
-------
values : np.ndarray
Sorted, unique values as returned by `np.unique`.
indices : list of lists of int
Each element provides the integer indices in `ar` with values given by
the corresponding value in `unique_values`.
"""
inverse, values = pd.factorize(ar, sort=sort)
if isinstance(values, pd.MultiIndex):
values.names = ar.names
return values, inverse
def season_to_month_tuple(seasons: Sequence[str]) -> tuple[tuple[int, ...], ...]:
"""
>>> season_to_month_tuple(["DJF", "MAM", "JJA", "SON"])
((12, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
>>> season_to_month_tuple(["DJFM", "MAMJ", "JJAS", "SOND"])
((12, 1, 2, 3), (3, 4, 5, 6), (6, 7, 8, 9), (9, 10, 11, 12))
>>> season_to_month_tuple(["DJFM", "SOND"])
((12, 1, 2, 3), (9, 10, 11, 12))
"""
initials = "JFMAMJJASOND"
starts = {
"".join(s): i + 1
for s, i in zip(sliding_window(2, initials + "J"), range(12), strict=True)
}
result: list[tuple[int, ...]] = []
for i, season in enumerate(seasons):
if len(season) == 1:
if i < len(seasons) - 1:
suffix = seasons[i + 1][0]
else:
suffix = seasons[0][0]
else:
suffix = season[1]
start = starts[season[0] + suffix]
month_append = []
for i in range(len(season[1:])):
elem = start + i + 1
month_append.append(elem - 12 * (elem > 12))
result.append((start,) + tuple(month_append))
return tuple(result)
def inds_to_season_string(asints: tuple[tuple[int, ...], ...]) -> tuple[str, ...]:
inits = "JFMAMJJASOND"
return tuple("".join([inits[i_ - 1] for i_ in t]) for t in asints)
def is_sorted_periodic(lst):
"""Used to verify that seasons provided to SeasonResampler are in order."""
n = len(lst)
# Find the wraparound point where the list decreases
wrap_point = -1
for i in range(1, n):
if lst[i] < lst[i - 1]:
wrap_point = i
break
# If no wraparound point is found, the list is already sorted
if wrap_point == -1:
return True
# Check if both parts around the wrap point are sorted
for i in range(1, wrap_point):
if lst[i] < lst[i - 1]:
return False
for i in range(wrap_point + 1, n):
if lst[i] < lst[i - 1]:
return False
# Check wraparound condition
return lst[-1] <= lst[0]
@dataclass(kw_only=True, frozen=True)
| TimeResampler |
python | readthedocs__readthedocs.org | readthedocs/gold/migrations/0001_initial.py | {
"start": 133,
"end": 2573
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("projects", "__first__"),
]
operations = [
migrations.CreateModel(
name="GoldUser",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"pub_date",
models.DateTimeField(auto_now_add=True, verbose_name="Publication date"),
),
(
"modified_date",
models.DateTimeField(auto_now=True, verbose_name="Modified date"),
),
(
"level",
models.CharField(
default=b"supporter",
max_length=20,
verbose_name="Level",
choices=[
(b"v1-org-5", b"$5/mo"),
(b"v1-org-10", b"$10/mo"),
(b"v1-org-15", b"$15/mo"),
(b"v1-org-20", b"$20/mo"),
(b"v1-org-50", b"$50/mo"),
(b"v1-org-100", b"$100/mo"),
],
),
),
("last_4_digits", models.CharField(max_length=4)),
("stripe_id", models.CharField(max_length=255)),
("subscribed", models.BooleanField(default=False)),
(
"projects",
models.ManyToManyField(
related_name="gold_owners",
verbose_name="Projects",
to="projects.Project",
),
),
(
"user",
models.ForeignKey(
related_name="gold",
verbose_name="User",
to=settings.AUTH_USER_MODEL,
unique=True,
on_delete=models.CASCADE,
),
),
],
),
]
| Migration |
python | sphinx-doc__sphinx | sphinx/domains/cpp/__init__.py | {
"start": 32595,
"end": 48326
} | class ____(Domain):
"""C++ language domain.
There are two 'object type' attributes being used::
- Each object created from directives gets an assigned .objtype from ObjectDescription.run.
This is simply the directive name.
- Each declaration (see the distinction in the directives dict below) has a nested .ast of
type ASTDeclaration. That object has .objectType which corresponds to the keys in the
object_types dict below. They are the core different types of declarations in C++ that
one can document.
"""
name = 'cpp'
label = 'C++'
object_types = {
'class': ObjType(_('class'), 'class', 'struct', 'identifier', 'type'),
'union': ObjType(_('union'), 'union', 'identifier', 'type'),
'function': ObjType(_('function'), 'func', 'identifier', 'type'),
'member': ObjType(_('member'), 'member', 'var', 'identifier'),
'type': ObjType(_('type'), 'identifier', 'type'),
'concept': ObjType(_('concept'), 'concept', 'identifier'),
'enum': ObjType(_('enum'), 'enum', 'identifier', 'type'),
'enumerator': ObjType(_('enumerator'), 'enumerator', 'identifier'),
# generated object types
'functionParam': ObjType(
_('function parameter'), 'identifier', 'member', 'var'
),
'templateParam': ObjType(
_('template parameter'),
'identifier',
'class',
'struct',
'union',
'member',
'var',
'type',
),
}
directives = {
# declarations
'class': CPPClassObject,
'struct': CPPClassObject,
'union': CPPUnionObject,
'function': CPPFunctionObject,
'member': CPPMemberObject,
'var': CPPMemberObject,
'type': CPPTypeObject,
'concept': CPPConceptObject,
'enum': CPPEnumObject,
'enum-struct': CPPEnumObject,
'enum-class': CPPEnumObject,
'enumerator': CPPEnumeratorObject,
# scope control
'namespace': CPPNamespaceObject,
'namespace-push': CPPNamespacePushObject,
'namespace-pop': CPPNamespacePopObject,
# other
'alias': CPPAliasObject,
}
roles = {
'any': CPPXRefRole(),
'class': CPPXRefRole(),
'struct': CPPXRefRole(),
'union': CPPXRefRole(),
'func': CPPXRefRole(fix_parens=True),
'member': CPPXRefRole(),
'var': CPPXRefRole(),
'type': CPPXRefRole(),
'concept': CPPXRefRole(),
'enum': CPPXRefRole(),
'enumerator': CPPXRefRole(),
'expr': CPPExprRole(asCode=True),
'texpr': CPPExprRole(asCode=False),
}
initial_data = {
'root_symbol': Symbol(None, None, None, None, None, None, None),
'names': {}, # full name for indexing -> docname
}
def clear_doc(self, docname: str) -> None:
if Symbol.debug_show_tree:
logger.debug('clear_doc: %s', docname)
logger.debug('\tbefore:')
logger.debug(self.data['root_symbol'].dump(1))
logger.debug('\tbefore end')
root_symbol = self.data['root_symbol']
root_symbol.clear_doc(docname)
if Symbol.debug_show_tree:
logger.debug('\tafter:')
logger.debug(self.data['root_symbol'].dump(1))
logger.debug('\tafter end')
logger.debug('clear_doc end: %s', docname)
for name, n_docname in list(self.data['names'].items()):
if n_docname == docname:
del self.data['names'][name]
def process_doc(
self, env: BuildEnvironment, docname: str, document: nodes.document
) -> None:
if Symbol.debug_show_tree:
logger.debug('process_doc: %s', docname)
logger.debug(self.data['root_symbol'].dump(0))
logger.debug('process_doc end: %s', docname)
def process_field_xref(self, pnode: pending_xref) -> None:
pnode.attributes.update(self.env.ref_context)
def merge_domaindata(self, docnames: Set[str], otherdata: dict[str, Any]) -> None:
if Symbol.debug_show_tree:
logger.debug('merge_domaindata:')
logger.debug('\tself:')
logger.debug(self.data['root_symbol'].dump(1))
logger.debug('\tself end')
logger.debug('\tother:')
logger.debug(otherdata['root_symbol'].dump(1))
logger.debug('\tother end')
self.data['root_symbol'].merge_with(
otherdata['root_symbol'], docnames, self.env
)
our_names = self.data['names']
for name, docname in otherdata['names'].items():
if docname in docnames:
if name not in our_names:
our_names[name] = docname
# no need to warn on duplicates, the symbol merge already does that
if Symbol.debug_show_tree:
logger.debug('\tresult:')
logger.debug(self.data['root_symbol'].dump(1))
logger.debug('\tresult end')
logger.debug('merge_domaindata end')
def _check_type(self, typ: str, decl_typ: str) -> bool:
if typ == 'any':
return True
objtypes = self.objtypes_for_role(typ)
if objtypes:
return decl_typ in objtypes
logger.debug(f'Type is {typ}, declaration type is {decl_typ}') # NoQA: G004
raise AssertionError
def _resolve_xref_inner(
self,
env: BuildEnvironment,
fromdocname: str,
builder: Builder,
typ: str,
target: str,
node: pending_xref,
contnode: Element,
) -> tuple[nodes.reference, str] | tuple[None, None]:
# add parens again for those that could be functions
if typ in {'any', 'func'}:
target += '()'
parser = DefinitionParser(target, location=node, config=env.config)
try:
ast, is_shorthand = parser.parse_xref_object()
except DefinitionError as e:
if typ in {'any', 'func'}:
# hax on top of the paren hax to try to get correct errors
parser2 = DefinitionParser(
target[:-2], location=node, config=env.config
)
try:
parser2.parse_xref_object()
except DefinitionError as e2:
target = target[:-2]
ex = e2
else:
# strange, that we don't get the error now, use the original
ex = e
else:
ex = e
logger.warning(
'Unparseable C++ cross-reference: %r\n%s', target, ex, location=node
)
return None, None
parent_key: LookupKey | None = node.get('cpp:parent_key', None)
root_symbol = self.data['root_symbol']
if parent_key:
parent_symbol: Symbol = root_symbol.direct_lookup(parent_key)
if not parent_symbol:
logger.debug('Target: %s', target)
logger.debug('ParentKey: %s', parent_key.data)
logger.debug(root_symbol.dump(1))
assert parent_symbol # should be there
else:
parent_symbol = root_symbol
if is_shorthand:
assert isinstance(ast, ASTNamespace)
ns = ast
name = ns.nestedName
if ns.templatePrefix:
template_decls = ns.templatePrefix.templates
else:
template_decls = []
# let's be conservative with the sibling lookup for now
search_in_siblings = (not name.rooted) and len(name.names) == 1
symbols, fail_reason = parent_symbol.find_name(
name,
template_decls,
typ,
templateShorthand=True,
matchSelf=True,
recurseInAnon=True,
searchInSiblings=search_in_siblings,
)
if symbols is None:
if typ == 'identifier':
if fail_reason == 'templateParamInQualified':
# this is an xref we created as part of a signature,
# so don't warn for names nested in template parameters
raise NoUri(str(name), typ)
s = None
else:
# just refer to the arbitrarily first symbol
s = symbols[0]
else:
assert isinstance(ast, ASTDeclaration)
decl = ast
name = decl.name
s = parent_symbol.find_declaration(
decl, typ, templateShorthand=True, matchSelf=True, recurseInAnon=True
)
if s is None or s.declaration is None:
txt_name = str(name)
if txt_name.startswith('std::') or txt_name == 'std':
raise NoUri(txt_name, typ)
return None, None
typ = typ.removeprefix('cpp:')
decl_typ = s.declaration.objectType
if not self._check_type(typ, decl_typ):
logger.warning(
'cpp:%s targets a %s (%s).',
typ,
s.declaration.objectType,
s.get_full_nested_name(),
location=node,
)
declaration = s.declaration
if is_shorthand:
full_nested_name = s.get_full_nested_name()
display_name = full_nested_name.get_display_string().lstrip(':')
else:
display_name = decl.get_display_string()
docname = s.docname
assert docname
# the non-identifier refs are cross-references, which should be processed:
# - fix parenthesis due to operator() and add_function_parentheses
if typ != 'identifier':
title = contnode.pop(0).astext()
# If it's operator(), we need to add '()' if explicit function parens
# are requested. Then the Sphinx machinery will add another pair.
# Also, if it's an 'any' ref that resolves to a function, we need to add
# parens as well.
# However, if it's a non-shorthand function ref, for a function that
# takes no arguments, then we may need to add parens again as well.
add_paren = 0
if (
not node.get('refexplicit', False)
and declaration.objectType == 'function'
):
if is_shorthand:
# this is just the normal haxing for 'any' roles
if env.config.add_function_parentheses and typ == 'any':
add_paren += 1
# and now this stuff for operator()
if (
env.config.add_function_parentheses
and typ == 'func'
and title.endswith('operator()')
):
add_paren += 1
if (
typ in {'any', 'func'}
and title.endswith('operator')
and display_name.endswith('operator()')
):
add_paren += 1
else:
# our job here is to essentially nullify add_function_parentheses
if env.config.add_function_parentheses:
if typ == 'any' and display_name.endswith('()'):
add_paren += 1
elif typ == 'func':
if not display_name.endswith('()'):
title = title.removesuffix('()')
else:
if display_name.endswith('()'):
add_paren += 1
if add_paren > 0:
title += '()' * add_paren
# and reconstruct the title again
contnode += nodes.Text(title)
res = (
make_refnode(
builder,
fromdocname,
docname,
declaration.get_newest_id(),
contnode,
display_name,
),
declaration.objectType,
)
return res
def resolve_xref(
self,
env: BuildEnvironment,
fromdocname: str,
builder: Builder,
typ: str,
target: str,
node: pending_xref,
contnode: Element,
) -> nodes.reference | None:
return self._resolve_xref_inner(
env, fromdocname, builder, typ, target, node, contnode
)[0]
def resolve_any_xref(
self,
env: BuildEnvironment,
fromdocname: str,
builder: Builder,
target: str,
node: pending_xref,
contnode: Element,
) -> list[tuple[str, nodes.reference]]:
with logging.suppress_logging():
retnode, objtype = self._resolve_xref_inner(
env, fromdocname, builder, 'any', target, node, contnode
)
if retnode:
if objtype == 'templateParam':
return [('cpp:templateParam', retnode)]
else:
return [('cpp:' + self.role_for_objtype(objtype), retnode)]
return []
def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]:
root_symbol = self.data['root_symbol']
for symbol in root_symbol.get_all_symbols():
if symbol.declaration is None:
continue
assert symbol.docname
full_nested_name = symbol.get_full_nested_name()
name = str(full_nested_name).lstrip(':')
dispname = full_nested_name.get_display_string().lstrip(':')
object_type = symbol.declaration.objectType
docname = symbol.docname
newest_id = symbol.declaration.get_newest_id()
yield name, dispname, object_type, docname, newest_id, 1
def get_full_qualified_name(self, node: Element) -> str | None:
target = node.get('reftarget', None)
if target is None:
return None
parent_key: LookupKey | None = node.get('cpp:parent_key', None)
if parent_key is None or len(parent_key.data) <= 0:
return None
root_symbol = self.data['root_symbol']
parent_symbol = root_symbol.direct_lookup(parent_key)
parent_name = parent_symbol.get_full_nested_name()
return f'{parent_name}::{target}'
def _init_stuff(app: Sphinx) -> None:
Symbol.debug_lookup = app.config.cpp_debug_lookup
Symbol.debug_show_tree = app.config.cpp_debug_show_tree
app.config.cpp_index_common_prefix.sort(reverse=True)
def setup(app: Sphinx) -> ExtensionMetadata:
app.add_domain(CPPDomain)
app.add_config_value('cpp_index_common_prefix', [], 'env', types=frozenset({list}))
app.add_config_value('cpp_id_attributes', [], 'env', types=frozenset({list, tuple}))
app.add_config_value(
'cpp_paren_attributes', [], 'env', types=frozenset({list, tuple})
)
app.add_config_value(
'cpp_maximum_signature_line_length',
None,
'env',
types=frozenset({int, NoneType}),
)
app.add_post_transform(AliasTransform)
# debug stuff
app.add_config_value('cpp_debug_lookup', False, '', types=frozenset({bool}))
app.add_config_value('cpp_debug_show_tree', False, '', types=frozenset({bool}))
app.connect('builder-inited', _init_stuff)
return {
'version': 'builtin',
'env_version': 9,
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| CPPDomain |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_task_runs.py | {
"start": 35984,
"end": 36545
} | class ____:
async def test_history_interval_must_be_one_second_or_larger(self, client):
response = await client.post(
"/task_runs/history",
json=dict(
history_start=str(now_fn("UTC")),
history_end=str(now_fn("UTC") + datetime.timedelta(days=1)),
history_interval_seconds=0.9,
),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
assert b"History interval must not be less than 1 second" in response.content
| TestTaskRunHistory |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/connectors/test_callback_connector.py | {
"start": 13479,
"end": 14388
} | class ____(Callback):
@property
def state_key(self):
return "same_key" # Same key as ConflictingCallback
def state_dict(self):
return {"state": 3}
@pytest.mark.parametrize(
("callbacks", "match_msg"),
[
(
[ConflictingCallback(), ConflictingCallback()],
"Found more than one stateful callback of type `ConflictingCallback`",
),
(
[ConflictingCallback(), Callback(), ConflictingCallback()],
"Found more than one stateful callback of type `ConflictingCallback`",
),
([ConflictingCallback(), AnotherConflictingCallback()], "Found more than one stateful callback"),
],
)
def test_raising_error_validate_callbacks_list_function(callbacks: list, match_msg: str):
with pytest.raises(RuntimeError, match=match_msg):
_validate_callbacks_list(callbacks)
| AnotherConflictingCallback |
python | aimacode__aima-python | reinforcement_learning.py | {
"start": 135,
"end": 2485
} | class ____:
"""
Passive (non-learning) agent that uses direct utility estimation
on a given MDP and policy.
import sys
from mdp import sequential_decision_environment
north = (0, 1)
south = (0,-1)
west = (-1, 0)
east = (1, 0)
policy = {(0, 2): east, (1, 2): east, (2, 2): east, (3, 2): None, (0, 1): north, (2, 1): north,
(3, 1): None, (0, 0): north, (1, 0): west, (2, 0): west, (3, 0): west,}
agent = PassiveDUEAgent(policy, sequential_decision_environment)
for i in range(200):
run_single_trial(agent,sequential_decision_environment)
agent.estimate_U()
agent.U[(0, 0)] > 0.2
True
"""
def __init__(self, pi, mdp):
self.pi = pi
self.mdp = mdp
self.U = {}
self.s = None
self.a = None
self.s_history = []
self.r_history = []
self.init = mdp.init
def __call__(self, percept):
s1, r1 = percept
self.s_history.append(s1)
self.r_history.append(r1)
##
##
if s1 in self.mdp.terminals:
self.s = self.a = None
else:
self.s, self.a = s1, self.pi[s1]
return self.a
def estimate_U(self):
# this function can be called only if the MDP has reached a terminal state
# it will also reset the mdp history
assert self.a is None, 'MDP is not in terminal state'
assert len(self.s_history) == len(self.r_history)
# calculating the utilities based on the current iteration
U2 = {s: [] for s in set(self.s_history)}
for i in range(len(self.s_history)):
s = self.s_history[i]
U2[s] += [sum(self.r_history[i:])]
U2 = {k: sum(v) / max(len(v), 1) for k, v in U2.items()}
# resetting history
self.s_history, self.r_history = [], []
# setting the new utilities to the average of the previous
# iteration and this one
for k in U2.keys():
if k in self.U.keys():
self.U[k] = (self.U[k] + U2[k]) / 2
else:
self.U[k] = U2[k]
return self.U
def update_state(self, percept):
"""To be overridden in most cases. The default case
assumes the percept to be of type (state, reward)"""
return percept
| PassiveDUEAgent |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 8504,
"end": 12460
} | class ____(_MaxPoolNd):
r"""Applies a 3D max pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
can be precisely described as:
.. math::
\begin{aligned}
\text{out}(N_i, C_j, d, h, w) ={} & \max_{k=0, \ldots, kD-1} \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
& \text{input}(N_i, C_j, \text{stride[0]} \times d + k,
\text{stride[1]} \times h + m, \text{stride[2]} \times w + n)
\end{aligned}
If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
Note:
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
or the input. Sliding windows that would start in the right padded region are ignored.
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
- a single ``int`` -- in which case the same value is used for the depth, height and width dimension
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
the second `int` for the height dimension and the third `int` for the width dimension
Args:
kernel_size: the size of the window to take a max over
stride: the stride of the window. Default value is :attr:`kernel_size`
padding: Implicit negative infinity padding to be added on all three sides
dilation: a parameter that controls the stride of elements in the window
return_indices: if ``True``, will return the max indices along with the outputs.
Useful for :class:`torch.nn.MaxUnpool3d` later
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
Shape:
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where
.. math::
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times
(\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times
(\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
.. math::
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] \times
(\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
Examples::
>>> # pool of square window of size=3, stride=2
>>> m = nn.MaxPool3d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2))
>>> input = torch.randn(20, 16, 50, 44, 31)
>>> output = m(input)
.. _link:
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
"""
kernel_size: _size_3_t
stride: _size_3_t
padding: _size_3_t
dilation: _size_3_t
def forward(self, input: Tensor):
"""Runs the forward pass."""
return F.max_pool3d(
input,
self.kernel_size,
self.stride,
self.padding,
self.dilation,
ceil_mode=self.ceil_mode,
return_indices=self.return_indices,
)
| MaxPool3d |
python | walkccc__LeetCode | solutions/229. Majority Element II/229.py | {
"start": 0,
"end": 493
} | class ____:
def majorityElement(self, nums: list[int]) -> list[int]:
ans1 = 0
ans2 = 1
count1 = 0
count2 = 0
for num in nums:
if num == ans1:
count1 += 1
elif num == ans2:
count2 += 1
elif count1 == 0:
ans1 = num
count1 = 1
elif count2 == 0:
ans2 = num
count2 = 1
else:
count1 -= 1
count2 -= 1
return [ans for ans in (ans1, ans2) if nums.count(ans) > len(nums) // 3]
| Solution |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 57927,
"end": 58160
} | class ____(BaseModel):
"""
Pool Collection serializer for responses.
"""
pools: Annotated[list[PoolResponse], Field(title="Pools")]
total_entries: Annotated[int, Field(title="Total Entries")]
| PoolCollectionResponse |
python | django__django | tests/staticfiles_tests/test_storage.py | {
"start": 16466,
"end": 17951
} | class ____(CollectionTestCase):
def setUp(self):
storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
super().setUp()
def cached_file_path(self, path):
fullpath = self.render_template(self.static_template_snippet(path))
return fullpath.replace(settings.STATIC_URL, "")
def test_multi_extension_patterns(self):
"""
With storage classes having several file extension patterns, only the
files matching a specific file pattern should be affected by the
substitution (#19670).
"""
# CSS files shouldn't be touched by JS patterns.
relpath = self.cached_file_path("cached/import.css")
self.assertEqual(relpath, "cached/import.f53576679e5a.css")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read())
# Confirm JS patterns have been applied to JS files.
relpath = self.cached_file_path("cached/test.js")
self.assertEqual(relpath, "cached/test.388d7a790d46.js")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read())
@override_settings(
STORAGES={
**settings.STORAGES,
STATICFILES_STORAGE_ALIAS: {
"BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage",
},
}
)
| TestExtraPatternsStorage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 283728,
"end": 284178
} | class ____(sgqlc.types.Input):
"""Ordering options for repository connections"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(RepositoryOrderField), graphql_name="field")
"""The field to order repositories by."""
direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction")
"""The ordering direction."""
| RepositoryOrder |
python | PyCQA__flake8 | src/flake8/statistics.py | {
"start": 2215,
"end": 3387
} | class ____(NamedTuple):
"""Simple key structure for the Statistics dictionary.
To make things clearer, easier to read, and more understandable, we use a
namedtuple here for all Keys in the underlying dictionary for the
Statistics object.
"""
filename: str
code: str
@classmethod
def create_from(cls, error: Violation) -> Key:
"""Create a Key from :class:`flake8.violation.Violation`."""
return cls(filename=error.filename, code=error.code)
def matches(self, prefix: str, filename: str | None) -> bool:
"""Determine if this key matches some constraints.
:param prefix:
The error code prefix that this key's error code should start with.
:param filename:
The filename that we potentially want to match on. This can be
None to only match on error prefix.
:returns:
True if the Key's code starts with the prefix and either filename
is None, or the Key's filename matches the value passed in.
"""
return self.code.startswith(prefix) and (
filename is None or self.filename == filename
)
| Key |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 46736,
"end": 47296
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("discussion_id", "reply_to_id", "body", "client_mutation_id")
discussion_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="discussionId"
)
reply_to_id = sgqlc.types.Field(ID, graphql_name="replyToId")
body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| AddDiscussionCommentInput |
python | streamlit__streamlit | lib/tests/streamlit/delta_generator_test.py | {
"start": 12969,
"end": 13553
} | class ____(DeltaGeneratorTestCase):
"""Test DeltaGenerator Container."""
def test_container(self):
container = st.container()
assert isinstance(container, DeltaGenerator)
assert not container._cursor.is_locked
def test_container_paths(self):
level3 = st.container().container().container()
level3.markdown("hi")
level3.markdown("bye")
msg = self.get_message_from_queue()
assert (
make_delta_path(RootContainer.MAIN, (0, 0, 0), 1) == msg.metadata.delta_path
)
| DeltaGeneratorContainerTest |
python | apache__airflow | dev/assign_cherry_picked_prs_with_milestone.py | {
"start": 5894,
"end": 13594
} | class ____(NamedTuple):
"""Stores details about commits"""
full_hash: str
short_hash: str
date: str
message: str
message_without_backticks: str
pr: int | None
def get_change_from_line(line: str) -> Change:
split_line = line.split(" ", maxsplit=3)
message = split_line[3]
pr = None
pr_match = PR_PATTERN.match(message)
if pr_match:
pr = pr_match.group(1)
return Change(
full_hash=split_line[0],
short_hash=split_line[1],
date=split_line[2],
message=message,
message_without_backticks=message.replace("`", "'").replace("'", "'").replace("&", "&"),
pr=int(pr) if pr else None,
)
def get_changes(verbose: bool, previous_release: str, current_release: str) -> list[Change]:
change_strings = subprocess.check_output(
get_git_log_command(verbose, from_commit=previous_release, to_commit=current_release),
cwd=SOURCE_DIR_PATH,
text=True,
)
return [get_change_from_line(line) for line in change_strings.splitlines()]
def update_milestone(r: Repository, pr: PullRequest, m: Milestone):
# PR in GitHub API does not have a way to update milestone. It should be opened as issue,
# and then it can be updated ¯\_(ツ)_/¯
r.get_issue(pr.number).edit(milestone=m)
@cli.command()
@option_github_token
@option_previous_release
@option_current_release
@option_verbose
@option_limit_pr_count
@option_dry_run
@option_milestone_number
@option_skip_assigned
@option_print_summary
@option_assume_yes
@option_output_folder
def assign_prs(
github_token: str,
previous_release: str,
current_release: str,
verbose: bool,
limit_pr_count: int | None,
dry_run: bool,
milestone_number: int,
skip_assigned: bool,
print_summary: bool,
assume_yes: bool,
output_folder: str,
):
changes = get_changes(verbose, previous_release, current_release)
changes = [change for change in changes if change.pr is not None]
g = Github(github_token)
repo = g.get_repo("apache/airflow")
if output_folder and not print_summary:
console.print("\n[yellow]Implying --print-summary as output folder is enabled[/]\n")
print_summary = True
if print_summary and not skip_assigned:
console.print("\n[yellow]Implying --skip-assigned as summary report is enabled[/]\n")
skip_assigned = True
milestone = repo.get_milestone(milestone_number)
count_prs = limit_pr_count or len(changes)
console.print(f"\n[green]Applying Milestone: {milestone.title} to {count_prs} merged PRs[/]\n")
if dry_run:
console.print("[yellow]Dry run mode![/]\n")
else:
if not assume_yes and not Confirm.ask("Is this OK?"):
sys.exit(1)
doc_only_label = repo.get_label(TYPE_DOC_ONLY_LABEL)
changelog_skip_label = repo.get_label(CHANGELOG_SKIP_LABEL)
changelog_changes: list[Change] = []
doc_only_changes: list[Change] = []
excluded_changes: list[Change] = []
for change in changes[:count_prs]:
pr_number = change.pr
if pr_number is None:
# Should not happen but MyPy is not happy
continue
console.print("-" * 80)
console.print(
f"\n >>>> Retrieving PR#{pr_number}: https://github.com/apache/airflow/pull/{pr_number}"
)
pr: PullRequest
try:
pr = repo.get_pull(pr_number)
except UnknownObjectException:
# Fallback to issue if PR not found
try:
# PR has almost the same fields as Issue
pr = cast("PullRequest", repo.get_issue(pr_number))
except UnknownObjectException:
console.print(f"[red]The PR #{pr_number} could not be found[/]")
continue
console.print(f"\nPR:{pr_number}: {pr.title}\n")
label_names = [label.name for label in pr.labels]
already_assigned_milestone_number = pr.milestone.number if pr.milestone else None
if already_assigned_milestone_number == milestone.number:
console.print(
f"[green]The PR #{pr_number} is already "
f"assigned to the milestone: {pr.milestone.title}[/]. Labels: {label_names}"
)
if TYPE_DOC_ONLY_LABEL in label_names:
console.print("[yellow]It will be classified as doc-only change[/]\n")
if skip_assigned:
doc_only_changes.append(change)
elif CHANGELOG_SKIP_LABEL in label_names:
console.print("[yellow]It will be excluded from changelog[/]\n")
if skip_assigned:
excluded_changes.append(change)
else:
console.print("[green]The change will be included in changelog[/]\n")
if skip_assigned:
changelog_changes.append(change)
if skip_assigned:
continue
elif already_assigned_milestone_number is not None:
console.print(
f"[yellow]The PR #{pr_number} is already "
f"assigned to another milestone: {pr.milestone.title}[/]. Labels: {label_names}"
)
# Ignore doc-only and skipped PRs
console.print(f"Marking the PR #{pr_number} as {milestone.title}")
chosen_option = Prompt.ask(
"Choose action:",
choices=["a", "add", "d", "doc", "e", "exclude", "s", "skip", "q", "quit"],
default="skip",
).lower()
if chosen_option in ("add", "a"):
console.print(f"Adding the PR #{pr_number} to {milestone.title}")
if not dry_run:
update_milestone(repo, pr, milestone)
if skip_assigned:
changelog_changes.append(change)
elif chosen_option in ("doc", "d"):
console.print(f"Applying the label {doc_only_label} the PR #{pr_number}")
if not dry_run:
pr.add_to_labels(doc_only_label)
update_milestone(repo, pr, milestone)
if skip_assigned:
doc_only_changes.append(change)
elif chosen_option in ("exclude", "e"):
console.print(f"Applying the label {changelog_skip_label} the PR #{pr_number}")
if not dry_run:
pr.add_to_labels(changelog_skip_label)
update_milestone(repo, pr, milestone)
if skip_assigned:
excluded_changes.append(change)
elif chosen_option in ("skip", "s"):
console.print(f"Skipping the PR #{pr_number}")
elif chosen_option in ("quit", "q"):
sys.exit(2)
if print_summary:
context = {
"changelog_changes": changelog_changes,
"excluded_changes": excluded_changes,
"doc_only_changes": doc_only_changes,
"previous_release": previous_release,
"current_release": current_release,
}
console.print(render_template("CHERRY_PICK_SUMMARY.txt", context=context))
if output_folder:
def write_commits(type: str, path: Path, changes_to_write: list[Change]):
path.write_text("".join(f"{change.short_hash}\n" for change in changes_to_write))
console.print(f"\n{type} commits written in {path}")
write_commits("Changelog", Path(output_folder) / CHANGELOG_CHANGES_FILE, changelog_changes)
write_commits("Doc only", Path(output_folder) / DOC_ONLY_CHANGES_FILE, doc_only_changes)
write_commits("Excluded", Path(output_folder) / EXCLUDED_CHANGES_FILE, excluded_changes)
console.print("\n")
if __name__ == "__main__":
cli()
| Change |
python | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 14596,
"end": 23120
} | class ____:
def setup_method(self):
np.random.seed(1234)
def test_definition(self):
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = fftn(x)
assert_array_almost_equal(y, direct_dftn(x))
x = random((20, 26))
assert_array_almost_equal(fftn(x), direct_dftn(x))
x = random((5, 4, 3, 20))
assert_array_almost_equal(fftn(x), direct_dftn(x))
def test_axes_argument(self):
# plane == ji_plane, x== kji_space
plane1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
plane2 = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
plane3 = [[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]
ki_plane1 = [[1, 2, 3],
[10, 11, 12],
[19, 20, 21]]
ki_plane2 = [[4, 5, 6],
[13, 14, 15],
[22, 23, 24]]
ki_plane3 = [[7, 8, 9],
[16, 17, 18],
[25, 26, 27]]
jk_plane1 = [[1, 10, 19],
[4, 13, 22],
[7, 16, 25]]
jk_plane2 = [[2, 11, 20],
[5, 14, 23],
[8, 17, 26]]
jk_plane3 = [[3, 12, 21],
[6, 15, 24],
[9, 18, 27]]
kj_plane1 = [[1, 4, 7],
[10, 13, 16], [19, 22, 25]]
kj_plane2 = [[2, 5, 8],
[11, 14, 17], [20, 23, 26]]
kj_plane3 = [[3, 6, 9],
[12, 15, 18], [21, 24, 27]]
ij_plane1 = [[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
ij_plane2 = [[10, 13, 16],
[11, 14, 17],
[12, 15, 18]]
ij_plane3 = [[19, 22, 25],
[20, 23, 26],
[21, 24, 27]]
ik_plane1 = [[1, 10, 19],
[2, 11, 20],
[3, 12, 21]]
ik_plane2 = [[4, 13, 22],
[5, 14, 23],
[6, 15, 24]]
ik_plane3 = [[7, 16, 25],
[8, 17, 26],
[9, 18, 27]]
ijk_space = [jk_plane1, jk_plane2, jk_plane3]
ikj_space = [kj_plane1, kj_plane2, kj_plane3]
jik_space = [ik_plane1, ik_plane2, ik_plane3]
jki_space = [ki_plane1, ki_plane2, ki_plane3]
kij_space = [ij_plane1, ij_plane2, ij_plane3]
x = array([plane1, plane2, plane3])
assert_array_almost_equal(fftn(x),
fftn(x, axes=(-3, -2, -1))) # kji_space
assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
y = fftn(x, axes=(2, 1, 0)) # ijk_space
assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
y = fftn(x, axes=(2, 0, 1)) # ikj_space
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
fftn(ikj_space))
y = fftn(x, axes=(1, 2, 0)) # jik_space
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
fftn(jik_space))
y = fftn(x, axes=(1, 0, 2)) # jki_space
assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
y = fftn(x, axes=(0, 2, 1)) # kij_space
assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
y = fftn(x, axes=(-2, -1)) # ji_plane
assert_array_almost_equal(fftn(plane1), y[0])
assert_array_almost_equal(fftn(plane2), y[1])
assert_array_almost_equal(fftn(plane3), y[2])
y = fftn(x, axes=(1, 2)) # ji_plane
assert_array_almost_equal(fftn(plane1), y[0])
assert_array_almost_equal(fftn(plane2), y[1])
assert_array_almost_equal(fftn(plane3), y[2])
y = fftn(x, axes=(-3, -2)) # kj_plane
assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
y = fftn(x, axes=(-3, -1)) # ki_plane
assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
y = fftn(x, axes=(-1, -2)) # ij_plane
assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
y = fftn(x, axes=(-1, -3)) # ik_plane
assert_array_almost_equal(fftn(ik_plane1),
swapaxes(y[:, 0, :], -1, -2))
assert_array_almost_equal(fftn(ik_plane2),
swapaxes(y[:, 1, :], -1, -2))
assert_array_almost_equal(fftn(ik_plane3),
swapaxes(y[:, 2, :], -1, -2))
y = fftn(x, axes=(-2, -3)) # jk_plane
assert_array_almost_equal(fftn(jk_plane1),
swapaxes(y[:, :, 0], -1, -2))
assert_array_almost_equal(fftn(jk_plane2),
swapaxes(y[:, :, 1], -1, -2))
assert_array_almost_equal(fftn(jk_plane3),
swapaxes(y[:, :, 2], -1, -2))
y = fftn(x, axes=(-1,)) # i_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
y = fftn(x, axes=(-2,)) # j_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
y = fftn(x, axes=(0,)) # k_line
for i in range(3):
for j in range(3):
assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
y = fftn(x, axes=()) # point
assert_array_almost_equal(y, x)
def test_shape_argument(self):
small_x = [[1, 2, 3],
[4, 5, 6]]
large_x1 = [[1, 2, 3, 0],
[4, 5, 6, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
y = fftn(small_x, shape=(4, 4))
assert_array_almost_equal(y, fftn(large_x1))
y = fftn(small_x, shape=(3, 4))
assert_array_almost_equal(y, fftn(large_x1[:-1]))
def test_shape_axes_argument(self):
small_x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
large_x1 = array([[1, 2, 3, 0],
[4, 5, 6, 0],
[7, 8, 9, 0],
[0, 0, 0, 0]])
y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
assert_array_almost_equal(y, fftn(large_x1))
y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
assert_array_almost_equal(y, swapaxes(
fftn(swapaxes(large_x1, -1, -2)), -1, -2))
def test_shape_axes_argument2(self):
# Change shape of the last axis
x = numpy.random.random((10, 5, 3, 7))
y = fftn(x, axes=(-1,), shape=(8,))
assert_array_almost_equal(y, fft(x, axis=-1, n=8))
# Change shape of an arbitrary axis which is not the last one
x = numpy.random.random((10, 5, 3, 7))
y = fftn(x, axes=(-2,), shape=(8,))
assert_array_almost_equal(y, fft(x, axis=-2, n=8))
# Change shape of axes: cf #244, where shape and axes were mixed up
x = numpy.random.random((4, 4, 2))
y = fftn(x, axes=(-3, -2), shape=(8, 8))
assert_array_almost_equal(y,
numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
def test_shape_argument_more(self):
x = zeros((4, 4, 2))
with assert_raises(ValueError,
match="when given, axes and shape arguments"
" have to be of the same length"):
fftn(x, shape=(8, 8, 2, 1))
def test_invalid_sizes(self):
with assert_raises(ValueError,
match="invalid number of data points"
r" \(\[1, 0\]\) specified"):
fftn([[]])
with assert_raises(ValueError,
match="invalid number of data points"
r" \(\[4, -3\]\) specified"):
fftn([[1, 1], [2, 2]], (4, -3))
| TestFftn |
python | apache__airflow | providers/google/tests/unit/google/cloud/transfers/test_http_to_gcs.py | {
"start": 1426,
"end": 3771
} | class ____:
def test_init(self):
operator = HttpToGCSOperator(
task_id="http_to_gcs_operator",
http_conn_id=HTTP_CONN_ID,
endpoint=ENDPOINT,
object_name=DESTINATION_PATH_FILE,
bucket_name=TEST_BUCKET,
)
assert operator.endpoint == ENDPOINT
assert operator.object_name == DESTINATION_PATH_FILE
assert operator.bucket_name == TEST_BUCKET
assert operator.http_conn_id == HTTP_CONN_ID
@mock.patch("airflow.providers.google.cloud.transfers.http_to_gcs.GCSHook")
@mock.patch("airflow.providers.google.cloud.transfers.http_to_gcs.HttpHook")
def test_execute_copy_single_file(self, http_hook, gcs_hook):
task = HttpToGCSOperator(
task_id="http_to_gcs_operator",
http_conn_id=HTTP_CONN_ID,
endpoint=ENDPOINT,
headers=HEADERS,
data=DATA,
extra_options=EXTRA_OPTIONS,
object_name=DESTINATION_PATH_FILE,
bucket_name=TEST_BUCKET,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
task.execute(None)
# GCS
gcs_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
task.gcs_hook.upload.assert_called_once_with(
bucket_name=TEST_BUCKET,
object_name=DESTINATION_PATH_FILE,
data=task.http_hook.run.return_value.content,
mime_type=None,
gzip=False,
encoding=task.http_hook.run.return_value.encoding,
chunk_size=None,
timeout=None,
num_max_attempts=NUM_MAX_ATTEMPTS,
metadata=None,
cache_control=None,
user_project=None,
)
# HTTP
http_hook.assert_called_once_with(
DEFAULT_HTTP_METHOD,
http_conn_id=HTTP_CONN_ID,
auth_type=None,
tcp_keep_alive=True,
tcp_keep_alive_idle=TCP_KEEP_ALIVE_IDLE,
tcp_keep_alive_count=TCP_KEEP_ALIVE_COUNT,
tcp_keep_alive_interval=TCP_KEEP_ALIVE_INTERVAL,
)
task.http_hook.run.assert_called_once_with(
endpoint=ENDPOINT, headers=HEADERS, data=DATA, extra_options=EXTRA_OPTIONS
)
| TestHttpToGCSOperator |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 29112,
"end": 31502
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([LukeLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
word_hidden_states,
entity_hidden_states,
attention_mask=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
):
all_word_hidden_states = () if output_hidden_states else None
all_entity_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)
layer_outputs = layer_module(
word_hidden_states,
entity_hidden_states,
attention_mask,
output_attentions,
)
word_hidden_states = layer_outputs[0]
if entity_hidden_states is not None:
entity_hidden_states = layer_outputs[1]
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[2],)
if output_hidden_states:
all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)
if not return_dict:
return tuple(
v
for v in [
word_hidden_states,
all_word_hidden_states,
all_self_attentions,
entity_hidden_states,
all_entity_hidden_states,
]
if v is not None
)
return BaseLukeModelOutput(
last_hidden_state=word_hidden_states,
hidden_states=all_word_hidden_states,
attentions=all_self_attentions,
entity_last_hidden_state=entity_hidden_states,
entity_hidden_states=all_entity_hidden_states,
)
# Copied from transformers.models.bert.modeling_bert.BertPooler
| LukeEncoder |
python | davidhalter__parso | parso/python/errors.py | {
"start": 34252,
"end": 35317
} | class ____(SyntaxRule):
# def f(x=3, y): pass
message = "non-default argument follows default argument"
def is_issue(self, node):
param_names = set()
default_only = False
star_seen = False
for p in _iter_params(node):
if p.type == 'operator':
if p.value == '*':
star_seen = True
default_only = False
continue
if p.name.value in param_names:
message = "duplicate argument '%s' in function definition"
self.add_issue(p.name, message=message % p.name.value)
param_names.add(p.name.value)
if not star_seen:
if p.default is None and not p.star_count:
if default_only:
return True
elif p.star_count:
star_seen = True
default_only = False
else:
default_only = True
@ErrorFinder.register_rule(type='try_stmt')
| _ParameterRule |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 11823,
"end": 14777
} | class ____:
"""
Tests for `source='*'` argument, which is often used for complex field or
nested representations.
For example:
nested_field = NestedField(source='*')
"""
data = {
'nested1': {'a': 1, 'b': 2},
'nested2': {'c': 3, 'd': 4}
}
def setup_method(self):
class NestedSerializer1(serializers.Serializer):
a = serializers.IntegerField()
b = serializers.IntegerField()
class NestedSerializer2(serializers.Serializer):
c = serializers.IntegerField()
d = serializers.IntegerField()
class NestedBaseSerializer(serializers.Serializer):
nested1 = NestedSerializer1(source='*')
nested2 = NestedSerializer2(source='*')
# nullable nested serializer testing
class NullableNestedSerializer(serializers.Serializer):
nested = NestedSerializer1(source='*', allow_null=True)
# nullable custom field testing
class CustomField(serializers.Field):
def to_representation(self, instance):
return getattr(instance, 'foo', None)
def to_internal_value(self, data):
return {'foo': data}
class NullableFieldSerializer(serializers.Serializer):
field = CustomField(source='*', allow_null=True)
self.Serializer = NestedBaseSerializer
self.NullableNestedSerializer = NullableNestedSerializer
self.NullableFieldSerializer = NullableFieldSerializer
def test_nested_validate(self):
"""
A nested representation is validated into a flat internal object.
"""
serializer = self.Serializer(data=self.data)
assert serializer.is_valid()
assert serializer.validated_data == {
'a': 1,
'b': 2,
'c': 3,
'd': 4
}
def test_nested_null_validate(self):
serializer = self.NullableNestedSerializer(data={'nested': None})
# validation should fail (but not error) since nested fields are required
assert not serializer.is_valid()
def test_nested_serialize(self):
"""
An object can be serialized into a nested representation.
"""
instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
serializer = self.Serializer(instance)
assert serializer.data == self.data
def test_field_validate(self):
serializer = self.NullableFieldSerializer(data={'field': 'bar'})
# validation should pass since no internal validation
assert serializer.is_valid()
assert serializer.validated_data == {'foo': 'bar'}
def test_field_null_validate(self):
serializer = self.NullableFieldSerializer(data={'field': None})
# validation should pass since no internal validation
assert serializer.is_valid()
assert serializer.validated_data == {'foo': None}
| TestStarredSource |
python | huggingface__transformers | src/transformers/models/segformer/modeling_segformer.py | {
"start": 22074,
"end": 24927
} | class ____(SegformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
# linear layers which will unify the channel dimension of each of the encoder blocks to the same config.decoder_hidden_size
mlps = []
for i in range(config.num_encoder_blocks):
mlp = SegformerMLP(config, input_dim=config.hidden_sizes[i])
mlps.append(mlp)
self.linear_c = nn.ModuleList(mlps)
# the following 3 layers implement the ConvModule of the original implementation
self.linear_fuse = nn.Conv2d(
in_channels=config.decoder_hidden_size * config.num_encoder_blocks,
out_channels=config.decoder_hidden_size,
kernel_size=1,
bias=False,
)
self.batch_norm = nn.BatchNorm2d(config.decoder_hidden_size)
self.activation = nn.ReLU()
self.dropout = nn.Dropout(config.classifier_dropout_prob)
self.classifier = nn.Conv2d(config.decoder_hidden_size, config.num_labels, kernel_size=1)
self.config = config
def forward(self, encoder_hidden_states: torch.FloatTensor) -> torch.Tensor:
batch_size = encoder_hidden_states[-1].shape[0]
all_hidden_states = ()
for encoder_hidden_state, mlp in zip(encoder_hidden_states, self.linear_c):
if self.config.reshape_last_stage is False and encoder_hidden_state.ndim == 3:
height = width = int(math.sqrt(encoder_hidden_state.shape[-1]))
encoder_hidden_state = (
encoder_hidden_state.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
)
# unify channel dimension
height, width = encoder_hidden_state.shape[2], encoder_hidden_state.shape[3]
encoder_hidden_state = mlp(encoder_hidden_state)
encoder_hidden_state = encoder_hidden_state.permute(0, 2, 1)
encoder_hidden_state = encoder_hidden_state.reshape(batch_size, -1, height, width)
# upsample
encoder_hidden_state = nn.functional.interpolate(
encoder_hidden_state, size=encoder_hidden_states[0].size()[2:], mode="bilinear", align_corners=False
)
all_hidden_states += (encoder_hidden_state,)
hidden_states = self.linear_fuse(torch.cat(all_hidden_states[::-1], dim=1))
hidden_states = self.batch_norm(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.dropout(hidden_states)
# logits are of shape (batch_size, num_labels, height/4, width/4)
logits = self.classifier(hidden_states)
return logits
@auto_docstring(
custom_intro="""
SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
"""
)
| SegformerDecodeHead |
python | pydata__xarray | xarray/tests/test_treenode.py | {
"start": 14316,
"end": 15329
} | class ____:
def test_render_nodetree(self) -> None:
john: NamedNode = NamedNode(
children={
"Mary": NamedNode(children={"Sam": NamedNode(), "Ben": NamedNode()}),
"Kate": NamedNode(),
}
)
mary = john.children["Mary"]
expected_nodes = [
"NamedNode()",
"\tNamedNode('Mary')",
"\t\tNamedNode('Sam')",
"\t\tNamedNode('Ben')",
"\tNamedNode('Kate')",
]
expected_str = "NamedNode('Mary')"
john_repr = john.__repr__()
mary_str = mary.__str__()
assert mary_str == expected_str
john_nodes = john_repr.splitlines()
assert len(john_nodes) == len(expected_nodes)
for expected_node, repr_node in zip(expected_nodes, john_nodes, strict=True):
assert expected_node == repr_node
def test_nodepath():
path = NodePath("/Mary")
assert path.root == "/"
assert path.stem == "Mary"
| TestRenderTree |
python | numba__numba | numba/core/typing/setdecl.py | {
"start": 1001,
"end": 2387
} | class ____(AttributeTemplate):
key = types.Set
@bound_function("set.add")
def resolve_add(self, set, args, kws):
item, = args
assert not kws
unified = self.context.unify_pairs(set.dtype, item)
if unified is not None:
sig = signature(types.none, unified)
sig = sig.replace(recvr=set.copy(dtype=unified))
return sig
@bound_function("set.update")
def resolve_update(self, set, args, kws):
iterable, = args
assert not kws
if not isinstance(iterable, types.IterableType):
return
dtype = iterable.iterator_type.yield_type
unified = self.context.unify_pairs(set.dtype, dtype)
if unified is not None:
sig = signature(types.none, iterable)
sig = sig.replace(recvr=set.copy(dtype=unified))
return sig
def _resolve_operator(self, set, args, kws):
assert not kws
iterable, = args
# Set arguments only supported for now
# (note we can mix non-reflected and reflected arguments)
if isinstance(iterable, types.Set) and iterable.dtype == set.dtype:
return signature(set, iterable)
def _resolve_comparator(self, set, args, kws):
assert not kws
arg, = args
if arg == set:
return signature(types.boolean, arg)
| SetAttribute |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 21032,
"end": 23427
} | class ____(utils.Enum):
unspecified = "unspecified"
key_compromise = "keyCompromise"
ca_compromise = "cACompromise"
affiliation_changed = "affiliationChanged"
superseded = "superseded"
cessation_of_operation = "cessationOfOperation"
certificate_hold = "certificateHold"
privilege_withdrawn = "privilegeWithdrawn"
aa_compromise = "aACompromise"
remove_from_crl = "removeFromCRL"
# These are distribution point bit string mappings. Not to be confused with
# CRLReason reason flags bit string mappings.
# ReasonFlags ::= BIT STRING {
# unused (0),
# keyCompromise (1),
# cACompromise (2),
# affiliationChanged (3),
# superseded (4),
# cessationOfOperation (5),
# certificateHold (6),
# privilegeWithdrawn (7),
# aACompromise (8) }
_REASON_BIT_MAPPING = {
1: ReasonFlags.key_compromise,
2: ReasonFlags.ca_compromise,
3: ReasonFlags.affiliation_changed,
4: ReasonFlags.superseded,
5: ReasonFlags.cessation_of_operation,
6: ReasonFlags.certificate_hold,
7: ReasonFlags.privilege_withdrawn,
8: ReasonFlags.aa_compromise,
}
_CRLREASONFLAGS = {
ReasonFlags.key_compromise: 1,
ReasonFlags.ca_compromise: 2,
ReasonFlags.affiliation_changed: 3,
ReasonFlags.superseded: 4,
ReasonFlags.cessation_of_operation: 5,
ReasonFlags.certificate_hold: 6,
ReasonFlags.privilege_withdrawn: 7,
ReasonFlags.aa_compromise: 8,
}
# CRLReason ::= ENUMERATED {
# unspecified (0),
# keyCompromise (1),
# cACompromise (2),
# affiliationChanged (3),
# superseded (4),
# cessationOfOperation (5),
# certificateHold (6),
# -- value 7 is not used
# removeFromCRL (8),
# privilegeWithdrawn (9),
# aACompromise (10) }
_CRL_ENTRY_REASON_ENUM_TO_CODE = {
ReasonFlags.unspecified: 0,
ReasonFlags.key_compromise: 1,
ReasonFlags.ca_compromise: 2,
ReasonFlags.affiliation_changed: 3,
ReasonFlags.superseded: 4,
ReasonFlags.cessation_of_operation: 5,
ReasonFlags.certificate_hold: 6,
ReasonFlags.remove_from_crl: 8,
ReasonFlags.privilege_withdrawn: 9,
ReasonFlags.aa_compromise: 10,
}
| ReasonFlags |
python | ray-project__ray | python/ray/data/_internal/execution/operators/map_transformer.py | {
"start": 750,
"end": 911
} | class ____(Enum):
"""An enum that represents the input/output data type of a MapTransformFn."""
Block = 0
Row = 1
Batch = 2
| MapTransformFnDataType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.