language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/config.py | {
"start": 3729,
"end": 4867
} | class ____:
"""
NodeTypeConfig is the helper class to provide node type specific configs.
This maps to subset of the `available_node_types` field in the
autoscaling config.
"""
# Node type name
name: NodeType
# The minimal number of worker nodes to be launched for this node type.
min_worker_nodes: int
# The maximal number of worker nodes can be launched for this node type.
max_worker_nodes: int
# Idle timeout seconds for worker nodes of this node type.
idle_timeout_s: Optional[float] = None
# The total resources on the node.
resources: Dict[str, float] = field(default_factory=dict)
# The labels on the node.
labels: Dict[str, str] = field(default_factory=dict)
# The node config's launch config hash. It's calculated from the auth
# config, and the node's config in the `AutoscalingConfig` for the node
# type when launching the node. It's used to detect config changes.
launch_config_hash: str = ""
def __post_init__(self):
assert self.min_worker_nodes <= self.max_worker_nodes
assert self.min_worker_nodes >= 0
| NodeTypeConfig |
python | pyca__cryptography | src/cryptography/hazmat/decrepit/ciphers/algorithms.py | {
"start": 1671,
"end": 1942
} | class ____(BlockCipherAlgorithm):
name = "SEED"
block_size = 128
key_sizes = frozenset([128])
def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
@property
def key_size(self) -> int:
return len(self.key) * 8
| SEED |
python | kamyu104__LeetCode-Solutions | Python/maximum-partition-factor.py | {
"start": 1844,
"end": 3644
} | class ____(object):
def maxPartitionFactor(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
y = stk.pop()
self.set[y] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return False
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
self.set[x] = self.set[y]
return True
def dist(u, v):
return abs(points[u][0]-points[v][0])+abs(points[u][1]-points[v][1])
sorted_dists = sorted((dist(u, v), u, v) for u in xrange(len(points)) for v in xrange(u+1, len(points)))
uf = UnionFind(len(points))
lookup = [-1]*len(points)
for d, u, v in sorted_dists:
if uf.find_set(u) == uf.find_set(v):
return d
if lookup[u] != -1:
uf.union_set(lookup[u], v)
else:
lookup[u] = v
if lookup[v] != -1:
uf.union_set(lookup[v], u)
else:
lookup[v] = u
return 0
# Time: O(n^2 * logn)
# Space: O(n^2)
# binary search, bfs, coordinate compression
| Solution2 |
python | facebookresearch__faiss | faiss/python/extra_wrappers.py | {
"start": 8853,
"end": 12936
} | class ____:
def __init__(self, capacity):
self.log2_capacity = int(np.log2(capacity))
assert capacity == 2 ** self.log2_capacity, "need power of 2 capacity"
self.capacity = capacity
self.tab = np.empty((capacity, 2), dtype='int64')
faiss.hashtable_int64_to_int64_init(self.log2_capacity, swig_ptr(self.tab))
def add(self, keys, vals):
n, = keys.shape
assert vals.shape == (n,)
faiss.hashtable_int64_to_int64_add(
self.log2_capacity, swig_ptr(self.tab),
n, swig_ptr(keys), swig_ptr(vals))
def lookup(self, keys):
n, = keys.shape
vals = np.empty((n,), dtype='int64')
faiss.hashtable_int64_to_int64_lookup(
self.log2_capacity, swig_ptr(self.tab),
n, swig_ptr(keys), swig_ptr(vals))
return vals
######################################################
# KNN function
######################################################
def knn(xq, xb, k, metric=METRIC_L2, metric_arg=0.0):
"""
Compute the k nearest neighbors of a vector without constructing an index
Parameters
----------
xq : array_like
Query vectors, shape (nq, d) where the dimension d is that same as xb
`dtype` must be float32.
xb : array_like
Database vectors, shape (nb, d) where dimension d is the same as xq
`dtype` must be float32.
k : int
Number of nearest neighbors.
metric : MetricType, optional
distance measure to use (either METRIC_L2 or METRIC_INNER_PRODUCT)
Returns
-------
D : array_like
Distances of the nearest neighbors, shape (nq, k)
I : array_like
Labels of the nearest neighbors, shape (nq, k)
"""
xq = np.ascontiguousarray(xq, dtype='float32')
xb = np.ascontiguousarray(xb, dtype='float32')
nq, d = xq.shape
nb, d2 = xb.shape
assert d == d2
I = np.empty((nq, k), dtype='int64')
D = np.empty((nq, k), dtype='float32')
if metric == METRIC_L2:
knn_L2sqr(
swig_ptr(xq), swig_ptr(xb),
d, nq, nb, k, swig_ptr(D), swig_ptr(I)
)
elif metric == METRIC_INNER_PRODUCT:
knn_inner_product(
swig_ptr(xq), swig_ptr(xb),
d, nq, nb, k, swig_ptr(D), swig_ptr(I)
)
else:
knn_extra_metrics(
swig_ptr(xq), swig_ptr(xb),
d, nq, nb, metric, metric_arg, k,
swig_ptr(D), swig_ptr(I)
)
return D, I
def knn_hamming(xq, xb, k, variant="hc"):
"""
Compute the k nearest neighbors of a set of vectors without constructing an index.
Parameters
----------
xq : array_like
Query vectors, shape (nq, d) where d is the number of bits / 8
`dtype` must be uint8.
xb : array_like
Database vectors, shape (nb, d) where d is the number of bits / 8
`dtype` must be uint8.
k : int
Number of nearest neighbors.
variant : string
Function variant to use, either "mc" (counter) or "hc" (heap)
Returns
-------
D : array_like
Distances of the nearest neighbors, shape (nq, k)
I : array_like
Labels of the nearest neighbors, shape (nq, k)
"""
# other variant is "mc"
nq, d = xq.shape
nb, d2 = xb.shape
assert d == d2
D = np.empty((nq, k), dtype='int32')
I = np.empty((nq, k), dtype='int64')
if variant == "hc":
heap = faiss.int_maxheap_array_t()
heap.k = k
heap.nh = nq
heap.ids = faiss.swig_ptr(I)
heap.val = faiss.swig_ptr(D)
faiss.hammings_knn_hc(
heap, faiss.swig_ptr(xq), faiss.swig_ptr(xb), nb,
d, 1
)
elif variant == "mc":
faiss.hammings_knn_mc(
faiss.swig_ptr(xq), faiss.swig_ptr(xb), nq, nb, k, d,
faiss.swig_ptr(D), faiss.swig_ptr(I)
)
else:
raise NotImplementedError
return D, I
###########################################
# Kmeans object
###########################################
| MapInt64ToInt64 |
python | scikit-image__scikit-image | tests/skimage/morphology/test_skeletonize.py | {
"start": 10757,
"end": 13680
} | class ____:
def test_all_zeros(self):
result = medial_axis(np.zeros((10, 10), dtype=bool))
assert np.all(result == False)
def test_all_zeros_masked(self):
result = medial_axis(
np.zeros((10, 10), dtype=bool), np.zeros((10, 10), dtype=bool)
)
assert np.all(result == False)
@pytest.mark.parametrize("dtype", [bool, float, int])
def test_vertical_line(self, dtype):
# Image is a thick vertical line (see gh-3861)
image = np.zeros((9, 9), dtype=dtype)
image[:, 2] = 1
image[:, 3] = 2
image[:, 4] = 3
expected = np.full(image.shape, False)
expected[:, 3] = True
result = medial_axis(image)
assert_array_equal(result, expected)
def test_rectangle(self):
image = np.zeros((9, 15), dtype=bool)
image[1:-1, 1:-1] = True
# Excepted are four diagonals from the corners, meeting in a horizontal line
expected = np.array(
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
],
dtype=bool,
)
result = medial_axis(image)
assert np.all(result == expected)
result, distance = medial_axis(image, return_distance=True)
assert distance.max() == 4
def test_rectange_with_hole(self):
image = np.zeros((9, 15), dtype=bool)
image[1:-1, 1:-1] = True
image[4, 4:-4] = False
expected = np.array(
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
],
dtype=bool,
)
result = medial_axis(image)
assert np.all(result == expected)
def test_narrow_image(self):
# Image is a 1-pixel thin strip
image = np.zeros((1, 5), dtype=bool)
image[:, 1:-1] = True
result = medial_axis(image)
assert np.all(result == image)
| TestMedialAxis |
python | mlflow__mlflow | mlflow/server/handlers.py | {
"start": 7310,
"end": 8352
} | class ____(TrackingStoreRegistry):
def __init__(self):
super().__init__()
self.register("", self._get_file_store)
self.register("file", self._get_file_store)
for scheme in DATABASE_ENGINES:
self.register(scheme, self._get_sqlalchemy_store)
# Add support for Databricks tracking store
self.register("databricks", self._get_databricks_rest_store)
self.register_entrypoints()
@classmethod
def _get_file_store(cls, store_uri, artifact_uri):
from mlflow.store.tracking.file_store import FileStore
return FileStore(store_uri, artifact_uri)
@classmethod
def _get_sqlalchemy_store(cls, store_uri, artifact_uri):
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
return SqlAlchemyStore(store_uri, artifact_uri)
@classmethod
def _get_databricks_rest_store(cls, store_uri, artifact_uri):
return DatabricksTracingRestStore(partial(get_databricks_host_creds, store_uri))
| TrackingStoreRegistryWrapper |
python | python__mypy | mypy/errors.py | {
"start": 10456,
"end": 12233
} | class ____(ErrorWatcher):
"""Error watcher that filters and separately collects `unreachable` errors,
`redundant-expr` and `redundant-casts` errors, and revealed types when analysing
code sections iteratively to help avoid making too-hasty reports."""
iteration_dependent_errors: IterationDependentErrors
def __init__(
self,
errors: Errors,
iteration_dependent_errors: IterationDependentErrors,
*,
filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,
save_filtered_errors: bool = False,
filter_deprecated: bool = False,
) -> None:
super().__init__(
errors,
filter_errors=filter_errors,
save_filtered_errors=save_filtered_errors,
filter_deprecated=filter_deprecated,
)
self.iteration_dependent_errors = iteration_dependent_errors
iteration_dependent_errors.uselessness_errors.append(set())
iteration_dependent_errors.unreachable_lines.append(set())
def on_error(self, file: str, info: ErrorInfo) -> bool:
"""Filter out the "iteration-dependent" errors and notes and store their
information to handle them after iteration is completed."""
iter_errors = self.iteration_dependent_errors
if info.code in (codes.UNREACHABLE, codes.REDUNDANT_EXPR, codes.REDUNDANT_CAST):
iter_errors.uselessness_errors[-1].add(
(info.code, info.message, info.line, info.column, info.end_line, info.end_column)
)
if info.code == codes.UNREACHABLE:
iter_errors.unreachable_lines[-1].update(range(info.line, info.end_line + 1))
return True
return super().on_error(file, info)
| IterationErrorWatcher |
python | kamyu104__LeetCode-Solutions | Python/throne-inheritance.py | {
"start": 128,
"end": 1192
} | class ____(object):
def __init__(self, kingName):
"""
:type kingName: str
"""
self.__king = kingName
self.__family_tree = collections.defaultdict(list)
self.__dead = set()
def birth(self, parentName, childName):
"""
:type parentName: str
:type childName: str
:rtype: None
"""
self.__family_tree[parentName].append(childName)
def death(self, name):
"""
:type name: str
:rtype: None
"""
self.__dead.add(name)
def getInheritanceOrder(self):
"""
:rtype: List[str]
"""
result = []
stk = [self.__king]
while stk: # preorder traversal
node = stk.pop()
if node not in self.__dead:
result.append(node)
if node not in self.__family_tree:
continue
for child in reversed(self.__family_tree[node]):
stk.append(child)
return result
| ThroneInheritance |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 25754,
"end": 25869
} | class ____(Structure):
_fields_ = (("name", lc_str),)
def describe(self):
return {}
| dylinker_command |
python | kamyu104__LeetCode-Solutions | Python/minimum-moves-to-equal-array-elements.py | {
"start": 29,
"end": 207
} | class ____(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums) - len(nums) * min(nums)
| Solution |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 26659,
"end": 27627
} | class ____(PrefixedSubAppResource):
def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None:
AbstractResource.__init__(self)
self._prefix = ""
self._app = app
self._rule = rule
@property
def canonical(self) -> str:
return self._rule.canonical
def get_info(self) -> _InfoDict:
return {"app": self._app, "rule": self._rule}
async def resolve(self, request: Request) -> _Resolve:
if not await self._rule.match(request):
return None, set()
match_info = await self._app.router.resolve(request)
match_info.add_app(self._app)
if isinstance(match_info.http_exception, HTTPMethodNotAllowed):
methods = match_info.http_exception.allowed_methods
else:
methods = set()
return match_info, methods
def __repr__(self) -> str:
return f"<MatchedSubAppResource -> {self._app!r}>"
| MatchedSubAppResource |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 15724,
"end": 18225
} | class ____(ConstraintWithMetadata):
"""Similar to the base class, but now your validation functions should take in columns (pd.Series) not Dataframes.
Args:
description (str): description of the constraint
validation_fn (Callable[[pd.Series], Tuple[bool, dict[str, Union[dict,list, str, set]]]]:
the validation function to run over inputted data
This function should return a tuple of a boolean for success or failure, and a dict containing
metadata about the test -- this metadata will be passed to the resulting exception if validation
fails.
resulting_exception (ConstraintWithMetadataException): what response a failed typecheck should induce
raise_or_typecheck (Optional[bool]): whether to raise an exception (if set to True) or emit a failed typecheck event
(if set to False) when validation fails
name (Optional[str]): what to call the constraint, defaults to the class name.
"""
def validate(self, data, *columns, **kwargs):
if len(columns) == 0:
columns = data.columns
columns = [column for column in columns if column in data.columns]
relevant_data = data[list(columns)]
offending_columns = set()
offending_values = {}
for column in columns:
# TODO: grab extra metadata
res = self.validation_fn(relevant_data[column])
if not res[0]:
offending_columns.add(column)
if res[1].get("actual") is not None:
offending_values[column] = [x.item() for x in res[1].get("actual").to_numpy()]
else:
offending_values[column] = [x.item() for x in relevant_data[column].to_numpy()]
if len(offending_columns) == 0 and not self.raise_or_typecheck:
return TypeCheck(success=True)
elif len(offending_columns) > 0:
metadict = {
"expectation": self.description.replace("Confirms", ""),
"actual": offending_values,
"offending": offending_columns,
}
exc = self.resulting_exception(
constraint_name=self.name, constraint_description=self.description, **metadict
)
if self.raise_or_typecheck:
raise exc
else:
return exc.return_as_typecheck()
| ColumnAggregateConstraintWithMetadata |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 12185,
"end": 12887
} | class ____:
"""Utility class, to be used to test an instructions list.
See :meth:`Instruction.match`.
"""
cls: type[Instruction]
kwargs: dict[str, Any]
def __init__(self, cls: type[Instruction], **kwargs: Any):
self.cls = cls
self.kwargs = kwargs
def __repr__(self) -> str:
cls_str = self.cls.__name__
kwargs_str = ", ".join(f"{k}={v}" for k, v in self.kwargs.items())
return f"{cls_str}({kwargs_str}) (partial match)"
def __eq__(self, other: object) -> bool:
if type(other) is not self.cls:
return False
return all(getattr(other, k) == v for k, v in self.kwargs.items())
@dataclass
| _InstructionMatch |
python | OmkarPathak__pygorithm | tests/test_math.py | {
"start": 372,
"end": 557
} | class ____(unittest.TestCase):
def test_sieve_of_eratosthenes(self):
self.assertEqual(sieve_of_eratosthenes.sieve_of_eratosthenes(11), [2, 3, 5, 7, 11])
| TestSieveOfEratosthenes |
python | keon__algorithms | tests/test_strings.py | {
"start": 3245,
"end": 3652
} | class ____(unittest.TestCase):
"""[summary]
Test for the file domain_extractor.py
Arguments:
unittest {[type]} -- [description]
"""
def test_valid(self):
self.assertEqual(domain_name_1("https://github.com/SaadBenn"),
"github")
def test_invalid(self):
self.assertEqual(domain_name_2("http://google.com"), "google")
| TestDomainExtractor |
python | gevent__gevent | src/greentest/3.12/test_socket.py | {
"start": 189963,
"end": 196624
} | class ____(ThreadedTCPSocketTest):
def __init__(self, methodName='runTest'):
self.event = threading.Event()
ThreadedTCPSocketTest.__init__(self, methodName=methodName)
def assert_sock_timeout(self, sock, timeout):
self.assertEqual(self.serv.gettimeout(), timeout)
blocking = (timeout != 0.0)
self.assertEqual(sock.getblocking(), blocking)
if fcntl is not None:
# When a Python socket has a non-zero timeout, it's switched
# internally to a non-blocking mode. Later, sock.sendall(),
# sock.recv(), and other socket operations use a select() call and
# handle EWOULDBLOCK/EGAIN on all socket operations. That's how
# timeouts are enforced.
fd_blocking = (timeout is None)
flag = fcntl.fcntl(sock, fcntl.F_GETFL, os.O_NONBLOCK)
self.assertEqual(not bool(flag & os.O_NONBLOCK), fd_blocking)
def testSetBlocking(self):
# Test setblocking() and settimeout() methods
self.serv.setblocking(True)
self.assert_sock_timeout(self.serv, None)
self.serv.setblocking(False)
self.assert_sock_timeout(self.serv, 0.0)
self.serv.settimeout(None)
self.assert_sock_timeout(self.serv, None)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
self.serv.settimeout(10)
self.assert_sock_timeout(self.serv, 10)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
def _testSetBlocking(self):
pass
@support.cpython_only
def testSetBlocking_overflow(self):
# Issue 15989
import _testcapi
if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
self.skipTest('needs UINT_MAX < ULONG_MAX')
self.serv.setblocking(False)
self.assertEqual(self.serv.gettimeout(), 0.0)
self.serv.setblocking(_testcapi.UINT_MAX + 1)
self.assertIsNone(self.serv.gettimeout())
_testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
'test needs socket.SOCK_NONBLOCK')
@support.requires_linux_version(2, 6, 28)
def testInitNonBlocking(self):
# create a socket with SOCK_NONBLOCK
self.serv.close()
self.serv = socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
self.assert_sock_timeout(self.serv, 0)
def _testInitNonBlocking(self):
pass
def testInheritFlagsBlocking(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must be blocking.
with socket_setdefaulttimeout(None):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testInheritFlagsBlocking(self):
self.cli.connect((HOST, self.port))
def testInheritFlagsTimeout(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must inherit
# the default timeout.
default_timeout = 20.0
with socket_setdefaulttimeout(default_timeout):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertEqual(conn.gettimeout(), default_timeout)
def _testInheritFlagsTimeout(self):
self.cli.connect((HOST, self.port))
def testAccept(self):
# Testing non-blocking accept
self.serv.setblocking(False)
# connect() didn't start: non-blocking accept() fails
start_time = time.monotonic()
with self.assertRaises(BlockingIOError):
conn, addr = self.serv.accept()
dt = time.monotonic() - start_time
self.assertLess(dt, 1.0)
self.event.set()
read, write, err = select.select([self.serv], [], [], support.LONG_TIMEOUT)
if self.serv not in read:
self.fail("Error trying to do accept after select.")
# connect() completed: non-blocking accept() doesn't block
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testAccept(self):
# don't connect before event is set to check
# that non-blocking accept() raises BlockingIOError
self.event.wait()
self.cli.connect((HOST, self.port))
def testRecv(self):
# Testing non-blocking recv
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
conn.setblocking(False)
# the server didn't send data yet: non-blocking recv() fails
with self.assertRaises(BlockingIOError):
msg = conn.recv(len(MSG))
self.event.set()
read, write, err = select.select([conn], [], [], support.LONG_TIMEOUT)
if conn not in read:
self.fail("Error during select call to non-blocking socket.")
# the server sent data yet: non-blocking recv() doesn't block
msg = conn.recv(len(MSG))
self.assertEqual(msg, MSG)
def _testRecv(self):
self.cli.connect((HOST, self.port))
# don't send anything before event is set to check
# that non-blocking recv() raises BlockingIOError
self.event.wait()
# send data: recv() will no longer block
self.cli.sendall(MSG)
@support.cpython_only
def testLargeTimeout(self):
# gh-126876: Check that a timeout larger than INT_MAX is replaced with
# INT_MAX in the poll() code path. The following assertion must not
# fail: assert(INT_MIN <= ms && ms <= INT_MAX).
import _testcapi
large_timeout = _testcapi.INT_MAX + 1
# test recv() with large timeout
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
try:
conn.settimeout(large_timeout)
except OverflowError:
# On Windows, settimeout() fails with OverflowError, whereas
# we want to test recv(). Just give up silently.
return
msg = conn.recv(len(MSG))
def _testLargeTimeout(self):
# test sendall() with large timeout
import _testcapi
large_timeout = _testcapi.INT_MAX + 1
self.cli.connect((HOST, self.port))
try:
self.cli.settimeout(large_timeout)
except OverflowError:
return
self.cli.sendall(MSG)
| NonBlockingTCPTests |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_highlight.py | {
"start": 7654,
"end": 8686
} | class ____(util.MdCase):
"""Test custom language prefix."""
extension = ['pymdownx.highlight', 'pymdownx.superfences', 'pymdownx.inlinehilite']
extension_configs = {
'pymdownx.highlight': {
'language_prefix': 'lang-',
'use_pygments': False
}
}
def test_custom_prefix_no_pygments(self):
"""Test with custom prefix and no Pygments."""
self.check_markdown(
r'''
```python
import test
test.test()
```
''',
r'''
<pre class="highlight"><code class="lang-python">import test
test.test()</code></pre>
''',
True
)
def test_custom_prefix_no_pygments_inline(self):
"""Test with custom prefix and no Pygments with inline code."""
self.check_markdown(
'`#!python import test`',
'<p><code class="lang-python highlight">import test</code></p>'
)
| TestCustomLangPrefixNoPygments |
python | sphinx-doc__sphinx | sphinx/roles.py | {
"start": 13537,
"end": 14124
} | class ____(SphinxRole):
amp_re = re.compile(r'(?<!&)&(?![&\s])')
def run(self) -> tuple[list[Node], list[system_message]]:
node = nodes.inline(rawtext=self.rawtext, classes=[self.name])
spans = self.amp_re.split(self.text)
node += nodes.Text(spans.pop(0))
for span in spans:
span = span.replace('&&', '&')
letter = nodes.Text(span[0])
accelerator = nodes.inline('', '', letter, classes=['accelerator'])
node += accelerator
node += nodes.Text(span[1:])
return [node], []
| GUILabel |
python | Netflix__metaflow | metaflow/plugins/aws/batch/batch.py | {
"start": 1139,
"end": 1227
} | class ____(MetaflowException):
headline = "AWS Batch task killed"
| BatchKilledException |
python | google__jax | jaxlib/mosaic/python/layout_defs.py | {
"start": 1155,
"end": 1422
} | class ____(enum.Enum):
REPLICATED = "*"
def __repr__(self):
return "*"
__str__ = __repr__
def __bool__(self):
return False # Useful because we can then say `offset or 0`
REPLICATED = Replicated.REPLICATED
Offset = int | Literal[REPLICATED]
| Replicated |
python | yaml__pyyaml | lib/yaml/emitter.py | {
"start": 426,
"end": 967
} | class ____:
def __init__(self, scalar, empty, multiline,
allow_flow_plain, allow_block_plain,
allow_single_quoted, allow_double_quoted,
allow_block):
self.scalar = scalar
self.empty = empty
self.multiline = multiline
self.allow_flow_plain = allow_flow_plain
self.allow_block_plain = allow_block_plain
self.allow_single_quoted = allow_single_quoted
self.allow_double_quoted = allow_double_quoted
self.allow_block = allow_block
| ScalarAnalysis |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 6858,
"end": 16709
} | class ____(TestCase, CustomAssertMixin):
def setUp(self) -> None:
self._backend = FakeRendezvousBackend()
mock_get_state = MagicMock(wraps=self._backend.get_state)
mock_set_state = MagicMock(wraps=self._backend.set_state)
self._mock_backend = Mock()
self._mock_backend.get_state = mock_get_state
self._mock_backend.set_state = mock_set_state
setattr(self._backend, "get_state", mock_get_state) # noqa: B010
setattr(self._backend, "set_state", mock_set_state) # noqa: B010
self._settings = RendezvousSettings(
run_id="dummy_run_id",
min_nodes=1,
max_nodes=1,
timeout=RendezvousTimeout(),
keep_alive_interval=timedelta(seconds=30),
keep_alive_max_attempt=3,
)
self._cache_duration = 0
self._now = datetime(2000, 1, 1, hour=0, minute=0)
self._datetime_patch = patch(
"torch.distributed.elastic.rendezvous.dynamic_rendezvous.datetime"
)
mock_datetime = self._datetime_patch.start()
mock_datetime.utcnow.return_value = self._now
def tearDown(self) -> None:
self._datetime_patch.stop()
def _create_state(self) -> _RendezvousState:
state = _RendezvousState()
state.round = 999
state.complete = True
state.deadline = self._now
state.closed = True
state.participants = {
_NodeDesc("dummy1", 1, 1): 0,
_NodeDesc("dummy2", 1, 1): 1,
_NodeDesc("dummy3", 1, 1): 2,
}
state.wait_list = {
_NodeDesc("dummy4", 1, 1),
_NodeDesc("dummy5", 1, 1),
}
state.last_heartbeats = {
_NodeDesc("dummy1", 1, 1): self._now,
_NodeDesc("dummy2", 1, 1): self._now - timedelta(seconds=15),
_NodeDesc("dummy3", 1, 1): self._now - timedelta(seconds=30),
_NodeDesc("dummy4", 1, 1): self._now - timedelta(seconds=60),
_NodeDesc("dummy5", 1, 1): self._now - timedelta(seconds=90),
}
return state
def _create_state_holder(self) -> _BackendRendezvousStateHolder:
return _BackendRendezvousStateHolder(
self._backend, self._settings, self._cache_duration
)
def test_init_initializes_state_holder(self) -> None:
state_holder = self._create_state_holder()
self.assert_state_empty(state_holder.state)
self._mock_backend.assert_not_called()
def test_sync_gets_empty_state_if_backend_state_does_not_exist(self) -> None:
state_holder = self._create_state_holder()
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assert_state_empty(state_holder.state)
self.assertEqual(self._mock_backend.get_state.call_count, 1)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
def test_sync_gets_backend_state_if_local_state_is_clean(self) -> None:
state_holder = self._create_state_holder()
expected_state = self._create_state()
for attempt in range(1, 4):
with self.subTest(attempt=attempt):
expected_state.round = attempt
self._backend.set_state_internal(expected_state)
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assert_state_equal(state_holder.state, expected_state)
self.assertEqual(self._mock_backend.get_state.call_count, 1)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
self._mock_backend.reset_mock()
def test_sync_gets_backend_state_if_local_state_is_old_and_dirty(self) -> None:
state_holder = self._create_state_holder()
expected_state = self._create_state()
for attempt in range(1, 4):
with self.subTest(attempt=attempt):
self._backend.set_state_internal(expected_state) # Increment token.
state_holder.state.round = attempt
state_holder.mark_dirty()
has_set = state_holder.sync()
self.assertFalse(has_set)
self.assert_state_equal(state_holder.state, expected_state)
self.assertEqual(self._mock_backend.get_state.call_count, 0)
self.assertEqual(self._mock_backend.set_state.call_count, 1)
self._mock_backend.reset_mock()
def test_sync_sets_backend_state_if_local_state_is_new_and_dirty(self) -> None:
state_holder = self._create_state_holder()
for attempt in range(1, 4):
with self.subTest(attempt=attempt):
state_holder.state.round = attempt
state_holder.mark_dirty()
has_set = state_holder.sync()
self.assertTrue(has_set)
expected_state = self._backend.get_state_internal()
self.assert_state_equal(state_holder.state, expected_state)
self.assertEqual(self._mock_backend.get_state.call_count, 0)
self.assertEqual(self._mock_backend.set_state.call_count, 1)
self._mock_backend.reset_mock()
def test_sync_uses_cached_state_if_cache_duration_is_specified(self) -> None:
state = self._create_state()
self._backend.set_state_internal(state)
with patch(
"torch.distributed.elastic.rendezvous.dynamic_rendezvous.time"
) as mock_time:
for cache_duration in [1, 5, 10]:
with self.subTest(cache_duration=cache_duration):
self._cache_duration = cache_duration
state_holder = self._create_state_holder()
mock_time.monotonic.return_value = 5
state_holder.sync()
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assertEqual(self._mock_backend.get_state.call_count, 1)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
mock_time.monotonic.return_value = 5 + self._cache_duration
state_holder.sync()
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assertEqual(self._mock_backend.get_state.call_count, 1)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
self._mock_backend.get_state.reset_mock()
def test_sync_gets_backend_state_if_cached_state_has_expired(self) -> None:
state = self._create_state()
self._backend.set_state_internal(state)
with patch(
"torch.distributed.elastic.rendezvous.dynamic_rendezvous.time"
) as mock_time:
self._cache_duration = 1
state_holder = self._create_state_holder()
mock_time.monotonic.return_value = 5
state_holder.sync()
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assertEqual(self._mock_backend.get_state.call_count, 1)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
mock_time.monotonic.return_value = 5 + self._cache_duration + 0.01
state_holder.sync()
has_set = state_holder.sync()
self.assertIsNone(has_set)
self.assertEqual(self._mock_backend.get_state.call_count, 2)
self.assertEqual(self._mock_backend.set_state.call_count, 0)
def test_sync_sanitizes_state(self) -> None:
state = self._create_state()
expected_state = copy.deepcopy(state)
dead_node1 = _NodeDesc("dead1", 1, 1)
dead_node2 = _NodeDesc("dead2", 1, 1)
dead_node3 = _NodeDesc("dead3", 1, 1)
dead_node4 = _NodeDesc("dead4", 1, 1)
dead_node5 = _NodeDesc("dead5", 1, 1)
state.last_heartbeats[dead_node1] = self._now - timedelta(seconds=91)
state.last_heartbeats[dead_node2] = self._now - timedelta(seconds=100)
state.last_heartbeats[dead_node3] = self._now - timedelta(seconds=110)
state.last_heartbeats[dead_node4] = self._now - timedelta(seconds=120)
state.last_heartbeats[dead_node5] = self._now - timedelta(seconds=130)
state.participants[dead_node1] = 0
state.participants[dead_node2] = 0
state.participants[dead_node3] = 0
state.wait_list.add(dead_node4)
state.wait_list.add(dead_node5)
self._backend.set_state_internal(state)
state_holder = self._create_state_holder()
state_holder.sync()
self.assert_state_equal(state_holder.state, expected_state)
def test_sync_sanitizes_state_if_no_participants_is_left(self) -> None:
state = self._create_state()
expected_state = copy.deepcopy(state)
for node in state.last_heartbeats:
state.last_heartbeats[node] = self._now - timedelta(seconds=100)
expected_state.complete = False
expected_state.round = 1000
expected_state.participants = {}
expected_state.wait_list = set()
expected_state.last_heartbeats = {}
self._backend.set_state_internal(state)
state_holder = self._create_state_holder()
state_holder.sync()
self.assert_state_equal(state_holder.state, expected_state)
def test_sync_raises_error_if_backend_state_is_corrupt(self) -> None:
self._backend.corrupt_state()
state_holder = self._create_state_holder()
with self.assertRaisesRegex(
RendezvousStateError,
r"^The rendezvous state is corrupt. See inner exception for details.$",
):
state_holder.sync()
| BackendRendezvousStateHolderTest |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 22886,
"end": 24757
} | class ____(SingleContinuousDistribution):
_argnames = ('k', 'l')
@staticmethod
def check(k, l):
_value_check(k > 0, "Number of degrees of freedom (k) must be positive.")
_value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.")
_value_check(l > 0, "Shift parameter Lambda must be positive.")
set = Interval(0, oo)
def pdf(self, x):
k, l = self.k, self.l
return exp(-(x**2+l**2)/2)*x**k*l / (l*x)**(k/2) * besseli(k/2-1, l*x)
def ChiNoncentral(name, k, l):
r"""
Create a continuous random variable with a non-central Chi distribution.
Explanation
===========
The density of the non-central Chi distribution is given by
.. math::
f(x) := \frac{e^{-(x^2+\lambda^2)/2} x^k\lambda}
{(\lambda x)^{k/2}} I_{k/2-1}(\lambda x)
with `x \geq 0`. Here, `I_\nu (x)` is the
:ref:`modified Bessel function of the first kind <besseli>`.
Parameters
==========
k : A positive Integer, $k > 0$
The number of degrees of freedom.
lambda : Real number, `\lambda > 0`
Shift parameter.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import ChiNoncentral, density
>>> from sympy import Symbol
>>> k = Symbol("k", integer=True)
>>> l = Symbol("l")
>>> z = Symbol("z")
>>> X = ChiNoncentral("x", k, l)
>>> density(X)(z)
l*z**k*exp(-l**2/2 - z**2/2)*besseli(k/2 - 1, l*z)/(l*z)**(k/2)
References
==========
.. [1] https://en.wikipedia.org/wiki/Noncentral_chi_distribution
"""
return rv(name, ChiNoncentralDistribution, (k, l))
#-------------------------------------------------------------------------------
# Chi squared distribution -----------------------------------------------------
| ChiNoncentralDistribution |
python | django__django | tests/i18n/test_extraction.py | {
"start": 35372,
"end": 37350
} | class ____(ExtractorTests):
PO_FILE_ES = "locale/es/LC_MESSAGES/django.po"
def test_copy_plural_forms(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertIn("Plural-Forms: nplurals=2; plural=(n != 1)", po_contents)
def test_override_plural_forms(self):
"""Ticket #20311."""
management.call_command(
"makemessages", locale=["es"], extensions=["djtpl"], verbosity=0
)
self.assertTrue(os.path.exists(self.PO_FILE_ES))
with open(self.PO_FILE_ES, encoding="utf-8") as fp:
po_contents = fp.read()
found = re.findall(
r'^(?P<value>"Plural-Forms.+?\\n")\s*$',
po_contents,
re.MULTILINE | re.DOTALL,
)
self.assertEqual(1, len(found))
def test_translate_and_plural_blocktranslate_collision(self):
"""
Ensures a correct workaround for the gettext bug when handling a
literal found inside a {% translate %} tag and also in another file
inside a {% blocktranslate %} with a plural (#17375).
"""
management.call_command(
"makemessages", locale=[LOCALE], extensions=["html", "djtpl"], verbosity=0
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertNotIn(
"#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents
)
self.assertMsgId(
"First `translate`, then `blocktranslate` with a plural", po_contents
)
self.assertMsgIdPlural(
"Plural for a `translate` and `blocktranslate` collision case",
po_contents,
)
| CopyPluralFormsExtractorTests |
python | apache__airflow | airflow-core/tests/unit/ti_deps/deps/test_task_concurrency.py | {
"start": 1148,
"end": 2572
} | class ____:
def _get_task(self, **kwargs):
return BaseOperator(task_id="test_task", dag=DAG("test_dag", schedule=None), **kwargs)
@pytest.mark.parametrize(
("kwargs", "num_running_tis", "is_task_concurrency_dep_met"),
[
({}, None, True),
({"max_active_tis_per_dag": 1}, 0, True),
({"max_active_tis_per_dag": 2}, 1, True),
({"max_active_tis_per_dag": 2}, 2, False),
({"max_active_tis_per_dagrun": 2}, 1, True),
({"max_active_tis_per_dagrun": 2}, 2, False),
({"max_active_tis_per_dag": 2, "max_active_tis_per_dagrun": 2}, 1, True),
({"max_active_tis_per_dag": 1, "max_active_tis_per_dagrun": 2}, 1, False),
({"max_active_tis_per_dag": 2, "max_active_tis_per_dagrun": 1}, 1, False),
({"max_active_tis_per_dag": 1, "max_active_tis_per_dagrun": 1}, 1, False),
],
)
def test_concurrency(self, kwargs, num_running_tis, is_task_concurrency_dep_met):
task = self._get_task(start_date=datetime(2016, 1, 1), **kwargs)
dep_context = DepContext()
ti = Mock(task=task, logical_date=datetime(2016, 1, 1))
if num_running_tis is not None:
ti.get_num_running_task_instances.return_value = num_running_tis
assert TaskConcurrencyDep().is_met(ti=ti, dep_context=dep_context) == is_task_concurrency_dep_met
| TestTaskConcurrencyDep |
python | pytorch__pytorch | torch/utils/_sympy/functions.py | {
"start": 40619,
"end": 41680
} | class ____(sympy.Function):
is_real = True
precedence: int = 35 # lower precedence than add
@classmethod
def eval(cls, base, divisor):
# assert base.is_integer is not True, base
# assert divisor.is_integer is not True, divisor
if divisor.is_zero:
raise ZeroDivisionError("division by zero")
if isinstance(base, sympy.Number) and isinstance(divisor, sympy.Number):
return sympy.Float(float(base) / float(divisor))
# Overloaded to be compatible with regular Python. We distinguish this from
# FloatTrueDiv, because the code generation has to be different for this case:
# Python has a fancy algorithm for integer true division that isn't just
# "promote both arguments to float and use float division", so you need to
# codegen it differently. While technically you can work it out from the
# types of the input, this is often inconvenient to do in Inductor codegen,
# so just have a different operator
# NB: Right now, Inductor codegen doesn't implement this correctly lol
| FloatTrueDiv |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 62047,
"end": 62774
} | class ____(object):
"A helper object that compares equal to everything."
def __eq__(self, other):
return True
def __ne__(self, other):
return False
def __repr__(self):
return '<ANY>'
ANY = _ANY()
def _format_call_signature(name, args, kwargs):
message = '%s(%%s)' % name
formatted_args = ''
args_string = ', '.join([repr(arg) for arg in args])
kwargs_string = ', '.join([
'%s=%r' % (key, value) for key, value in kwargs.items()
])
if args_string:
formatted_args = args_string
if kwargs_string:
if formatted_args:
formatted_args += ', '
formatted_args += kwargs_string
return message % formatted_args
| _ANY |
python | plotly__plotly.py | plotly/graph_objs/indicator/_title.py | {
"start": 233,
"end": 3789
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "indicator"
_path_str = "indicator.title"
_valid_props = {"align", "font", "text"}
@property
def align(self):
"""
Sets the horizontal alignment of the title. It defaults to
`center` except for bullet charts for which it defaults to
right.
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'center', 'right']
Returns
-------
Any
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def font(self):
"""
Set the font used to display the title
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.indicator.title.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.indicator.title.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def text(self):
"""
Sets the title of this indicator.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the title. It defaults
to `center` except for bullet charts for which it
defaults to right.
font
Set the font used to display the title
text
Sets the title of this indicator.
"""
def __init__(self, arg=None, align=None, font=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.indicator.Title`
align
Sets the horizontal alignment of the title. It defaults
to `center` except for bullet charts for which it
defaults to right.
font
Set the font used to display the title
text
Sets the title of this indicator.
Returns
-------
Title
"""
super().__init__("title")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.indicator.Title
constructor must be a dict or
an instance of :class:`plotly.graph_objs.indicator.Title`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("font", arg, font)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Title |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 390587,
"end": 395926
} | class ____:
@pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)])
@pytest.mark.parametrize('weights', [None, True])
@pytest.mark.parametrize('keepdims', [False, True])
def test_xp_mean_basic(self, xp, axis, weights, keepdims):
rng = np.random.default_rng(90359458245906)
x = rng.random((3, 4, 5))
x_xp = xp.asarray(x)
w = w_xp = None
if weights:
w = rng.random((1, 5))
w_xp = xp.asarray(w)
x, w = np.broadcast_arrays(x, w)
res = _xp_mean(x_xp, weights=w_xp, axis=axis, keepdims=keepdims)
ref = np.average(x, weights=w, axis=axis, keepdims=keepdims)
xp_assert_close(res, xp.asarray(ref))
def test_non_broadcastable(self, xp):
# non-broadcastable x and weights
x, w = xp.arange(10.), xp.zeros(5)
message = "Array shapes are incompatible for broadcasting."
with pytest.raises(ValueError, match=message):
_xp_mean(x, weights=w)
@pytest.mark.filterwarnings("ignore:divide by zero encountered:RuntimeWarning:dask")
@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
def test_special_cases(self, xp):
# weights sum to zero
weights = xp.asarray([-1., 0., 1.])
res = _xp_mean(xp.asarray([1., 1., 1.]), weights=weights)
xp_assert_close(res, xp.asarray(xp.nan))
res = _xp_mean(xp.asarray([2., 1., 1.]), weights=weights)
xp_assert_close(res, xp.asarray(-np.inf))
res = _xp_mean(xp.asarray([1., 1., 2.]), weights=weights)
xp_assert_close(res, xp.asarray(np.inf))
@pytest.mark.filterwarnings(
"ignore:invalid value encountered:RuntimeWarning"
) # for dask
def test_nan_policy(self, xp):
x = xp.arange(10.)
mask = (x == 3)
x = xp.where(mask, xp.nan, x)
# nan_policy='raise' raises an error
if is_lazy_array(x):
with pytest.raises(TypeError, match='not supported for lazy arrays'):
_xp_mean(x, nan_policy='raise')
else:
with pytest.raises(ValueError, match='The input contains nan values'):
_xp_mean(x, nan_policy='raise')
# `nan_policy='propagate'` is the default, and the result is NaN
res1 = _xp_mean(x)
res2 = _xp_mean(x, nan_policy='propagate')
ref = xp.asarray(xp.nan)
xp_assert_equal(res1, ref)
xp_assert_equal(res2, ref)
# `nan_policy='omit'` omits NaNs in `x`
res = _xp_mean(x, nan_policy='omit')
ref = xp.mean(x[~mask])
xp_assert_close(res, ref)
# `nan_policy='omit'` omits NaNs in `weights`, too
weights = xp.ones(10)
weights = xp.where(mask, xp.nan, weights)
res = _xp_mean(xp.arange(10.), weights=weights, nan_policy='omit')
ref = xp.mean(x[~mask])
xp_assert_close(res, ref)
@skip_xp_backends(eager_only=True)
def test_nan_policy_warns(self, xp):
x = xp.arange(10.)
x = xp.where(x == 3, xp.nan, x)
# Check for warning if omitting NaNs causes empty slice
message = 'After omitting NaNs...'
with pytest.warns(RuntimeWarning, match=message):
res = _xp_mean(x * np.nan, nan_policy='omit')
ref = xp.asarray(xp.nan)
xp_assert_equal(res, ref)
def test_empty(self, xp):
message = 'One or more sample arguments is too small...'
with pytest.warns(SmallSampleWarning, match=message):
res = _xp_mean(xp.asarray([]))
ref = xp.asarray(xp.nan)
xp_assert_equal(res, ref)
message = "All axis-slices of one or more sample arguments..."
with pytest.warns(SmallSampleWarning, match=message):
res = _xp_mean(xp.asarray([[]]), axis=1)
ref = xp.asarray([xp.nan])
xp_assert_equal(res, ref)
res = _xp_mean(xp.asarray([[]]), axis=0)
ref = xp.asarray([])
xp_assert_equal(res, ref)
@pytest.mark.filterwarnings(
"ignore:overflow encountered in reduce:RuntimeWarning"
) # for dask
def test_dtype(self, xp):
max = xp.finfo(xp.float32).max
x_np = np.asarray([max, max], dtype=np.float32)
x_xp = xp.asarray(x_np)
# Overflow occurs for float32 input
with np.errstate(over='ignore'):
res = _xp_mean(x_xp)
ref = np.mean(x_np)
np.testing.assert_equal(ref, np.inf)
xp_assert_close(res, xp.asarray(ref))
# correct result is returned if `float64` is used
res = _xp_mean(x_xp, dtype=xp.float64)
ref = xp.asarray(np.mean(np.asarray(x_np, dtype=np.float64)))
xp_assert_close(res, ref)
def test_integer(self, xp):
# integer inputs are converted to the appropriate float
x = xp.arange(10)
y = xp.arange(10.)
xp_assert_equal(_xp_mean(x), _xp_mean(y))
xp_assert_equal(_xp_mean(y, weights=x), _xp_mean(y, weights=y))
def test_complex_gh22404(self, xp):
rng = np.random.default_rng(90359458245906)
x, y, wx, wy = rng.random((4, 20))
res = _xp_mean(xp.asarray(x + y*1j), weights=xp.asarray(wx + wy*1j))
ref = np.average(x + y*1j, weights=wx + wy*1j)
xp_assert_close(res, xp.asarray(ref))
| TestXP_Mean |
python | docker__docker-py | docker/models/plugins.py | {
"start": 64,
"end": 3374
} | class ____(Model):
"""
A plugin on the server.
"""
def __repr__(self):
return f"<{self.__class__.__name__}: '{self.name}'>"
@property
def name(self):
"""
The plugin's name.
"""
return self.attrs.get('Name')
@property
def enabled(self):
"""
Whether the plugin is enabled.
"""
return self.attrs.get('Enabled')
@property
def settings(self):
"""
A dictionary representing the plugin's configuration.
"""
return self.attrs.get('Settings')
def configure(self, options):
"""
Update the plugin's settings.
Args:
options (dict): A key-value mapping of options.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
self.client.api.configure_plugin(self.name, options)
self.reload()
def disable(self, force=False):
"""
Disable the plugin.
Args:
force (bool): Force disable. Default: False
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
self.client.api.disable_plugin(self.name, force)
self.reload()
def enable(self, timeout=0):
"""
Enable the plugin.
Args:
timeout (int): Timeout in seconds. Default: 0
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
self.client.api.enable_plugin(self.name, timeout)
self.reload()
def push(self):
"""
Push the plugin to a remote registry.
Returns:
A dict iterator streaming the status of the upload.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self.client.api.push_plugin(self.name)
def remove(self, force=False):
"""
Remove the plugin from the server.
Args:
force (bool): Remove even if the plugin is enabled.
Default: False
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self.client.api.remove_plugin(self.name, force=force)
def upgrade(self, remote=None):
"""
Upgrade the plugin.
Args:
remote (string): Remote reference to upgrade to. The
``:latest`` tag is optional and is the default if omitted.
Default: this plugin's name.
Returns:
A generator streaming the decoded API logs
"""
if self.enabled:
raise errors.DockerError(
'Plugin must be disabled before upgrading.'
)
if remote is None:
remote = self.name
privileges = self.client.api.plugin_privileges(remote)
yield from self.client.api.upgrade_plugin(
self.name,
remote,
privileges,
)
self.reload()
| Plugin |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 137157,
"end": 137959
} | class ____(MiscellaneousTest):
INTERPRET: bool = True
def test_async_copy_slice(self):
# https://github.com/jax-ml/jax/issues/33260
def kernel(o):
@functools.partial(pl.run_scoped,
sem=pltpu.SemaphoreType.DMA,
x=pltpu.MemorySpace.VMEM((1,), jnp.float32))
def _(sem, x):
x[...] = jnp.ones_like(x)
@functools.partial(pl.run_scoped,
y=pltpu.MemorySpace.VMEM((1, 1,), jnp.float32))
def _(y):
pltpu.async_copy(x, y.at[0], sem).wait()
o[...] = y[0]
result = pl.pallas_call(kernel, out_shape=jax.ShapeDtypeStruct(
(1,), jnp.float32), interpret=True)()
np.testing.assert_array_equal(result, np.ones((1,), dtype=jnp.float32))
| MiscellaneousInterpretTest |
python | huggingface__transformers | tests/models/deit/test_modeling_deit.py | {
"start": 1770,
"end": 7008
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
type_sequence_label_size=10,
initializer_range=0.02,
num_labels=3,
scope=None,
encoder_stride=2,
mask_ratio=0.5,
attn_implementation="eager",
):
self.parent = parent
self.batch_size = batch_size
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.is_training = is_training
self.use_labels = use_labels
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.type_sequence_label_size = type_sequence_label_size
self.initializer_range = initializer_range
self.scope = scope
self.encoder_stride = encoder_stride
self.attn_implementation = attn_implementation
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
num_patches = (image_size // patch_size) ** 2
self.seq_length = num_patches + 2
self.mask_ratio = mask_ratio
self.num_masks = int(mask_ratio * self.seq_length)
self.mask_length = num_patches
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
labels = None
if self.use_labels:
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
config = self.get_config()
return config, pixel_values, labels
def get_config(self):
return DeiTConfig(
image_size=self.image_size,
patch_size=self.patch_size,
num_channels=self.num_channels,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
is_decoder=False,
initializer_range=self.initializer_range,
encoder_stride=self.encoder_stride,
attn_implementation=self.attn_implementation,
)
def create_and_check_model(self, config, pixel_values, labels):
model = DeiTModel(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
model = DeiTForMaskedImageModeling(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
self.parent.assertEqual(
result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
)
# test greyscale images
config.num_channels = 1
model = DeiTForMaskedImageModeling(config)
model.to(torch_device)
model.eval()
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
result = model(pixel_values)
self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size))
def create_and_check_for_image_classification(self, config, pixel_values, labels):
config.num_labels = self.type_sequence_label_size
model = DeiTForImageClassification(config)
model.to(torch_device)
model.eval()
result = model(pixel_values, labels=labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
# test greyscale images
config.num_channels = 1
model = DeiTForImageClassification(config)
model.to(torch_device)
model.eval()
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
result = model(pixel_values, labels=labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
pixel_values,
labels,
) = config_and_inputs
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
| DeiTModelTester |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 453037,
"end": 455017
} | class ____(YieldExprNode):
def yield_from_func(self, code):
raise NotImplementedError()
def generate_evaluation_code(self, code, source_cname=None, decref_source=False):
if source_cname is None:
self.arg.generate_evaluation_code(code)
result_temp = code.funcstate.allocate_temp(PyrexTypes.PySendResult_type, manage_ref=False)
code.putln("%s = %s(%s, %s, &%s);" % (
result_temp,
self.yield_from_func(code),
Naming.generator_cname,
self.arg.py_result() if source_cname is None else source_cname,
Naming.retval_cname))
if source_cname is None:
self.arg.generate_disposal_code(code)
self.arg.free_temps(code)
elif decref_source:
code.put_decref_clear(source_cname, py_object_type)
code.putln("if (likely(%s == PYGEN_NEXT)) {" % result_temp)
code.put_gotref(Naming.retval_cname, py_object_type)
code.funcstate.release_temp(result_temp) # before generating the yield code
self.generate_yield_code(code)
code.putln("} else if (likely(%s == PYGEN_RETURN)) {" % result_temp)
code.put_gotref(Naming.retval_cname, py_object_type)
if self.result_is_used:
self.fetch_iteration_result(code)
else:
code.put_decref_clear(Naming.retval_cname, py_object_type)
code.putln("} else {")
self.propagate_exception(code)
code.putln("}")
def propagate_exception(self, code):
# YieldExprNode has allocated the result temp for us
code.put_xgotref(Naming.retval_cname, py_object_type)
code.putln(code.error_goto(self.pos))
def fetch_iteration_result(self, code):
# YieldExprNode has allocated the result temp for us
code.putln("%s = %s; %s = NULL;" % (
self.result(),
Naming.retval_cname,
Naming.retval_cname,
))
| _YieldDelegationExprNode |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 4475,
"end": 4572
} | class ____:
name: Annotated[str, 10]
graph: Annotated["Graph", 20]
@dataclass
| GraphArgument |
python | bottlepy__bottle | bottle.py | {
"start": 77879,
"end": 78563
} | class ____(HTTPResponse):
""" A subclass of :class:`HTTPResponse` that triggers error handlers. """
default_status = 500
def __init__(self,
status=None,
body=None,
exception=None,
traceback=None, **more_headers):
self.exception = exception
self.traceback = traceback
super(HTTPError, self).__init__(body, status, **more_headers)
###############################################################################
# Plugins ######################################################################
###############################################################################
| HTTPError |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows_cli.py | {
"start": 1920,
"end": 2019
} | class ____(MetaflowException):
headline = "Argo Workflows name too long"
| ArgoWorkflowsNameTooLong |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py | {
"start": 710,
"end": 831
} | class ____(NamedTuple):
"""docstring"""
a: int
b: object = object()
c: list[int] = [1, 2, 3]
| MyNamedTuple1 |
python | sanic-org__sanic | sanic/cli/app.py | {
"start": 662,
"end": 9793
} | class ____:
DESCRIPTION = indent(
f"""
{get_logo(True)}
To start running a Sanic application, provide a path to the module, where
app is a Sanic() instance in the global scope:
$ sanic path.to.server:app
If the Sanic instance variable is called 'app', you can leave off the last
part, and only provide a path to the module where the instance is:
$ sanic path.to.server
Or, a path to a callable that returns a Sanic() instance:
$ sanic path.to.factory:create_app
Or, a path to a directory to run as a simple HTTP server:
$ sanic ./path/to/static
""",
prefix=" ",
)
def __init__(self) -> None:
width = shutil.get_terminal_size().columns
self.parser = SanicArgumentParser(
prog="sanic",
description=self.DESCRIPTION,
formatter_class=lambda prog: SanicHelpFormatter(
prog,
max_help_position=36 if width > 96 else 24,
indent_increment=4,
width=None,
),
)
self.parser._positionals.title = "Required\n========\n Positional"
self.parser._optionals.title = "Optional\n========\n General"
self.main_process = (
os.environ.get("SANIC_RELOADER_PROCESS", "") != "true"
)
self.args: Namespace = Namespace()
self.groups: list[Group] = []
self.run_mode = "serve"
def attach(self):
if len(sys.argv) > 1 and sys.argv[1] == "inspect":
self.run_mode = "inspect"
self.parser.description = get_logo(True)
make_inspector_parser(self.parser)
return
for group in Group._registry:
instance = group.create(self.parser)
instance.attach()
self.groups.append(instance)
if len(sys.argv) > 2 and sys.argv[2] == "exec":
self.run_mode = "exec"
self.parser.description = get_logo(True)
make_executor_parser(self.parser)
def run(self, parse_args=None):
if self.run_mode == "inspect":
self._inspector()
return
legacy_version = False
if not parse_args:
# This is to provide backwards compat -v to display version
legacy_version = len(sys.argv) == 2 and sys.argv[-1] == "-v"
parse_args = ["--version"] if legacy_version else None
elif parse_args == ["-v"]:
parse_args = ["--version"]
if not legacy_version:
if self.run_mode == "exec":
parse_args = [
a
for a in (parse_args or sys.argv[1:])
if a not in "-h --help".split()
]
parsed, unknown = self.parser.parse_known_args(args=parse_args)
if unknown and parsed.factory:
for arg in unknown:
if arg.startswith("--"):
self.parser.add_argument(arg.split("=")[0])
if self.run_mode == "exec":
self.args, _ = self.parser.parse_known_args(args=parse_args)
else:
self.args = self.parser.parse_args(args=parse_args)
self._precheck()
app_loader = AppLoader(
self.args.target, self.args.factory, self.args.simple, self.args
)
try:
app = self._get_app(app_loader)
kwargs = self._build_run_kwargs()
except ValueError as e:
error_logger.exception(f"Failed to run app: {e}")
else:
if self.run_mode == "exec":
self._executor(app, kwargs)
return
elif self.run_mode != "serve":
raise ValueError(f"Unknown run mode: {self.run_mode}")
if self.args.repl:
self._repl(app)
for http_version in self.args.http:
app.prepare(**kwargs, version=http_version)
if self.args.single:
serve = Sanic.serve_single
else:
serve = partial(Sanic.serve, app_loader=app_loader)
serve(app)
def _inspector(self):
args = sys.argv[2:]
self.args, unknown = self.parser.parse_known_args(args=args)
if unknown:
for arg in unknown:
if arg.startswith("--"):
try:
key, value = arg.split("=")
key = key.lstrip("-")
except ValueError:
value = False if arg.startswith("--no-") else True
key = (
arg.replace("--no-", "")
.lstrip("-")
.replace("-", "_")
)
setattr(self.args, key, value)
kwargs = {**self.args.__dict__}
host = kwargs.pop("host")
port = kwargs.pop("port")
secure = kwargs.pop("secure")
raw = kwargs.pop("raw")
action = kwargs.pop("action") or "info"
api_key = kwargs.pop("api_key")
positional = kwargs.pop("positional", None)
if action == "<custom>" and positional:
action = positional[0]
if len(positional) > 1:
kwargs["args"] = positional[1:]
InspectorClient(host, port, secure, raw, api_key).do(action, **kwargs)
def _executor(self, app: Sanic, kwargs: dict):
args = sys.argv[3:]
Executor(app, kwargs).run(self.args.command, args)
def _repl(self, app: Sanic):
if is_atty():
@app.main_process_ready
async def start_repl(app):
SanicREPL(app, self.args.repl).run()
await app._startup()
elif self.args.repl is True:
error_logger.error(
"Can't start REPL in non-interactive mode. "
"You can only run with --repl in a TTY."
)
def _precheck(self):
# Custom TLS mismatch handling for better diagnostics
if self.main_process and (
# one of cert/key missing
bool(self.args.cert) != bool(self.args.key)
# new and old style self.args used together
or self.args.tls
and self.args.cert
# strict host checking without certs would always fail
or self.args.tlshost
and not self.args.tls
and not self.args.cert
):
self.parser.print_usage(sys.stderr)
message = (
"TLS certificates must be specified by either of:\n"
" --cert certdir/fullchain.pem --key certdir/privkey.pem\n"
" --tls certdir (equivalent to the above)"
)
error_logger.error(message)
sys.exit(1)
def _get_app(self, app_loader: AppLoader):
try:
app = app_loader.load()
except ImportError as e:
if app_loader.module_name.startswith(e.name): # type: ignore
error_logger.error(
f"No module named {e.name} found.\n"
" Example File: project/sanic_server.py -> app\n"
" Example Module: project.sanic_server.app"
)
error_logger.error(
"\nThe error below might have caused the above one:\n"
f"{e.msg}"
)
sys.exit(1)
else:
raise e
return app
def _build_run_kwargs(self):
for group in self.groups:
group.prepare(self.args)
ssl: Union[None, dict, str, list] = []
if self.args.tlshost:
ssl.append(None)
if self.args.cert is not None or self.args.key is not None:
ssl.append(dict(cert=self.args.cert, key=self.args.key))
if self.args.tls:
ssl += self.args.tls
if not ssl:
ssl = None
elif len(ssl) == 1 and ssl[0] is not None:
# Use only one cert, no TLSSelector.
ssl = ssl[0]
kwargs = {
"access_log": self.args.access_log,
"coffee": self.args.coffee,
"debug": self.args.debug,
"fast": self.args.fast,
"host": self.args.host,
"motd": self.args.motd,
"noisy_exceptions": self.args.noisy_exceptions,
"port": self.args.port,
"ssl": ssl,
"unix": self.args.unix,
"verbosity": self.args.verbosity or 0,
"workers": self.args.workers,
"auto_tls": self.args.auto_tls,
"single_process": self.args.single,
}
for maybe_arg in ("auto_reload", "dev"):
if getattr(self.args, maybe_arg, False):
kwargs[maybe_arg] = True
if self.args.dev and all(
arg not in sys.argv for arg in ("--repl", "--no-repl")
):
self.args.repl = _default
if self.args.path:
kwargs["auto_reload"] = True
kwargs["reload_dir"] = self.args.path
return kwargs
| SanicCLI |
python | wandb__wandb | wandb/errors/errors.py | {
"start": 37,
"end": 368
} | class ____(Exception):
"""Base W&B Error.
<!-- lazydoc-ignore-class: internal -->
"""
def __init__(self, message: str, context: dict | None = None) -> None:
super().__init__(message)
self.message = message
# sentry context capture
if context:
self.context = context
| Error |
python | ethereum__web3.py | web3/types.py | {
"start": 5736,
"end": 5804
} | class ____(TypedDict):
subscription: HexBytes
| SubscriptionResponse |
python | django__django | tests/model_inheritance/models.py | {
"start": 2570,
"end": 2613
} | class ____(Supplier):
pass
| CustomSupplier |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 852343,
"end": 853616
} | class ____(sgqlc.types.Type, Node, RepositoryNode):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"database_id",
"discussion",
"gradient_stop_colors",
"pattern",
"pinned_by",
"preconfigured_gradient",
"updated_at",
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
discussion = sgqlc.types.Field(
sgqlc.types.non_null(Discussion), graphql_name="discussion"
)
gradient_stop_colors = sgqlc.types.Field(
sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))),
graphql_name="gradientStopColors",
)
pattern = sgqlc.types.Field(
sgqlc.types.non_null(PinnedDiscussionPattern), graphql_name="pattern"
)
pinned_by = sgqlc.types.Field(sgqlc.types.non_null(Actor), graphql_name="pinnedBy")
preconfigured_gradient = sgqlc.types.Field(
PinnedDiscussionGradient, graphql_name="preconfiguredGradient"
)
updated_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="updatedAt"
)
| PinnedDiscussion |
python | huggingface__transformers | src/transformers/integrations/integration_utils.py | {
"start": 50452,
"end": 60634
} | class ____(TrainerCallback):
"""
A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting
environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`.
"""
def __init__(self):
if not is_mlflow_available():
raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.")
import mlflow
self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
self._initialized = False
self._auto_end_run = False
self._log_artifacts = False
self._ml_flow = mlflow
def setup(self, args, state, model):
"""
Setup the optional MLflow integration.
Environment:
- **HF_MLFLOW_LOG_ARTIFACTS** (`str`, *optional*):
Whether to use MLflow `.log_artifact()` facility to log artifacts. This only makes sense if logging to a
remote server, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in
[`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote
storage will just copy the files to your artifact location.
- **MLFLOW_TRACKING_URI** (`str`, *optional*):
Whether to store runs at a specific path or remote server. Unset by default, which skips setting the
tracking URI entirely.
- **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`):
Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point
to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be
activated. If an experiment with this name does not exist, a new experiment with this name is created.
- **MLFLOW_TAGS** (`str`, *optional*):
A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example:
`os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`.
- **MLFLOW_NESTED_RUN** (`str`, *optional*):
Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current
run.
- **MLFLOW_RUN_ID** (`str`, *optional*):
Allow to reattach to an existing run which can be useful when resuming training from a checkpoint. When
`MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID
and other parameters are ignored.
- **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`):
Whether to flatten the parameters dictionary before logging.
- **MLFLOW_MAX_LOG_PARAMS** (`int`, *optional*):
Set the maximum number of parameters to log in the run.
"""
self._log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
self._nested_run = os.getenv("MLFLOW_NESTED_RUN", "FALSE").upper() in ENV_VARS_TRUE_VALUES
self._tracking_uri = os.getenv("MLFLOW_TRACKING_URI", None)
self._experiment_name = os.getenv("MLFLOW_EXPERIMENT_NAME", None)
self._flatten_params = os.getenv("MLFLOW_FLATTEN_PARAMS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
self._run_id = os.getenv("MLFLOW_RUN_ID", None)
self._max_log_params = os.getenv("MLFLOW_MAX_LOG_PARAMS", None)
# "synchronous" flag is only available with mlflow version >= 2.8.0
# https://github.com/mlflow/mlflow/pull/9705
# https://github.com/mlflow/mlflow/releases/tag/v2.8.0
self._async_log = packaging.version.parse(self._ml_flow.__version__) >= packaging.version.parse("2.8.0")
logger.debug(
f"MLflow experiment_name={self._experiment_name}, run_name={args.run_name}, nested={self._nested_run},"
f" tracking_uri={self._tracking_uri}"
)
if state.is_world_process_zero:
if not self._ml_flow.is_tracking_uri_set():
if self._tracking_uri:
self._ml_flow.set_tracking_uri(self._tracking_uri)
logger.debug(f"MLflow tracking URI is set to {self._tracking_uri}")
else:
logger.debug(
"Environment variable `MLFLOW_TRACKING_URI` is not provided and therefore will not be"
" explicitly set."
)
else:
logger.debug(f"MLflow tracking URI is set to {self._ml_flow.get_tracking_uri()}")
if self._ml_flow.active_run() is None or self._nested_run or self._run_id:
if self._experiment_name:
# Use of set_experiment() ensure that Experiment is created if not exists
self._ml_flow.set_experiment(self._experiment_name)
self._ml_flow.start_run(run_name=args.run_name, nested=self._nested_run)
logger.debug(f"MLflow run started with run_id={self._ml_flow.active_run().info.run_id}")
self._auto_end_run = True
combined_dict = args.to_dict()
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
combined_dict = {**model_config, **combined_dict}
combined_dict = flatten_dict(combined_dict) if self._flatten_params else combined_dict
# remove params that are too long for MLflow
for name, value in list(combined_dict.items()):
# internally, all values are converted to str in MLflow
if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
logger.warning(
f'Trainer is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
" log_param() only accepts values no longer than 250 characters so we dropped this attribute."
" You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and"
" avoid this message."
)
del combined_dict[name]
# MLflow cannot log more than 100 values in one go, so we have to split it
combined_dict_items = list(combined_dict.items())
if self._max_log_params and self._max_log_params.isdigit():
max_log_params = int(self._max_log_params)
if max_log_params < len(combined_dict_items):
logger.debug(
f"Reducing the number of parameters to log from {len(combined_dict_items)} to {max_log_params}."
)
combined_dict_items = combined_dict_items[:max_log_params]
for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
if self._async_log:
self._ml_flow.log_params(
dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]), synchronous=False
)
else:
self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
mlflow_tags = os.getenv("MLFLOW_TAGS", None)
if mlflow_tags:
mlflow_tags = json.loads(mlflow_tags)
self._ml_flow.set_tags(mlflow_tags)
self._initialized = True
def on_train_begin(self, args, state, control, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
def on_log(self, args, state, control, logs, model=None, **kwargs):
if not self._initialized:
self.setup(args, state, model)
if state.is_world_process_zero:
metrics = {}
for k, v in logs.items():
if isinstance(v, (int, float)):
metrics[k] = v
elif isinstance(v, torch.Tensor) and v.numel() == 1:
metrics[k] = v.item()
else:
logger.warning(
f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
"MLflow's log_metric() only accepts float and int types so we dropped this attribute."
)
# sanitize metric names to replace unsupported characters like parentheses
sanitized_metrics = {re.sub(r"[^0-9A-Za-z_\-\.\ :/]", "_", k): v for k, v in metrics.items()}
if self._async_log:
self._ml_flow.log_metrics(metrics=sanitized_metrics, step=state.global_step, synchronous=False)
else:
self._ml_flow.log_metrics(metrics=sanitized_metrics, step=state.global_step)
def on_train_end(self, args, state, control, **kwargs):
if self._initialized and state.is_world_process_zero:
if self._auto_end_run and self._ml_flow.active_run():
self._ml_flow.end_run()
def on_save(self, args, state, control, **kwargs):
if self._initialized and state.is_world_process_zero and self._log_artifacts:
ckpt_dir = f"checkpoint-{state.global_step}"
artifact_path = os.path.join(args.output_dir, ckpt_dir)
logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.")
self._ml_flow.pyfunc.log_model(
ckpt_dir,
artifacts={"model_path": artifact_path},
python_model=self._ml_flow.pyfunc.PythonModel(),
)
def __del__(self):
# if the previous run is not terminated correctly, the fluent API will
# not let you start a new run before the previous one is killed
if (
self._auto_end_run
and callable(getattr(self._ml_flow, "active_run", None))
and self._ml_flow.active_run() is not None
):
self._ml_flow.end_run()
| MLflowCallback |
python | boto__boto3 | boto3/dynamodb/transform.py | {
"start": 5212,
"end": 8738
} | class ____:
"""Injects the transformations into the user provided parameters."""
def __init__(
self,
transformer=None,
condition_builder=None,
serializer=None,
deserializer=None,
):
self._transformer = transformer
if transformer is None:
self._transformer = ParameterTransformer()
self._condition_builder = condition_builder
if condition_builder is None:
self._condition_builder = ConditionExpressionBuilder()
self._serializer = serializer
if serializer is None:
self._serializer = TypeSerializer()
self._deserializer = deserializer
if deserializer is None:
self._deserializer = TypeDeserializer()
def inject_condition_expressions(self, params, model, **kwargs):
"""Injects the condition expression transformation into the parameters
This injection includes transformations for ConditionExpression shapes
and KeyExpression shapes. It also handles any placeholder names and
values that are generated when transforming the condition expressions.
"""
self._condition_builder.reset()
generated_names = {}
generated_values = {}
# Create and apply the Condition Expression transformation.
transformation = ConditionExpressionTransformation(
self._condition_builder,
placeholder_names=generated_names,
placeholder_values=generated_values,
is_key_condition=False,
)
self._transformer.transform(
params, model.input_shape, transformation, 'ConditionExpression'
)
# Create and apply the Key Condition Expression transformation.
transformation = ConditionExpressionTransformation(
self._condition_builder,
placeholder_names=generated_names,
placeholder_values=generated_values,
is_key_condition=True,
)
self._transformer.transform(
params, model.input_shape, transformation, 'KeyExpression'
)
expr_attr_names_input = 'ExpressionAttributeNames'
expr_attr_values_input = 'ExpressionAttributeValues'
# Now that all of the condition expression transformation are done,
# update the placeholder dictionaries in the request.
if expr_attr_names_input in params:
params[expr_attr_names_input].update(generated_names)
else:
if generated_names:
params[expr_attr_names_input] = generated_names
if expr_attr_values_input in params:
params[expr_attr_values_input].update(generated_values)
else:
if generated_values:
params[expr_attr_values_input] = generated_values
def inject_attribute_value_input(self, params, model, **kwargs):
"""Injects DynamoDB serialization into parameter input"""
self._transformer.transform(
params,
model.input_shape,
self._serializer.serialize,
'AttributeValue',
)
def inject_attribute_value_output(self, parsed, model, **kwargs):
"""Injects DynamoDB deserialization into responses"""
if model.output_shape is not None:
self._transformer.transform(
parsed,
model.output_shape,
self._deserializer.deserialize,
'AttributeValue',
)
| TransformationInjector |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 26997,
"end": 27367
} | class ____(HandlerBaseTestCase):
class Handler(RequestHandler):
def get(self):
self.write(dict(protocol=self.request.protocol))
def get_httpserver_options(self):
return dict(protocol="https")
def test_manual_protocol(self):
self.assertEqual(self.fetch_json("/")["protocol"], "https")
@abstract_base_test
| ManualProtocolTest |
python | neetcode-gh__leetcode | python/0787-cheapest-flights-within-k-stops.py | {
"start": 0,
"end": 598
} | class ____:
def findCheapestPrice(
self, n: int, flights: List[List[int]], src: int, dst: int, k: int
) -> int:
prices = [float("inf")] * n
prices[src] = 0
for i in range(k + 1):
tmpPrices = prices.copy()
for s, d, p in flights: # s=source, d=dest, p=price
if prices[s] == float("inf"):
continue
if prices[s] + p < tmpPrices[d]:
tmpPrices[d] = prices[s] + p
prices = tmpPrices
return -1 if prices[dst] == float("inf") else prices[dst]
| Solution |
python | langchain-ai__langchain | libs/partners/perplexity/langchain_perplexity/output_parsers.py | {
"start": 2240,
"end": 3223
} | class ____(
PydanticOutputParser[TBaseModel], Generic[TBaseModel]
):
"""A structured output parser that strips reasoning tags before parsing.
This parser removes any content enclosed in <think> tags from the input text
before delegating to the parent PydanticOutputParser for structured parsing.
"""
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
"""Parse the result of an LLM call to a Pydantic object.
Args:
result: The result of the LLM call.
partial: Whether to parse partial JSON objects.
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
If `False`, the output will be the full JSON object.
"""
text = result[0].text
text = strip_think_tags(text)
return super().parse_result([Generation(text=text)], partial=partial)
| ReasoningStructuredOutputParser |
python | huggingface__transformers | tests/models/moshi/test_modeling_moshi.py | {
"start": 5085,
"end": 16284
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (MoshiModel, MoshiForCausalLM) if is_torch_available() else ()
test_resize_embeddings = True
pipeline_model_mapping = (
{
"feature-extraction": MoshiModel,
"text-generation": MoshiForCausalLM,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = MoshiDecoderTester(self)
self.config_tester = ConfigTester(
self,
config_class=MoshiConfig,
hidden_size=16,
audio_encoder_config={"model_type": self.model_tester.audio_encoder_type},
)
@unittest.skip(reason="The MoshiModel does not have support dynamic compile yet")
@pytest.mark.torch_compile_test
def test_sdpa_can_compile_dynamic(self):
pass
def _get_input_ids_and_config(self, batch_size=1):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(batch_size)
input_ids = inputs_dict.pop("input_ids").to(torch_device)
attention_mask = inputs_dict.pop("attention_mask").to(torch_device)
return config, input_ids, attention_mask, inputs_dict
def _get_logits_processor_kwargs(self, do_sample=False, config=None):
logits_processor_kwargs = {}
return logits_processor_kwargs
@parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION)
def test_eager_matches_sdpa_inference(
self, name, dtype, padding_side, use_attention_mask, output_attentions, enable_kernels
):
if use_attention_mask or (not use_attention_mask and dtype == "fp32" and not output_attentions):
self.skipTest("Test is failing, fix me :) ")
parent_parameterized_test = getattr(ModelTesterMixin, self._testMethodName)
parent_parameterized_test(self)
# Copied from tests.test_modeling_common.ModelTesterMixin.test_resize_tokens_embeddings
def test_resize_tokens_embeddings(self):
if not self.test_resize_embeddings:
self.skipTest(reason="test_resize_embeddings is set to `False`")
(
original_config,
inputs_dict,
) = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
config = copy.deepcopy(original_config)
if is_deepspeed_zero3_enabled():
with deepspeed.zero.Init():
model = model_class(config)
else:
model = model_class(config)
model.to(torch_device)
model_embed_pre_resize = model.get_input_embeddings()
type_model_embed_pre_resize = type(model_embed_pre_resize)
if self.model_tester.is_training is False:
model.eval()
model_vocab_size = config.get_text_config().vocab_size
# Retrieve the embeddings and clone theme
model_embed = model.resize_token_embeddings(model_vocab_size)
cloned_embeddings = model_embed.weight.clone()
# Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
model_embed = model.resize_token_embeddings(model_vocab_size + 10)
new_model_vocab_size = model.config.get_text_config().vocab_size
self.assertEqual(new_model_vocab_size, model_vocab_size + 10)
# Check that it actually resizes the embeddings matrix
self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
# Check to make sure the type of embeddings returned post resizing is same as type of input
type_model_embed_post_resize = type(model_embed)
self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize)
# Check that added embeddings mean is close to the old embeddings mean
if is_deepspeed_zero3_enabled():
with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None):
old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0)
new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0)
else:
old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0)
new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0)
torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3)
# Check that the model can still do a forward pass successfully (every parameter should be resized)
if not is_deepspeed_zero3_enabled():
# A distriputed launcher is needed for the forward pass when deepspeed is enabled
model(**self._prepare_for_class(inputs_dict, model_class))
# Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
model_embed = model.resize_token_embeddings(model_vocab_size - 15)
new_model_vocab_size = model.config.get_text_config().vocab_size
self.assertEqual(new_model_vocab_size, model_vocab_size - 15)
# Check that it actually resizes the embeddings matrix
self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15)
# Check that the model can still do a forward pass successfully (every parameter should be resized)
# Input ids should be clamped to the maximum size of the vocabulary
inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1)
# make sure that decoder_input_ids are resized as well
if not is_deepspeed_zero3_enabled():
# A distriputed launcher is needed for the forward pass when deepspeed is enabled
if "decoder_input_ids" in inputs_dict:
inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1)
model(**self._prepare_for_class(inputs_dict, model_class))
# Check that adding and removing tokens has not modified the first part of the embedding matrix.
models_equal = True
for p1, p2 in zip(cloned_embeddings, model_embed.weight):
if p1.data.ne(p2.data).sum() > 0:
models_equal = False
self.assertTrue(models_equal)
del model
if is_deepspeed_zero3_enabled():
with deepspeed.zero.Init():
model = model_class(config)
else:
model = model_class(config)
model.to(torch_device)
model_vocab_size = config.get_text_config().vocab_size
model.resize_token_embeddings(model_vocab_size + 10, pad_to_multiple_of=1)
new_model_vocab_size = model.config.get_text_config().vocab_size
self.assertTrue(new_model_vocab_size + 10, model_vocab_size)
model_embed = model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=64)
new_model_vocab_size = model.config.get_text_config().vocab_size
self.assertTrue(model_embed.weight.shape[0] // 64, 0)
self.assertTrue(model_embed.weight.shape[0], new_model_vocab_size)
self.assertTrue(new_model_vocab_size, model.vocab_size)
model_embed = model.resize_token_embeddings(model_vocab_size + 13, pad_to_multiple_of=64)
self.assertTrue(model_embed.weight.shape[0] // 64, 0)
# Check that resizing a model to a multiple of pad_to_multiple leads to a model of exactly that size
target_dimension = 128
model_embed = model.resize_token_embeddings(target_dimension, pad_to_multiple_of=64)
self.assertTrue(model_embed.weight.shape[0], target_dimension)
with self.assertRaisesRegex(
ValueError,
"Asking to pad the embedding matrix to a multiple of `1.3`, which is not and integer. Please make sure to pass an integer",
):
model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=1.3)
# Test when `vocab_size` is smaller than `hidden_size`.
del model
config.vocab_size = 4
config.pad_token_id = 4 # Ignore copy
if is_deepspeed_zero3_enabled():
with deepspeed.zero.Init():
model = model_class(config)
else:
model = model_class(config)
model.to(torch_device)
model_vocab_size = config.get_text_config().vocab_size
# Retrieve the embeddings and clone theme
model_embed = model.resize_token_embeddings(model_vocab_size)
cloned_embeddings = model_embed.weight.clone()
# Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
model_embed = model.resize_token_embeddings(model_vocab_size + 10)
new_model_vocab_size = model.config.get_text_config().vocab_size
self.assertEqual(new_model_vocab_size, model_vocab_size + 10)
# Check that it actually resizes the embeddings matrix
self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
# Check to make sure the type of embeddings returned post resizing is same as type of input
type_model_embed_post_resize = type(model_embed)
self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize)
# Check that added embeddings mean is close to the old embeddings mean
if is_deepspeed_zero3_enabled():
with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None):
old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0)
new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0)
else:
old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0)
new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0)
torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3)
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_cpu_offload(self):
pass
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_disk_offload_bin(self):
pass
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_disk_offload_safetensors(self):
pass
@unittest.skip(reason="Test becomes too complex with Moshi requiring multiple input modalities.")
def test_generate_continue_from_inputs_embeds(self):
pass
@is_flaky(max_attempts=5, description="flaky on some models.")
def test_save_load(self):
super().test_save_load()
| MoshiDecoderTest |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared_tests/test_check.py | {
"start": 52303,
"end": 52328
} | class ____(Foo): ...
| SubFoo |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 21816,
"end": 22369
} | class ____(VOTableSpecWarning):
"""
Version 1.0 of the VOTable specification used the ``DEFINITIONS``
element to define coordinate systems. Version 1.1 now uses
``COOSYS`` elements throughout the document.
**References:** `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:definitions>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:definitions>`__
"""
message_template = "The DEFINITIONS element is deprecated in VOTable 1.1. Ignoring"
| W22 |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/transfers/test_local_to_wasb.py | {
"start": 1018,
"end": 2830
} | class ____:
_config = {
"file_path": "file",
"container_name": "container",
"blob_name": "blob",
"wasb_conn_id": "wasb_default",
"retries": 3,
}
def setup_method(self):
args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1, 1)}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
def test_init(self):
operator = LocalFilesystemToWasbOperator(task_id="wasb_operator_1", dag=self.dag, **self._config)
assert operator.file_path == self._config["file_path"]
assert operator.container_name == self._config["container_name"]
assert operator.blob_name == self._config["blob_name"]
assert operator.wasb_conn_id == self._config["wasb_conn_id"]
assert operator.load_options == {}
assert operator.retries == self._config["retries"]
operator = LocalFilesystemToWasbOperator(
task_id="wasb_operator_2", dag=self.dag, load_options={"timeout": 2}, **self._config
)
assert operator.load_options == {"timeout": 2}
@pytest.mark.parametrize(argnames="create_container", argvalues=[True, False])
@mock.patch("airflow.providers.microsoft.azure.transfers.local_to_wasb.WasbHook", autospec=True)
def test_execute(self, mock_hook, create_container):
mock_instance = mock_hook.return_value
operator = LocalFilesystemToWasbOperator(
task_id="wasb_sensor",
dag=self.dag,
create_container=create_container,
load_options={"timeout": 2},
**self._config,
)
operator.execute(None)
mock_instance.load_file.assert_called_once_with(
"file", "container", "blob", create_container, timeout=2
)
| TestLocalFilesystemToWasbOperator |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flows.py | {
"start": 15735,
"end": 24636
} | class ____:
@pytest.fixture
async def flows(self, client):
await client.post("/flows/", json={"name": "my-flow-1"})
await client.post("/flows/", json={"name": "my-flow-2"})
@pytest.mark.usefixtures("flows")
async def test_paginate_flows(self, client):
response = await client.post("/flows/paginate")
assert response.status_code == status.HTTP_200_OK
json = response.json()
assert len(json["results"]) == 2
assert json["page"] == 1
assert json["pages"] == 1
assert json["count"] == 2
@pytest.mark.usefixtures("flows")
async def test_paginate_flows_applies_limit(self, client):
response = await client.post("/flows/paginate", json=dict(limit=1))
assert response.status_code == status.HTTP_200_OK
json = response.json()
assert len(json["results"]) == 1
assert json["page"] == 1
assert json["pages"] == 2
assert json["count"] == 2
async def test_paginate_flows_applies_flow_filter(self, client, session):
flow_1 = await models.flows.create_flow(
session=session,
flow=schemas.core.Flow(name="my-flow-1", tags=["db", "blue"]),
)
await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-2", tags=["db"])
)
await session.commit()
flow_filter = dict(
flows=schemas.filters.FlowFilter(
name=schemas.filters.FlowFilterName(any_=["my-flow-1"])
).model_dump(mode="json")
)
response = await client.post("/flows/paginate", json=flow_filter)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == flow_1.id
async def test_paginate_flows_applies_flow_run_filter(self, client, session):
flow_1 = await models.flows.create_flow(
session=session,
flow=schemas.core.Flow(name="my-flow-1", tags=["db", "blue"]),
)
await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-2", tags=["db"])
)
flow_run_1 = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.actions.FlowRunCreate(flow_id=flow_1.id),
)
await session.commit()
flow_filter = dict(
flow_runs=schemas.filters.FlowRunFilter(
id=schemas.filters.FlowRunFilterId(any_=[flow_run_1.id])
).model_dump(mode="json")
)
response = await client.post("/flows/paginate", json=flow_filter)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == flow_1.id
async def test_paginate_flows_applies_task_run_filter(self, client, session):
flow_1 = await models.flows.create_flow(
session=session,
flow=schemas.core.Flow(name="my-flow-1", tags=["db", "blue"]),
)
await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-2", tags=["db"])
)
flow_run_1 = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.actions.FlowRunCreate(flow_id=flow_1.id),
)
task_run_1 = await models.task_runs.create_task_run(
session=session,
task_run=schemas.actions.TaskRunCreate(
flow_run_id=flow_run_1.id,
task_key="my-key",
dynamic_key="0",
),
)
await session.commit()
flow_filter = dict(
task_runs=schemas.filters.TaskRunFilter(
id=schemas.filters.TaskRunFilterId(any_=[task_run_1.id])
).model_dump(mode="json")
)
response = await client.post("/flows/paginate", json=flow_filter)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == flow_1.id
async def test_paginate_flows_applies_work_pool(self, client, session, work_pool):
flow_1 = await models.flows.create_flow(
session=session,
flow=schemas.core.Flow(name="my-flow-1", tags=["db", "blue"]),
)
await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-2", tags=["db"])
)
await session.commit()
response = await client.post("/flows/paginate")
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["results"]) == 2
# work queue
work_queue = await models.workers.create_work_queue(
session=session,
work_pool_id=work_pool.id,
work_queue=schemas.actions.WorkQueueCreate(name="test-queue"), # type: ignore
)
# deployment
await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment X",
flow_id=flow_1.id,
work_queue_id=work_queue.id,
),
)
await session.commit()
work_pool_filter = dict(
work_pools=schemas.filters.WorkPoolFilter(
id=schemas.filters.WorkPoolFilterId(any_=[work_pool.id])
).model_dump(mode="json")
)
response = await client.post("/flows/paginate", json=work_pool_filter)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == flow_1.id
async def test_paginate_flows_applies_deployment_is_null(self, client, session):
undeployed_flow = await models.flows.create_flow(
session=session,
flow=schemas.core.Flow(name="undeployment_flow"),
)
deployed_flow = await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="deployed_flow")
)
await session.commit()
await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="Mr. Deployment",
flow_id=deployed_flow.id,
),
)
await session.commit()
deployment_filter_isnull = dict(
flows=schemas.filters.FlowFilter(
deployment=schemas.filters.FlowFilterDeployment(is_null_=True)
).model_dump(mode="json")
)
response = await client.post("/flows/paginate", json=deployment_filter_isnull)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == undeployed_flow.id
deployment_filter_not_isnull = dict(
flows=schemas.filters.FlowFilter(
deployment=schemas.filters.FlowFilterDeployment(is_null_=False)
).model_dump(mode="json")
)
response = await client.post(
"/flows/paginate", json=deployment_filter_not_isnull
)
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert UUID(results[0]["id"]) == deployed_flow.id
async def test_paginate_flows_page(self, flows, client):
# right now this works because flows are ordered by name
# by default, when ordering is actually implemented, this test
# should be re-written
response = await client.post("/flows/paginate", json=dict(page=2, limit=1))
assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 1
assert results[0]["name"] == "my-flow-2"
async def test_paginate_flows_sort(self, flows, client):
response = await client.post(
"/flows/paginate", json=dict(sort=schemas.sorting.FlowSort.NAME_ASC)
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["results"][0]["name"] == "my-flow-1"
response_desc = await client.post(
"/flows/paginate", json=dict(sort=schemas.sorting.FlowSort.NAME_DESC)
)
assert response_desc.status_code == status.HTTP_200_OK
assert response_desc.json()["results"][0]["name"] == "my-flow-2"
async def test_read_flows_returns_empty_list(self, client):
response = await client.post("/flows/paginate")
assert response.status_code == status.HTTP_200_OK
assert response.json()["results"] == []
| TestPaginateFlows |
python | chroma-core__chroma | chromadb/utils/embedding_functions/jina_embedding_function.py | {
"start": 411,
"end": 10138
} | class ____(EmbeddingFunction[Embeddable]):
"""
This class is used to get embeddings for a list of texts using the Jina AI API.
It requires an API key and a model name. The default model name is "jina-embeddings-v2-base-en".
"""
def __init__(
self,
api_key: Optional[str] = None,
model_name: str = "jina-embeddings-v2-base-en",
api_key_env_var: str = "CHROMA_JINA_API_KEY",
task: Optional[str] = None,
late_chunking: Optional[bool] = None,
truncate: Optional[bool] = None,
dimensions: Optional[int] = None,
embedding_type: Optional[str] = None,
normalized: Optional[bool] = None,
query_config: Optional[JinaQueryConfig] = None,
):
"""
Initialize the JinaEmbeddingFunction.
Args:
api_key_env_var (str, optional): Environment variable name that contains your API key for the Jina AI API.
Defaults to "CHROMA_JINA_API_KEY".
model_name (str, optional): The name of the model to use for text embeddings.
Defaults to "jina-embeddings-v2-base-en".
task (str, optional): The task to use for the Jina AI API.
Defaults to None.
late_chunking (bool, optional): Whether to use late chunking for the Jina AI API.
Defaults to None.
truncate (bool, optional): Whether to truncate the Jina AI API.
Defaults to None.
dimensions (int, optional): The number of dimensions to use for the Jina AI API.
Defaults to None.
embedding_type (str, optional): The type of embedding to use for the Jina AI API.
Defaults to None.
normalized (bool, optional): Whether to normalize the Jina AI API.
Defaults to None.
"""
try:
import httpx
except ImportError:
raise ValueError(
"The httpx python package is not installed. Please install it with `pip install httpx`"
)
try:
self._PILImage = importlib.import_module("PIL.Image")
except ImportError:
raise ValueError(
"The PIL python package is not installed. Please install it with `pip install pillow`"
)
if api_key is not None:
warnings.warn(
"Direct api_key configuration will not be persisted. "
"Please use environment variables via api_key_env_var for persistent storage.",
DeprecationWarning,
)
if os.getenv("JINA_API_KEY") is not None:
self.api_key_env_var = "JINA_API_KEY"
else:
self.api_key_env_var = api_key_env_var
self.api_key = api_key or os.getenv(self.api_key_env_var)
if not self.api_key:
raise ValueError(
f"The {self.api_key_env_var} environment variable is not set."
)
self.model_name = model_name
# Initialize optional attributes to None
self.task = task
self.late_chunking = late_chunking
self.truncate = truncate
self.dimensions = dimensions
self.embedding_type = embedding_type
self.normalized = normalized
self.query_config = query_config
self._api_url = "https://api.jina.ai/v1/embeddings"
self._session = httpx.Client()
self._session.headers.update(
{"Authorization": f"Bearer {self.api_key}", "Accept-Encoding": "identity"}
)
def _build_payload(self, input: Embeddable, is_query: bool) -> Dict[str, Any]:
payload: Dict[str, Any] = {
"input": [],
"model": self.model_name,
}
if all(is_document(item) for item in input):
payload["input"] = input
else:
for item in input:
if is_document(item):
payload["input"].append({"text": item})
elif is_image(item):
try:
pil_image = self._PILImage.fromarray(item)
buffer = io.BytesIO()
pil_image.save(buffer, format="PNG")
img_bytes = buffer.getvalue()
# Encode bytes to base64 string
base64_string = base64.b64encode(img_bytes).decode("utf-8")
except Exception as e:
raise ValueError(
f"Failed to convert image numpy array to base64 data URI: {e}"
) from e
payload["input"].append({"image": base64_string})
if self.task is not None:
payload["task"] = self.task
if self.late_chunking is not None:
payload["late_chunking"] = self.late_chunking
if self.truncate is not None:
payload["truncate"] = self.truncate
if self.dimensions is not None:
payload["dimensions"] = self.dimensions
if self.embedding_type is not None:
payload["embedding_type"] = self.embedding_type
if self.normalized is not None:
payload["normalized"] = self.normalized
# overwrite parameteres when query payload is used
if is_query and self.query_config is not None:
for key, value in self.query_config.items():
payload[key] = value
return payload
def _convert_resp(self, resp: Any, is_query: bool = False) -> Embeddings:
"""
Convert the response from the Jina AI API to a list of numpy arrays.
Args:
resp (Any): The response from the Jina AI API.
Returns:
Embeddings: A list of numpy arrays representing the embeddings.
"""
if "data" not in resp:
raise RuntimeError(resp.get("detail", "Unknown error"))
embeddings_data: List[Dict[str, Union[int, List[float]]]] = resp["data"]
# Sort resulting embeddings by index
sorted_embeddings = sorted(embeddings_data, key=lambda e: e["index"])
# Return embeddings as numpy arrays
return [
np.array(result["embedding"], dtype=np.float32)
for result in sorted_embeddings
]
def __call__(self, input: Embeddable) -> Embeddings:
"""
Get the embeddings for a list of texts.
Args:
input (Embeddable): A list of texts and/or images to get embeddings for.
Returns:
Embeddings: The embeddings for the texts.
Example:
>>> jina_ai_fn = JinaEmbeddingFunction(api_key_env_var="CHROMA_JINA_API_KEY")
>>> input = ["Hello, world!", "How are you?"]
"""
payload = self._build_payload(input, is_query=False)
# Call Jina AI Embedding API
resp = self._session.post(self._api_url, json=payload, timeout=60).json()
return self._convert_resp(resp)
def embed_query(self, input: Embeddable) -> Embeddings:
payload = self._build_payload(input, is_query=True)
# Call Jina AI Embedding API
resp = self._session.post(self._api_url, json=payload, timeout=60).json()
return self._convert_resp(resp, is_query=True)
@staticmethod
def name() -> str:
return "jina"
def default_space(self) -> Space:
return "cosine"
def supported_spaces(self) -> List[Space]:
return ["cosine", "l2", "ip"]
@staticmethod
def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Embeddable]":
api_key_env_var = config.get("api_key_env_var")
model_name = config.get("model_name")
task = config.get("task")
late_chunking = config.get("late_chunking")
truncate = config.get("truncate")
dimensions = config.get("dimensions")
embedding_type = config.get("embedding_type")
normalized = config.get("normalized")
query_config = config.get("query_config")
if api_key_env_var is None or model_name is None:
assert False, "This code should not be reached" # this is for type checking
return JinaEmbeddingFunction(
api_key_env_var=api_key_env_var,
model_name=model_name,
task=task,
late_chunking=late_chunking,
truncate=truncate,
dimensions=dimensions,
embedding_type=embedding_type,
normalized=normalized,
query_config=query_config,
)
def get_config(self) -> Dict[str, Any]:
return {
"api_key_env_var": self.api_key_env_var,
"model_name": self.model_name,
"task": self.task,
"late_chunking": self.late_chunking,
"truncate": self.truncate,
"dimensions": self.dimensions,
"embedding_type": self.embedding_type,
"normalized": self.normalized,
"query_config": self.query_config,
}
def validate_config_update(
self, old_config: Dict[str, Any], new_config: Dict[str, Any]
) -> None:
if "model_name" in new_config:
raise ValueError(
"The model name cannot be changed after the embedding function has been initialized."
)
@staticmethod
def validate_config(config: Dict[str, Any]) -> None:
"""
Validate the configuration using the JSON schema.
Args:
config: Configuration to validate
Raises:
ValidationError: If the configuration does not match the schema
"""
validate_config_schema(config, "jina")
| JinaEmbeddingFunction |
python | automl__auto-sklearn | test/test_pipeline/test_classification.py | {
"start": 1309,
"end": 2027
} | class ____(AutoSklearnClassificationAlgorithm):
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "AB",
"name": "AdaBoost Classifier",
"handles_regression": False,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": False,
"is_deterministic": True,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (PREDICTIONS,),
}
@staticmethod
def get_hyperparameter_search_space(feat_type=None, dataset_properties=None):
cs = ConfigurationSpace()
return cs
| DummyClassifier |
python | apache__airflow | providers/standard/tests/unit/standard/sensors/test_external_task_sensor.py | {
"start": 58136,
"end": 65251
} | class ____:
TASK_ID = "external_task_sensor_check"
EXTERNAL_DAG_ID = "child_dag" # DAG the external task sensor is waiting on
EXTERNAL_TASK_ID = "child_task" # Task the external task sensor is waiting on
def test_defer_and_fire_task_state_trigger(self):
"""
Asserts that a task is deferred and TaskStateTrigger will be fired
when the ExternalTaskAsyncSensor is provided with all required arguments
(i.e. including the external_task_id).
"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with pytest.raises(TaskDeferred) as exc:
sensor.execute(context=context)
assert isinstance(exc.value.trigger, WorkflowTrigger), "Trigger is not a WorkflowTrigger"
def test_defer_and_fire_failed_state_trigger(self):
"""Tests that an ExternalTaskNotFoundError is raised in case of error event"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with pytest.raises(ExternalTaskNotFoundError):
sensor.execute_complete(
context=context, event={"status": "error", "message": "test failure message"}
)
def test_defer_and_fire_timeout_state_trigger(self):
"""Tests that an ExternalTaskNotFoundError is raised in case of timeout event"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with pytest.raises(ExternalTaskNotFoundError):
sensor.execute_complete(
context=context,
event={"status": "timeout", "message": "Dag was not started within 1 minute, assuming fail."},
)
def test_defer_execute_check_correct_logging(self):
"""Asserts that logging occurs as expected"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with mock.patch.object(sensor.log, "info") as mock_log_info:
sensor.execute_complete(
context=context,
event={"status": "success"},
)
mock_log_info.assert_called_with("External tasks %s has executed successfully.", [EXTERNAL_TASK_ID])
def test_defer_execute_check_failed_status(self):
"""Tests that the execute_complete method properly handles the 'failed' status from WorkflowTrigger"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with pytest.raises(ExternalDagFailedError, match="External job has failed."):
sensor.execute_complete(
context=context,
event={"status": "failed"},
)
def test_defer_execute_check_failed_status_soft_fail(self):
"""Tests that the execute_complete method properly handles the 'failed' status with soft_fail=True"""
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
soft_fail=True,
)
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
with pytest.raises(AirflowSkipException, match="External job has failed skipping."):
sensor.execute_complete(
context=context,
event={"status": "failed"},
)
def test_defer_with_failed_states(self):
"""Tests that failed_states are properly passed to the WorkflowTrigger when the sensor is deferred"""
failed_states = ["failed", "upstream_failed"]
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
failed_states=failed_states,
)
context = {"execution_date": datetime(2025, 1, 1), "logical_date": datetime(2025, 1, 1)}
with pytest.raises(TaskDeferred) as exc:
sensor.execute(context=context)
trigger = exc.value.trigger
assert isinstance(trigger, WorkflowTrigger), "Trigger is not a WorkflowTrigger"
assert trigger.failed_states == failed_states, "failed_states not properly passed to WorkflowTrigger"
def test_defer_execute_complete_re_sets_external_dates_filter_attr(self):
sensor = ExternalTaskSensor(
task_id=TASK_ID,
external_task_id=EXTERNAL_TASK_ID,
external_dag_id=EXTERNAL_DAG_ID,
deferrable=True,
)
assert sensor.external_dates_filter is None
context = {"execution_date": DEFAULT_DATE, "logical_date": DEFAULT_DATE}
sensor.execute_complete(context=context, event={"status": "success"})
assert sensor.external_dates_filter == DEFAULT_DATE.isoformat()
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Needs Flask app context fixture for AF 2")
@pytest.mark.parametrize(
argnames=("external_dag_id", "external_task_id", "expected_external_dag_id", "expected_external_task_id"),
argvalues=[
("dag_test", "task_test", "dag_test", "task_test"),
("dag_{{ ds }}", "task_{{ ds }}", f"dag_{DEFAULT_DATE.date()}", f"task_{DEFAULT_DATE.date()}"),
],
ids=["not_templated", "templated"],
)
def test_external_task_sensor_extra_link(
external_dag_id,
external_task_id,
expected_external_dag_id,
expected_external_task_id,
create_task_instance_of_operator,
):
ti = create_task_instance_of_operator(
ExternalTaskSensor,
dag_id="external_task_sensor_extra_links_dag",
logical_date=DEFAULT_DATE,
task_id="external_task_sensor_extra_links_task",
external_dag_id=external_dag_id,
external_task_id=external_task_id,
)
ti.render_templates()
assert ti.task.external_dag_id == expected_external_dag_id
assert ti.task.external_task_id == expected_external_task_id
assert ti.task.external_task_ids == [expected_external_task_id]
url = ti.task.operator_extra_links[0].get_link(operator=ti.task, ti_key=ti.key)
assert f"/dags/{expected_external_dag_id}/runs" in url
| TestExternalTaskAsyncSensor |
python | getsentry__sentry | src/sentry/interfaces/template.py | {
"start": 125,
"end": 2638
} | class ____(Interface):
"""
A rendered template (generally used like a single frame in a stacktrace).
The attributes ``filename``, ``context_line``, and ``lineno`` are required.
>>> {
>>> "abs_path": "/real/file/name.html"
>>> "filename": "file/name.html",
>>> "pre_context": [
>>> "line1",
>>> "line2"
>>> ],
>>> "context_line": "line3",
>>> "lineno": 3,
>>> "post_context": [
>>> "line4",
>>> "line5"
>>> ],
>>> }
.. note:: This interface can be passed as the 'template' key in addition
to the full interface path.
"""
score = 1100
@classmethod
def to_python(cls, data, **kwargs):
for key in (
"abs_path",
"filename",
"context_line",
"lineno",
"pre_context",
"post_context",
):
data.setdefault(key, None)
return super().to_python(data, **kwargs)
def to_string(self, event) -> str:
context = get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
)
result = ["Stacktrace (most recent call last):", "", self.get_traceback(event, context)]
return "\n".join(result)
def get_traceback(self, event, context):
result = [event.message, "", f'File "{self.filename}", line {self.lineno}', ""]
result.extend([n[1].strip("\n") if n[1] else "" for n in context])
return "\n".join(result)
def get_api_context(self, is_public=False, platform=None):
return {
"lineNo": self.lineno,
"filename": self.filename,
"context": get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
),
}
def get_api_meta(self, meta, is_public=False, platform=None):
return {
"": meta.get(""),
"lineNo": meta.get("lineno"),
"filename": meta.get("filename"),
"context": get_context(
lineno=meta.get("lineno"),
context_line=meta.get("context_line"),
pre_context=meta.get("pre_context"),
post_context=meta.get("post_context"),
),
}
| Template |
python | mwaskom__seaborn | tests/test_matrix.py | {
"start": 24619,
"end": 48942
} | class ____:
rs = np.random.RandomState(sum(map(ord, "clustermap")))
x_norm = rs.randn(4, 8) + np.arange(8)
x_norm = (x_norm.T + np.arange(4)).T
letters = pd.Series(["A", "B", "C", "D", "E", "F", "G", "H"],
name="letters")
df_norm = pd.DataFrame(x_norm, columns=letters)
default_kws = dict(pivot_kws=None, z_score=None, standard_scale=None,
figsize=(10, 10), row_colors=None, col_colors=None,
dendrogram_ratio=.2, colors_ratio=.03,
cbar_pos=(0, .8, .05, .2))
default_plot_kws = dict(metric='euclidean', method='average',
colorbar_kws=None,
row_cluster=True, col_cluster=True,
row_linkage=None, col_linkage=None,
tree_kws=None)
row_colors = color_palette('Set2', df_norm.shape[0])
col_colors = color_palette('Dark2', df_norm.shape[1])
if not _no_scipy:
if _no_fastcluster:
x_norm_distances = distance.pdist(x_norm.T, metric='euclidean')
x_norm_linkage = hierarchy.linkage(x_norm_distances, method='single')
else:
x_norm_linkage = fastcluster.linkage_vector(x_norm.T,
metric='euclidean',
method='single')
x_norm_dendrogram = hierarchy.dendrogram(x_norm_linkage, no_plot=True,
color_threshold=-np.inf)
x_norm_leaves = x_norm_dendrogram['leaves']
df_norm_leaves = np.asarray(df_norm.columns[x_norm_leaves])
def test_ndarray_input(self):
cg = mat.ClusterGrid(self.x_norm, **self.default_kws)
pdt.assert_frame_equal(cg.data, pd.DataFrame(self.x_norm))
assert len(cg.fig.axes) == 4
assert cg.ax_row_colors is None
assert cg.ax_col_colors is None
def test_df_input(self):
cg = mat.ClusterGrid(self.df_norm, **self.default_kws)
pdt.assert_frame_equal(cg.data, self.df_norm)
def test_corr_df_input(self):
df = self.df_norm.corr()
cg = mat.ClusterGrid(df, **self.default_kws)
cg.plot(**self.default_plot_kws)
diag = cg.data2d.values[np.diag_indices_from(cg.data2d)]
npt.assert_array_almost_equal(diag, np.ones(cg.data2d.shape[0]))
def test_pivot_input(self):
df_norm = self.df_norm.copy()
df_norm.index.name = 'numbers'
df_long = pd.melt(df_norm.reset_index(), var_name='letters',
id_vars='numbers')
kws = self.default_kws.copy()
kws['pivot_kws'] = dict(index='numbers', columns='letters',
values='value')
cg = mat.ClusterGrid(df_long, **kws)
pdt.assert_frame_equal(cg.data2d, df_norm)
def test_colors_input(self):
kws = self.default_kws.copy()
kws['row_colors'] = self.row_colors
kws['col_colors'] = self.col_colors
cg = mat.ClusterGrid(self.df_norm, **kws)
npt.assert_array_equal(cg.row_colors, self.row_colors)
npt.assert_array_equal(cg.col_colors, self.col_colors)
assert len(cg.fig.axes) == 6
def test_categorical_colors_input(self):
kws = self.default_kws.copy()
row_colors = pd.Series(self.row_colors, dtype="category")
col_colors = pd.Series(
self.col_colors, dtype="category", index=self.df_norm.columns
)
kws['row_colors'] = row_colors
kws['col_colors'] = col_colors
exp_row_colors = list(map(mpl.colors.to_rgb, row_colors))
exp_col_colors = list(map(mpl.colors.to_rgb, col_colors))
cg = mat.ClusterGrid(self.df_norm, **kws)
npt.assert_array_equal(cg.row_colors, exp_row_colors)
npt.assert_array_equal(cg.col_colors, exp_col_colors)
assert len(cg.fig.axes) == 6
def test_nested_colors_input(self):
kws = self.default_kws.copy()
row_colors = [self.row_colors, self.row_colors]
col_colors = [self.col_colors, self.col_colors]
kws['row_colors'] = row_colors
kws['col_colors'] = col_colors
cm = mat.ClusterGrid(self.df_norm, **kws)
npt.assert_array_equal(cm.row_colors, row_colors)
npt.assert_array_equal(cm.col_colors, col_colors)
assert len(cm.fig.axes) == 6
def test_colors_input_custom_cmap(self):
kws = self.default_kws.copy()
kws['cmap'] = mpl.cm.PRGn
kws['row_colors'] = self.row_colors
kws['col_colors'] = self.col_colors
cg = mat.clustermap(self.df_norm, **kws)
npt.assert_array_equal(cg.row_colors, self.row_colors)
npt.assert_array_equal(cg.col_colors, self.col_colors)
assert len(cg.fig.axes) == 6
def test_z_score(self):
df = self.df_norm.copy()
df = (df - df.mean()) / df.std()
kws = self.default_kws.copy()
kws['z_score'] = 1
cg = mat.ClusterGrid(self.df_norm, **kws)
pdt.assert_frame_equal(cg.data2d, df)
def test_z_score_axis0(self):
df = self.df_norm.copy()
df = df.T
df = (df - df.mean()) / df.std()
df = df.T
kws = self.default_kws.copy()
kws['z_score'] = 0
cg = mat.ClusterGrid(self.df_norm, **kws)
pdt.assert_frame_equal(cg.data2d, df)
def test_standard_scale(self):
df = self.df_norm.copy()
df = (df - df.min()) / (df.max() - df.min())
kws = self.default_kws.copy()
kws['standard_scale'] = 1
cg = mat.ClusterGrid(self.df_norm, **kws)
pdt.assert_frame_equal(cg.data2d, df)
def test_standard_scale_axis0(self):
df = self.df_norm.copy()
df = df.T
df = (df - df.min()) / (df.max() - df.min())
df = df.T
kws = self.default_kws.copy()
kws['standard_scale'] = 0
cg = mat.ClusterGrid(self.df_norm, **kws)
pdt.assert_frame_equal(cg.data2d, df)
def test_z_score_standard_scale(self):
kws = self.default_kws.copy()
kws['z_score'] = True
kws['standard_scale'] = True
with pytest.raises(ValueError):
mat.ClusterGrid(self.df_norm, **kws)
def test_color_list_to_matrix_and_cmap(self):
# Note this uses the attribute named col_colors but tests row colors
matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
self.col_colors, self.x_norm_leaves, axis=0)
for i, leaf in enumerate(self.x_norm_leaves):
color = self.col_colors[leaf]
assert_colors_equal(cmap(matrix[i, 0]), color)
def test_nested_color_list_to_matrix_and_cmap(self):
# Note this uses the attribute named col_colors but tests row colors
colors = [self.col_colors, self.col_colors[::-1]]
matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
colors, self.x_norm_leaves, axis=0)
for i, leaf in enumerate(self.x_norm_leaves):
for j, color_row in enumerate(colors):
color = color_row[leaf]
assert_colors_equal(cmap(matrix[i, j]), color)
def test_color_list_to_matrix_and_cmap_axis1(self):
matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
self.col_colors, self.x_norm_leaves, axis=1)
for j, leaf in enumerate(self.x_norm_leaves):
color = self.col_colors[leaf]
assert_colors_equal(cmap(matrix[0, j]), color)
def test_color_list_to_matrix_and_cmap_different_sizes(self):
colors = [self.col_colors, self.col_colors * 2]
with pytest.raises(ValueError):
matrix, cmap = mat.ClusterGrid.color_list_to_matrix_and_cmap(
colors, self.x_norm_leaves, axis=1)
def test_savefig(self):
# Not sure if this is the right way to test....
cg = mat.ClusterGrid(self.df_norm, **self.default_kws)
cg.plot(**self.default_plot_kws)
cg.savefig(tempfile.NamedTemporaryFile(), format='png')
def test_plot_dendrograms(self):
cm = mat.clustermap(self.df_norm, **self.default_kws)
assert len(cm.ax_row_dendrogram.collections[0].get_paths()) == len(
cm.dendrogram_row.independent_coord
)
assert len(cm.ax_col_dendrogram.collections[0].get_paths()) == len(
cm.dendrogram_col.independent_coord
)
data2d = self.df_norm.iloc[cm.dendrogram_row.reordered_ind,
cm.dendrogram_col.reordered_ind]
pdt.assert_frame_equal(cm.data2d, data2d)
def test_cluster_false(self):
kws = self.default_kws.copy()
kws['row_cluster'] = False
kws['col_cluster'] = False
cm = mat.clustermap(self.df_norm, **kws)
assert len(cm.ax_row_dendrogram.lines) == 0
assert len(cm.ax_col_dendrogram.lines) == 0
assert len(cm.ax_row_dendrogram.get_xticks()) == 0
assert len(cm.ax_row_dendrogram.get_yticks()) == 0
assert len(cm.ax_col_dendrogram.get_xticks()) == 0
assert len(cm.ax_col_dendrogram.get_yticks()) == 0
pdt.assert_frame_equal(cm.data2d, self.df_norm)
def test_row_col_colors(self):
kws = self.default_kws.copy()
kws['row_colors'] = self.row_colors
kws['col_colors'] = self.col_colors
cm = mat.clustermap(self.df_norm, **kws)
assert len(cm.ax_row_colors.collections) == 1
assert len(cm.ax_col_colors.collections) == 1
def test_cluster_false_row_col_colors(self):
kws = self.default_kws.copy()
kws['row_cluster'] = False
kws['col_cluster'] = False
kws['row_colors'] = self.row_colors
kws['col_colors'] = self.col_colors
cm = mat.clustermap(self.df_norm, **kws)
assert len(cm.ax_row_dendrogram.lines) == 0
assert len(cm.ax_col_dendrogram.lines) == 0
assert len(cm.ax_row_dendrogram.get_xticks()) == 0
assert len(cm.ax_row_dendrogram.get_yticks()) == 0
assert len(cm.ax_col_dendrogram.get_xticks()) == 0
assert len(cm.ax_col_dendrogram.get_yticks()) == 0
assert len(cm.ax_row_colors.collections) == 1
assert len(cm.ax_col_colors.collections) == 1
pdt.assert_frame_equal(cm.data2d, self.df_norm)
def test_row_col_colors_df(self):
kws = self.default_kws.copy()
kws['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),
'row_2': list(self.row_colors)},
index=self.df_norm.index,
columns=['row_1', 'row_2'])
kws['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),
'col_2': list(self.col_colors)},
index=self.df_norm.columns,
columns=['col_1', 'col_2'])
cm = mat.clustermap(self.df_norm, **kws)
row_labels = [l.get_text() for l in
cm.ax_row_colors.get_xticklabels()]
assert cm.row_color_labels == ['row_1', 'row_2']
assert row_labels == cm.row_color_labels
col_labels = [l.get_text() for l in
cm.ax_col_colors.get_yticklabels()]
assert cm.col_color_labels == ['col_1', 'col_2']
assert col_labels == cm.col_color_labels
def test_row_col_colors_df_shuffled(self):
# Tests if colors are properly matched, even if given in wrong order
m, n = self.df_norm.shape
shuffled_inds = [self.df_norm.index[i] for i in
list(range(0, m, 2)) + list(range(1, m, 2))]
shuffled_cols = [self.df_norm.columns[i] for i in
list(range(0, n, 2)) + list(range(1, n, 2))]
kws = self.default_kws.copy()
row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},
index=self.df_norm.index)
kws['row_colors'] = row_colors.loc[shuffled_inds]
col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},
index=self.df_norm.columns)
kws['col_colors'] = col_colors.loc[shuffled_cols]
cm = mat.clustermap(self.df_norm, **kws)
assert list(cm.col_colors)[0] == list(self.col_colors)
assert list(cm.row_colors)[0] == list(self.row_colors)
def test_row_col_colors_df_missing(self):
kws = self.default_kws.copy()
row_colors = pd.DataFrame({'row_annot': list(self.row_colors)},
index=self.df_norm.index)
kws['row_colors'] = row_colors.drop(self.df_norm.index[0])
col_colors = pd.DataFrame({'col_annot': list(self.col_colors)},
index=self.df_norm.columns)
kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])
cm = mat.clustermap(self.df_norm, **kws)
assert list(cm.col_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])
assert list(cm.row_colors)[0] == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])
def test_row_col_colors_df_one_axis(self):
# Test case with only row annotation.
kws1 = self.default_kws.copy()
kws1['row_colors'] = pd.DataFrame({'row_1': list(self.row_colors),
'row_2': list(self.row_colors)},
index=self.df_norm.index,
columns=['row_1', 'row_2'])
cm1 = mat.clustermap(self.df_norm, **kws1)
row_labels = [l.get_text() for l in
cm1.ax_row_colors.get_xticklabels()]
assert cm1.row_color_labels == ['row_1', 'row_2']
assert row_labels == cm1.row_color_labels
# Test case with only col annotation.
kws2 = self.default_kws.copy()
kws2['col_colors'] = pd.DataFrame({'col_1': list(self.col_colors),
'col_2': list(self.col_colors)},
index=self.df_norm.columns,
columns=['col_1', 'col_2'])
cm2 = mat.clustermap(self.df_norm, **kws2)
col_labels = [l.get_text() for l in
cm2.ax_col_colors.get_yticklabels()]
assert cm2.col_color_labels == ['col_1', 'col_2']
assert col_labels == cm2.col_color_labels
def test_row_col_colors_series(self):
kws = self.default_kws.copy()
kws['row_colors'] = pd.Series(list(self.row_colors), name='row_annot',
index=self.df_norm.index)
kws['col_colors'] = pd.Series(list(self.col_colors), name='col_annot',
index=self.df_norm.columns)
cm = mat.clustermap(self.df_norm, **kws)
row_labels = [l.get_text() for l in cm.ax_row_colors.get_xticklabels()]
assert cm.row_color_labels == ['row_annot']
assert row_labels == cm.row_color_labels
col_labels = [l.get_text() for l in cm.ax_col_colors.get_yticklabels()]
assert cm.col_color_labels == ['col_annot']
assert col_labels == cm.col_color_labels
def test_row_col_colors_series_shuffled(self):
# Tests if colors are properly matched, even if given in wrong order
m, n = self.df_norm.shape
shuffled_inds = [self.df_norm.index[i] for i in
list(range(0, m, 2)) + list(range(1, m, 2))]
shuffled_cols = [self.df_norm.columns[i] for i in
list(range(0, n, 2)) + list(range(1, n, 2))]
kws = self.default_kws.copy()
row_colors = pd.Series(list(self.row_colors), name='row_annot',
index=self.df_norm.index)
kws['row_colors'] = row_colors.loc[shuffled_inds]
col_colors = pd.Series(list(self.col_colors), name='col_annot',
index=self.df_norm.columns)
kws['col_colors'] = col_colors.loc[shuffled_cols]
cm = mat.clustermap(self.df_norm, **kws)
assert list(cm.col_colors) == list(self.col_colors)
assert list(cm.row_colors) == list(self.row_colors)
def test_row_col_colors_series_missing(self):
kws = self.default_kws.copy()
row_colors = pd.Series(list(self.row_colors), name='row_annot',
index=self.df_norm.index)
kws['row_colors'] = row_colors.drop(self.df_norm.index[0])
col_colors = pd.Series(list(self.col_colors), name='col_annot',
index=self.df_norm.columns)
kws['col_colors'] = col_colors.drop(self.df_norm.columns[0])
cm = mat.clustermap(self.df_norm, **kws)
assert list(cm.col_colors) == [(1.0, 1.0, 1.0)] + list(self.col_colors[1:])
assert list(cm.row_colors) == [(1.0, 1.0, 1.0)] + list(self.row_colors[1:])
def test_row_col_colors_ignore_heatmap_kwargs(self):
g = mat.clustermap(self.rs.uniform(0, 200, self.df_norm.shape),
row_colors=self.row_colors,
col_colors=self.col_colors,
cmap="Spectral",
norm=mpl.colors.LogNorm(),
vmax=100)
assert np.array_equal(
np.array(self.row_colors)[g.dendrogram_row.reordered_ind],
g.ax_row_colors.collections[0].get_facecolors()[:, :3]
)
assert np.array_equal(
np.array(self.col_colors)[g.dendrogram_col.reordered_ind],
g.ax_col_colors.collections[0].get_facecolors()[:, :3]
)
def test_row_col_colors_raise_on_mixed_index_types(self):
row_colors = pd.Series(
list(self.row_colors), name="row_annot", index=self.df_norm.index
)
col_colors = pd.Series(
list(self.col_colors), name="col_annot", index=self.df_norm.columns
)
with pytest.raises(TypeError):
mat.clustermap(self.x_norm, row_colors=row_colors)
with pytest.raises(TypeError):
mat.clustermap(self.x_norm, col_colors=col_colors)
def test_mask_reorganization(self):
kws = self.default_kws.copy()
kws["mask"] = self.df_norm > 0
g = mat.clustermap(self.df_norm, **kws)
npt.assert_array_equal(g.data2d.index, g.mask.index)
npt.assert_array_equal(g.data2d.columns, g.mask.columns)
npt.assert_array_equal(g.mask.index,
self.df_norm.index[
g.dendrogram_row.reordered_ind])
npt.assert_array_equal(g.mask.columns,
self.df_norm.columns[
g.dendrogram_col.reordered_ind])
def test_ticklabel_reorganization(self):
kws = self.default_kws.copy()
xtl = np.arange(self.df_norm.shape[1])
kws["xticklabels"] = list(xtl)
ytl = self.letters.loc[:self.df_norm.shape[0]]
kws["yticklabels"] = ytl
g = mat.clustermap(self.df_norm, **kws)
xtl_actual = [t.get_text() for t in g.ax_heatmap.get_xticklabels()]
ytl_actual = [t.get_text() for t in g.ax_heatmap.get_yticklabels()]
xtl_want = xtl[g.dendrogram_col.reordered_ind].astype("<U1")
ytl_want = ytl[g.dendrogram_row.reordered_ind].astype("<U1")
npt.assert_array_equal(xtl_actual, xtl_want)
npt.assert_array_equal(ytl_actual, ytl_want)
def test_noticklabels(self):
kws = self.default_kws.copy()
kws["xticklabels"] = False
kws["yticklabels"] = False
g = mat.clustermap(self.df_norm, **kws)
xtl_actual = [t.get_text() for t in g.ax_heatmap.get_xticklabels()]
ytl_actual = [t.get_text() for t in g.ax_heatmap.get_yticklabels()]
assert xtl_actual == []
assert ytl_actual == []
def test_size_ratios(self):
# The way that wspace/hspace work in GridSpec, the mapping from input
# ratio to actual width/height of each axes is complicated, so this
# test is just going to assert comparative relationships
kws1 = self.default_kws.copy()
kws1.update(dendrogram_ratio=.2, colors_ratio=.03,
col_colors=self.col_colors, row_colors=self.row_colors)
kws2 = kws1.copy()
kws2.update(dendrogram_ratio=.3, colors_ratio=.05)
g1 = mat.clustermap(self.df_norm, **kws1)
g2 = mat.clustermap(self.df_norm, **kws2)
assert (g2.ax_col_dendrogram.get_position().height
> g1.ax_col_dendrogram.get_position().height)
assert (g2.ax_col_colors.get_position().height
> g1.ax_col_colors.get_position().height)
assert (g2.ax_heatmap.get_position().height
< g1.ax_heatmap.get_position().height)
assert (g2.ax_row_dendrogram.get_position().width
> g1.ax_row_dendrogram.get_position().width)
assert (g2.ax_row_colors.get_position().width
> g1.ax_row_colors.get_position().width)
assert (g2.ax_heatmap.get_position().width
< g1.ax_heatmap.get_position().width)
kws1 = self.default_kws.copy()
kws1.update(col_colors=self.col_colors)
kws2 = kws1.copy()
kws2.update(col_colors=[self.col_colors, self.col_colors])
g1 = mat.clustermap(self.df_norm, **kws1)
g2 = mat.clustermap(self.df_norm, **kws2)
assert (g2.ax_col_colors.get_position().height
> g1.ax_col_colors.get_position().height)
kws1 = self.default_kws.copy()
kws1.update(dendrogram_ratio=(.2, .2))
kws2 = kws1.copy()
kws2.update(dendrogram_ratio=(.2, .3))
g1 = mat.clustermap(self.df_norm, **kws1)
g2 = mat.clustermap(self.df_norm, **kws2)
# Fails on pinned matplotlib?
# assert (g2.ax_row_dendrogram.get_position().width
# == g1.ax_row_dendrogram.get_position().width)
assert g1.gs.get_width_ratios() == g2.gs.get_width_ratios()
assert (g2.ax_col_dendrogram.get_position().height
> g1.ax_col_dendrogram.get_position().height)
def test_cbar_pos(self):
kws = self.default_kws.copy()
kws["cbar_pos"] = (.2, .1, .4, .3)
g = mat.clustermap(self.df_norm, **kws)
pos = g.ax_cbar.get_position()
assert pytest.approx(tuple(pos.p0)) == kws["cbar_pos"][:2]
assert pytest.approx(pos.width) == kws["cbar_pos"][2]
assert pytest.approx(pos.height) == kws["cbar_pos"][3]
kws["cbar_pos"] = None
g = mat.clustermap(self.df_norm, **kws)
assert g.ax_cbar is None
def test_square_warning(self):
kws = self.default_kws.copy()
g1 = mat.clustermap(self.df_norm, **kws)
with pytest.warns(UserWarning):
kws["square"] = True
g2 = mat.clustermap(self.df_norm, **kws)
g1_shape = g1.ax_heatmap.get_position().get_points()
g2_shape = g2.ax_heatmap.get_position().get_points()
assert np.array_equal(g1_shape, g2_shape)
def test_clustermap_annotation(self):
g = mat.clustermap(self.df_norm, annot=True, fmt=".1f")
for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):
assert text.get_text() == f"{val:.1f}"
g = mat.clustermap(self.df_norm, annot=self.df_norm, fmt=".1f")
for val, text in zip(np.asarray(g.data2d).flat, g.ax_heatmap.texts):
assert text.get_text() == f"{val:.1f}"
def test_tree_kws(self):
rgb = (1, .5, .2)
g = mat.clustermap(self.df_norm, tree_kws=dict(color=rgb))
for ax in [g.ax_col_dendrogram, g.ax_row_dendrogram]:
tree, = ax.collections
assert tuple(tree.get_color().squeeze())[:3] == rgb
if _no_scipy:
def test_required_scipy_errors():
x = np.random.normal(0, 1, (10, 10))
with pytest.raises(RuntimeError):
mat.clustermap(x)
with pytest.raises(RuntimeError):
mat.ClusterGrid(x)
with pytest.raises(RuntimeError):
mat.dendrogram(x)
| TestClustermap |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/graph_decorator.py | {
"start": 563,
"end": 9278
} | class ____:
name: Optional[str]
description: Optional[str]
input_defs: Sequence[InputDefinition]
output_defs: Optional[Sequence[OutputDefinition]]
ins: Optional[Mapping[str, GraphIn]]
out: Optional[Union[GraphOut, Mapping[str, GraphOut]]]
tags: Optional[Mapping[str, str]]
config_mapping: Optional[ConfigMapping]
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
input_defs: Optional[Sequence[InputDefinition]] = None,
output_defs: Optional[Sequence[OutputDefinition]] = None,
ins: Optional[Mapping[str, GraphIn]] = None,
out: Optional[Union[GraphOut, Mapping[str, GraphOut]]] = None,
tags: Optional[Mapping[str, Any]] = None,
config_mapping: Optional[ConfigMapping] = None,
):
self.name = check.opt_str_param(name, "name")
self.description = check.opt_str_param(description, "description")
self.input_defs = check.opt_sequence_param(
input_defs, "input_defs", of_type=InputDefinition
)
self.did_pass_outputs = output_defs is not None or out is not None
self.output_defs = check.opt_nullable_sequence_param(
output_defs, "output_defs", of_type=OutputDefinition
)
self.ins = ins
self.out = out
self.tags = tags
self.config_mapping = check.opt_inst_param(config_mapping, "config_mapping", ConfigMapping)
def __call__(self, fn: Callable[..., Any]) -> GraphDefinition:
check.callable_param(fn, "fn")
if not self.name:
self.name = fn.__name__
if self.ins is not None:
input_defs = [inp.to_definition(name) for name, inp in self.ins.items()]
else:
input_defs = check.opt_list_param(
self.input_defs, "input_defs", of_type=InputDefinition
)
if self.out is None:
output_defs = self.output_defs
elif isinstance(self.out, GraphOut):
output_defs = [self.out.to_definition(name=None)]
else:
check.dict_param(self.out, "out", key_type=str, value_type=GraphOut)
output_defs = [out.to_definition(name=name) for name, out in self.out.items()]
from dagster._core.definitions.composition import do_composition
(
input_mappings,
output_mappings,
dependencies,
node_defs,
config_mapping,
positional_inputs,
input_assets,
) = do_composition(
decorator_name="@graph",
graph_name=self.name,
fn=fn,
provided_input_defs=input_defs,
provided_output_defs=output_defs,
ignore_output_from_composition_fn=False,
config_mapping=self.config_mapping,
)
graph_def = GraphDefinition(
name=self.name,
dependencies=dependencies,
node_defs=node_defs,
description=self.description or format_docstring_for_description(fn),
input_mappings=input_mappings,
output_mappings=output_mappings,
config=config_mapping,
positional_inputs=positional_inputs,
tags=self.tags,
input_assets=input_assets,
composition_fn=fn,
)
update_wrapper(graph_def, fn)
return graph_def
@overload
def graph(compose_fn: Callable[..., Any]) -> GraphDefinition: ...
@overload
def graph(
*,
name: Optional[str] = ...,
description: Optional[str] = ...,
input_defs: Optional[Sequence[InputDefinition]] = ...,
output_defs: Optional[Sequence[OutputDefinition]] = ...,
ins: Optional[Mapping[str, GraphIn]] = ...,
out: Optional[Union[GraphOut, Mapping[str, GraphOut]]] = ...,
tags: Optional[Mapping[str, Any]] = ...,
config: Optional[Union[ConfigMapping, Mapping[str, Any]]] = ...,
) -> _Graph: ...
@public
def graph(
compose_fn: Optional[Callable] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
input_defs: Optional[Sequence[InputDefinition]] = None,
output_defs: Optional[Sequence[OutputDefinition]] = None,
ins: Optional[Mapping[str, GraphIn]] = None,
out: Optional[Union[GraphOut, Mapping[str, GraphOut]]] = None,
tags: Optional[Mapping[str, Any]] = None,
config: Optional[Union[ConfigMapping, Mapping[str, Any]]] = None,
) -> Union[GraphDefinition, _Graph]:
"""Create an op graph with the specified parameters from the decorated composition function.
Using this decorator allows you to build up a dependency graph by writing a
function that invokes ops (or other graphs) and passes the output to subsequent invocations.
Args:
name (Optional[str]):
The name of the op graph. Must be unique within any :py:class:`RepositoryDefinition` containing the graph.
description (Optional[str]):
A human-readable description of the graph.
input_defs (Optional[List[InputDefinition]]):
Information about the inputs that this graph maps. Information provided here
will be combined with what can be inferred from the function signature, with these
explicit InputDefinitions taking precedence.
Uses of inputs in the body of the decorated composition function will determine
the :py:class:`InputMappings <InputMapping>` passed to the underlying
:py:class:`GraphDefinition`.
output_defs (Optional[List[OutputDefinition]]):
Output definitions for the graph. If not provided explicitly, these will be inferred from typehints.
Uses of these outputs in the body of the decorated composition function, as well as the
return value of the decorated function, will be used to infer the appropriate set of
:py:class:`OutputMappings <OutputMapping>` for the underlying
:py:class:`GraphDefinition`.
To map multiple outputs, return a dictionary from the composition function.
ins (Optional[Dict[str, GraphIn]]):
Information about the inputs that this graph maps. Information provided here
will be combined with what can be inferred from the function signature, with these
explicit GraphIn taking precedence.
out (Optional[Union[GraphOut, Dict[str, GraphOut]]]):
Information about the outputs that this graph maps. Information provided here will be
combined with what can be inferred from the return type signature if the function does
not use yield.
To map multiple outputs, return a dictionary from the composition function.
tags (Optional[Dict[str, Any]]): Arbitrary metadata for any execution run of the graph.
Values that are not strings will be json encoded and must meet the criteria that
`json.loads(json.dumps(value)) == value`. These tag values may be overwritten by tag
values provided at invocation time.
config (Optional[Union[ConfigMapping], Mapping[str, Any]):
Describes how the graph is configured at runtime.
If a :py:class:`ConfigMapping` object is provided, then the graph takes on the config
schema of this object. The mapping will be applied at runtime to generate the config for
the graph's constituent nodes.
If a dictionary is provided, then it will be used as the default run config for the
graph. This means it must conform to the config schema of the underlying nodes. Note
that the values provided will be viewable and editable in the Dagster UI, so be careful
with secrets. its constituent nodes.
If no value is provided, then the config schema for the graph is the default (derived
from the underlying nodes).
"""
if compose_fn is not None:
check.invariant(description is None)
return _Graph()(compose_fn)
config_mapping = None
# Case 1: a dictionary of config is provided, convert to config mapping.
if config is not None and not isinstance(config, ConfigMapping):
config = check.dict_param(config, "config", key_type=str)
config_mapping = ConfigMapping(config_fn=lambda _: config, config_schema=None)
# Case 2: actual config mapping is provided.
else:
config_mapping = config
return _Graph(
name=name,
description=description,
input_defs=input_defs,
output_defs=output_defs,
ins=ins,
out=out,
tags=tags,
config_mapping=config_mapping,
)
| _Graph |
python | great-expectations__great_expectations | great_expectations/data_context/types/base.py | {
"start": 60860,
"end": 67594
} | class ____(BaseStoreBackendDefaults):
"""
Default store configs for Google Cloud Storage (GCS) backends, with some accessible parameters
Args:
default_bucket_name: Use this bucket name for stores that do not have a bucket name provided
default_project_name: Use this project name for stores that do not have a project name provided
expectations_store_bucket_name: Overrides default_bucket_name if supplied
validation_results_store_bucket_name: Overrides default_bucket_name if supplied
data_docs_bucket_name: Overrides default_bucket_name if supplied
checkpoint_store_bucket_name: Overrides default_bucket_name if supplied
expectations_store_project_name: Overrides default_project_name if supplied
validation_results_store_project_name: Overrides default_project_name if supplied
data_docs_project_name: Overrides default_project_name if supplied
checkpoint_store_project_name: Overrides default_project_name if supplied
expectations_store_prefix: Overrides default if supplied
validation_results_store_prefix: Overrides default if supplied
data_docs_prefix: Overrides default if supplied
checkpoint_store_prefix: Overrides default if supplied
expectations_store_name: Overrides default if supplied
validation_results_store_name: Overrides default if supplied
checkpoint_store_name: Overrides default if supplied
""" # noqa: E501 # FIXME CoP
def __init__( # noqa: C901, PLR0913 # FIXME CoP
self,
default_bucket_name: Optional[str] = None,
default_project_name: Optional[str] = None,
expectations_store_bucket_name: Optional[str] = None,
validation_results_store_bucket_name: Optional[str] = None,
validation_definition_store_bucket_name: Optional[str] = None,
data_docs_bucket_name: Optional[str] = None,
checkpoint_store_bucket_name: Optional[str] = None,
expectations_store_project_name: Optional[str] = None,
validation_results_store_project_name: Optional[str] = None,
validation_definition_store_project_name: Optional[str] = None,
data_docs_project_name: Optional[str] = None,
checkpoint_store_project_name: Optional[str] = None,
expectations_store_prefix: str = "expectations",
validation_results_store_prefix: str = "validations",
validation_definition_store_prefix: str = "validation_definitions",
data_docs_prefix: str = "data_docs",
checkpoint_store_prefix: str = "checkpoints",
expectations_store_name: str = "expectations_GCS_store",
validation_results_store_name: str = "validation_results_GCS_store",
checkpoint_store_name: str = "checkpoint_GCS_store",
) -> None:
# Initialize base defaults
super().__init__()
# Use default_bucket_name if separate store buckets are not provided
if expectations_store_bucket_name is None:
expectations_store_bucket_name = default_bucket_name
if validation_results_store_bucket_name is None:
validation_results_store_bucket_name = default_bucket_name
if validation_definition_store_bucket_name is None:
validation_definition_store_bucket_name = default_bucket_name
if data_docs_bucket_name is None:
data_docs_bucket_name = default_bucket_name
if checkpoint_store_bucket_name is None:
checkpoint_store_bucket_name = default_bucket_name
# Use default_project_name if separate store projects are not provided
if expectations_store_project_name is None:
expectations_store_project_name = default_project_name
if validation_results_store_project_name is None:
validation_results_store_project_name = default_project_name
if validation_definition_store_project_name is None:
validation_definition_store_project_name = default_project_name
if data_docs_project_name is None:
data_docs_project_name = default_project_name
if checkpoint_store_project_name is None:
checkpoint_store_project_name = default_project_name
# Overwrite defaults
self.expectations_store_name = expectations_store_name
self.validation_results_store_name = validation_results_store_name
self.checkpoint_store_name = checkpoint_store_name
self.stores = {
expectations_store_name: {
"class_name": "ExpectationsStore",
"store_backend": {
"class_name": "TupleGCSStoreBackend",
"project": expectations_store_project_name,
"bucket": expectations_store_bucket_name,
"prefix": expectations_store_prefix,
},
},
validation_results_store_name: {
"class_name": "ValidationResultsStore",
"store_backend": {
"class_name": "TupleGCSStoreBackend",
"project": validation_results_store_project_name,
"bucket": validation_results_store_bucket_name,
"prefix": validation_results_store_prefix,
},
},
self.validation_definition_store_name: {
"class_name": "ValidationDefinitionStore",
"store_backend": {
"class_name": "TupleGCSStoreBackend",
"project": validation_definition_store_project_name,
"bucket": validation_definition_store_bucket_name,
"prefix": validation_definition_store_prefix,
},
},
checkpoint_store_name: {
"class_name": "CheckpointStore",
"store_backend": {
"class_name": "TupleGCSStoreBackend",
"project": checkpoint_store_project_name,
"bucket": checkpoint_store_bucket_name,
"prefix": checkpoint_store_prefix,
},
},
}
self.data_docs_sites = {
"gcs_site": {
"class_name": "SiteBuilder",
"show_how_to_buttons": True,
"store_backend": {
"class_name": "TupleGCSStoreBackend",
"project": data_docs_project_name,
"bucket": data_docs_bucket_name,
"prefix": data_docs_prefix,
},
"site_index_builder": {
"class_name": "DefaultSiteIndexBuilder",
},
}
}
| GCSStoreBackendDefaults |
python | doocs__leetcode | solution/1100-1199/1196.How Many Apples Can You Put into the Basket/Solution.py | {
"start": 0,
"end": 246
} | class ____:
def maxNumberOfApples(self, weight: List[int]) -> int:
weight.sort()
s = 0
for i, x in enumerate(weight):
s += x
if s > 5000:
return i
return len(weight)
| Solution |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_shear_test.py | {
"start": 258,
"end": 6195
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.RandomShear,
init_kwargs={
"x_factor": (0.5, 1),
"y_factor": (0.5, 1),
"interpolation": "bilinear",
"fill_mode": "reflect",
"data_format": "channels_last",
"seed": 1,
},
input_shape=(8, 3, 4, 3),
supports_masking=False,
expected_output_shape=(8, 3, 4, 3),
)
def test_random_posterization_inference(self):
seed = 3481
layer = layers.RandomShear(1, 1)
np.random.seed(seed)
inputs = np.random.randint(0, 255, size=(224, 224, 3))
output = layer(inputs, training=False)
self.assertAllClose(inputs, output)
def test_shear_pixel_level(self):
image = np.zeros((1, 5, 5, 3))
image[0, 1:4, 1:4, :] = 1.0
image[0, 2, 2, :] = [0.0, 1.0, 0.0]
image = keras.ops.convert_to_tensor(image, dtype="float32")
data_format = backend.config.image_data_format()
if data_format == "channels_first":
image = keras.ops.transpose(image, (0, 3, 1, 2))
shear_layer = layers.RandomShear(
x_factor=(0.2, 0.3),
y_factor=(0.2, 0.3),
interpolation="bilinear",
fill_mode="constant",
fill_value=0.0,
seed=42,
data_format=data_format,
)
sheared_image = shear_layer(image)
if data_format == "channels_first":
sheared_image = keras.ops.transpose(sheared_image, (0, 2, 3, 1))
original_pixel = image[0, 2, 2, :]
sheared_pixel = sheared_image[0, 2, 2, :]
self.assertNotAllClose(original_pixel, sheared_pixel)
def test_tf_data_compatibility(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_data = np.random.random((2, 8, 8, 3))
else:
input_data = np.random.random((2, 3, 8, 8))
layer = layers.RandomShear(1, 1)
ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer)
for output in ds.take(1):
output.numpy()
@parameterized.named_parameters(
(
"with_x_shift",
[[1.0, 0.0]],
[[[0.0, 1.0, 3.2, 3.0], [1.2, 4.0, 4.8, 6.0]]],
),
(
"with_y_shift",
[[0.0, 1.0]],
[[[2.0, 0.0, 4.0, 0.5], [6.0, 0.0, 8.0, 0.0]]],
),
(
"with_xy_shift",
[[1.0, 1.0]],
[[[0.0, 0.0, 3.2, 3.5], [1.2, 0.0, 4.8, 4.5]]],
),
)
def test_random_shear_bounding_boxes(self, translation, expected_boxes):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
image_shape = (10, 8, 3)
else:
image_shape = (3, 10, 8)
input_image = np.random.random(image_shape)
bounding_boxes = {
"boxes": np.array(
[
[2, 1, 4, 3],
[6, 4, 8, 6],
]
),
"labels": np.array([[1, 2]]),
}
input_data = {"images": input_image, "bounding_boxes": bounding_boxes}
layer = layers.RandomShear(
x_factor=0.5,
y_factor=0.5,
data_format=data_format,
seed=42,
bounding_box_format="xyxy",
)
transformation = {
"shear_factor": backend_utils.convert_tf_tensor(
np.array(translation)
),
"input_shape": image_shape,
}
output = layer.transform_bounding_boxes(
input_data["bounding_boxes"],
transformation=transformation,
training=True,
)
self.assertAllClose(output["boxes"], expected_boxes)
@parameterized.named_parameters(
(
"with_x_shift",
[[1.0, 0.0]],
[[[0.0, 1.0, 3.2, 3.0], [1.2, 4.0, 4.8, 6.0]]],
),
(
"with_y_shift",
[[0.0, 1.0]],
[[[2.0, 0.0, 4.0, 0.5], [6.0, 0.0, 8.0, 0.0]]],
),
(
"with_xy_shift",
[[1.0, 1.0]],
[[[0.0, 0.0, 3.2, 3.5], [1.2, 0.0, 4.8, 4.5]]],
),
)
def test_random_shear_tf_data_bounding_boxes(
self, translation, expected_boxes
):
data_format = backend.config.image_data_format()
if backend.config.image_data_format() == "channels_last":
image_shape = (1, 10, 8, 3)
else:
image_shape = (1, 3, 10, 8)
input_image = np.random.random(image_shape)
bounding_boxes = {
"boxes": np.array(
[
[
[2, 1, 4, 3],
[6, 4, 8, 6],
]
]
),
"labels": np.array([[1, 2]]),
}
input_data = {"images": input_image, "bounding_boxes": bounding_boxes}
ds = tf_data.Dataset.from_tensor_slices(input_data)
layer = layers.RandomShear(
x_factor=0.5,
y_factor=0.5,
data_format=data_format,
seed=42,
bounding_box_format="xyxy",
)
transformation = {
"shear_factor": np.array(translation),
"input_shape": image_shape,
}
ds = ds.map(
lambda x: layer.transform_bounding_boxes(
x["bounding_boxes"],
transformation=transformation,
training=True,
)
)
output = next(iter(ds))
expected_boxes = np.array(expected_boxes)
self.assertAllClose(output["boxes"], expected_boxes)
| RandomShearTest |
python | pypa__warehouse | warehouse/sessions.py | {
"start": 730,
"end": 2002
} | class ____(dict):
__contains__ = _invalid_method(dict.__contains__)
__delitem__ = _invalid_method(dict.__delitem__)
__getitem__ = _invalid_method(dict.__getitem__)
__iter__ = _invalid_method(dict.__iter__)
__len__ = _invalid_method(dict.__len__)
__setitem__ = _invalid_method(dict.__setitem__)
clear = _invalid_method(dict.clear)
copy = _invalid_method(dict.copy)
fromkeys = _invalid_method(dict.fromkeys)
get = _invalid_method(dict.get)
items = _invalid_method(dict.items)
keys = _invalid_method(dict.keys)
pop = _invalid_method(dict.pop)
popitem = _invalid_method(dict.popitem)
setdefault = _invalid_method(dict.setdefault)
update = _invalid_method(dict.update)
values = _invalid_method(dict.values)
def _error_message(self):
raise RuntimeError(
"Cannot use request.session in a view without uses_session=True."
)
def __getattr__(self, name):
self._error_message()
@property
def created(self):
self._error_message()
def _changed_method(method):
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
self.changed()
return method(self, *args, **kwargs)
return wrapped
@implementer(ISession)
| InvalidSession |
python | ray-project__ray | python/ray/data/_internal/logical/interfaces/optimizer.py | {
"start": 560,
"end": 1386
} | class ____:
"""Abstract class for optimizers.
An optimizers transforms a DAG of operators with a list of predefined rules.
"""
@property
def rules(self) -> List[Rule]:
"""List of predefined rules for this optimizer."""
raise NotImplementedError
def optimize(self, plan: Plan) -> Plan:
"""Optimize operators with a list of rules."""
# Apply rules until the plan is not changed
previous_plan = plan
while True:
for rule in self.rules:
plan = rule.apply(plan)
# TODO: Eventually we should implement proper equality.
# Using str to check equality seems brittle
if plan.dag.dag_str == previous_plan.dag.dag_str:
break
previous_plan = plan
return plan
| Optimizer |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 27672,
"end": 29666
} | class ____(nn.Module):
def __init__(self, config: FunnelConfig) -> None:
super().__init__()
self.config = config
self.attention_structure = FunnelAttentionStructure(config)
self.layers = nn.ModuleList([FunnelLayer(config, 0) for _ in range(config.num_decoder_layers)])
def forward(
self,
final_hidden: torch.Tensor,
first_block_hidden: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: bool = True,
) -> Union[tuple, BaseModelOutput]:
upsampled_hidden = upsample(
final_hidden,
stride=2 ** (len(self.config.block_sizes) - 1),
target_len=first_block_hidden.shape[1],
separate_cls=self.config.separate_cls,
truncate_seq=self.config.truncate_seq,
)
hidden = upsampled_hidden + first_block_hidden
all_hidden_states = (hidden,) if output_hidden_states else None
all_attentions = () if output_attentions else None
attention_inputs = self.attention_structure.init_attention_inputs(
hidden,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
)
for layer in self.layers:
layer_output = layer(hidden, hidden, hidden, attention_inputs, output_attentions=output_attentions)
hidden = layer_output[0]
if output_attentions:
all_attentions = all_attentions + layer_output[1:]
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden,)
if not return_dict:
return tuple(v for v in [hidden, all_hidden_states, all_attentions] if v is not None)
return BaseModelOutput(last_hidden_state=hidden, hidden_states=all_hidden_states, attentions=all_attentions)
| FunnelDecoder |
python | coleifer__peewee | tests/cysqlite.py | {
"start": 3936,
"end": 4771
} | class ____(CyDatabaseTestCase):
database = database
def setUp(self):
super(TestHashFunctions, self).setUp()
self.database.execute_sql(
'create table users (id integer not null primary key, '
'username text not null)')
def test_md5(self):
for username in ('charlie', 'huey', 'zaizee'):
HUser.insert({HUser.username: username}).execute(self.database)
query = (HUser
.select(HUser.username,
fn.SUBSTR(fn.SHA1(HUser.username), 1, 6).alias('sha'))
.order_by(HUser.username)
.tuples()
.execute(self.database))
self.assertEqual(query[:], [
('charlie', 'd8cd10'),
('huey', '89b31a'),
('zaizee', 'b4dcf9')])
| TestHashFunctions |
python | nedbat__coveragepy | tests/test_arcs.py | {
"start": 50341,
"end": 54061
} | class ____(CoverageTest):
"""Miscellaneous arc-measuring tests."""
def test_dict_literal(self) -> None:
self.check_coverage(
"""\
d = {
'a': 2,
'b': 3,
'c': {
'd': 5,
'e': 6,
}
}
assert d
""",
branchz="",
branchz_missing="",
)
self.check_coverage(
"""\
d = \\
{ 'a': 2,
'b': 3,
'c': {
'd': 5,
'e': 6,
}
}
assert d
""",
branchz="",
branchz_missing="",
)
def test_unpacked_literals(self) -> None:
self.check_coverage(
"""\
d = {
'a': 2,
'b': 3,
}
weird = {
**d,
**{'c': 7},
'd': 8,
}
assert weird['b'] == 3
""",
branchz="",
branchz_missing="",
)
self.check_coverage(
"""\
l = [
2,
3,
]
weird = [
*l,
*[7],
8,
]
assert weird[1] == 3
""",
branchz="",
branchz_missing="",
)
@pytest.mark.parametrize("n", [10, 50, 100, 500, 1000, 2000, 10000])
def test_pathologically_long_code_object(self, n: int) -> None:
# https://github.com/coveragepy/coveragepy/issues/359
# Long code objects sometimes cause problems. Originally, it was
# due to EXTENDED_ARG bytes codes. Then it showed a mistake in
# line-number packing.
code = (
"""\
data = [
"""
+ "".join(
f"""\
[
{i}, {i}, {i}, {i}, {i}, {i}, {i}, {i}, {i}, {i}],
"""
for i in range(n)
)
+ """\
]
print(len(data))
"""
)
self.check_coverage(code, branchz="")
assert self.stdout() == f"{n}\n"
def test_partial_generators(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/475
# Line 2 is executed completely.
# Line 3 is started but not finished, because zip ends before it finishes.
# Line 4 is never started.
self.check_coverage(
"""\
def f(a, b):
c = (i for i in a) # 2
d = (j for j in b) # 3
e = (k for k in b) # 4
return dict(zip(c, d))
f(['a', 'b'], [1, 2, 3])
""",
branchz="",
branchz_missing="",
)
def test_failing_open(self) -> None:
with mock.patch.object(coverage.python, "open", side_effect=IOError("Nope")):
self.make_file(
"some_branches.py",
"""\
def forelse(seq):
for n in seq:
if n > 5:
break
else:
print('None of the values were greater than 5')
print('Done')
forelse([1,2])
""",
)
cov = coverage.Coverage(branch=True)
self.start_import_stop(cov, "some_branches")
# No assert: the test passes if it didn't raise an exception.
| MiscArcTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 60532,
"end": 60677
} | class ____(AnsiFunction[datetime.datetime]):
"""The SYSDATE() SQL function."""
type = sqltypes.DateTime()
inherit_cache = True
| sysdate |
python | pytorch__pytorch | torch/autograd/function.py | {
"start": 19393,
"end": 26896
} | class ____(_SingleLevelFunction):
r"""Base class to create custom `autograd.Function`.
To create a custom `autograd.Function`, subclass this class and implement
the :meth:`forward` and :meth:`backward` static methods. Then, to use your custom
op in the forward pass, call the class method ``apply``. Do not call
:meth:`forward` directly.
To ensure correctness and best performance, make sure you are calling the
correct methods on ``ctx`` and validating your backward function using
:func:`torch.autograd.gradcheck`.
See :ref:`extending-autograd` for more details on how to use this class.
Examples::
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
>>> class Exp(Function):
>>> @staticmethod
>>> def forward(ctx, i):
>>> result = i.exp()
>>> ctx.save_for_backward(result)
>>> return result
>>>
>>> @staticmethod
>>> def backward(ctx, grad_output):
>>> result, = ctx.saved_tensors
>>> return grad_output * result
>>>
>>> # Use it by calling the apply method:
>>> # xdoctest: +SKIP
>>> output = Exp.apply(input)
"""
def __init__(self, *args, **kwargs):
warnings.warn(
f"{self.__class__} should not be instantiated. Methods on autograd functions "
"are all static, so you should invoke them on the class itself. "
"Instantiating an autograd function will raise an "
"error in a future version of PyTorch.",
DeprecationWarning,
stacklevel=2,
)
def __call__(self, *args, **kwargs):
raise RuntimeError(
"Legacy autograd function with non-static forward method is deprecated. "
"Please use new-style autograd function with static forward method. "
"(Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)"
)
"""
Bool that specifies if PyTorch should attempt to autogenerate
:func:`torch.vmap` support for this autograd.Function. You may set this to
True only if this autograd.Function's forward, backward, and jvp (if they
exist) are written using PyTorch operations; otherwise, please override
:meth:`torch.autograd.Function.vmap` to add support for :func:`torch.vmap`.
Please see :ref:`func-autograd-function` for more details.
"""
generate_vmap_rule = False
@staticmethod
def vmap(info, in_dims, *args):
r"""Define the behavior for this autograd.Function underneath :func:`torch.vmap`.
For a :func:`torch.autograd.Function` to support
:func:`torch.vmap`, you must either override this static method, or set
``generate_vmap_rule`` to ``True`` (you may not do both).
If you choose to override this staticmethod: it must accept
- an ``info`` object as the first argument. ``info.batch_size``
specifies the size of the dimension being vmapped over,
while ``info.randomness`` is the randomness option passed to
:func:`torch.vmap`.
- an ``in_dims`` tuple as the second argument.
For each arg in ``args``, ``in_dims`` has a corresponding
``Optional[int]``. It is ``None`` if the arg is not a Tensor or if
the arg is not being vmapped over, otherwise, it is an integer
specifying what dimension of the Tensor is being vmapped over.
- ``*args``, which is the same as the args to :meth:`~Function.forward`.
The return of the vmap staticmethod is a tuple of ``(output, out_dims)``.
Similar to ``in_dims``, ``out_dims`` should be of the same structure as
``output`` and contain one ``out_dim`` per output that specifies if the
output has the vmapped dimension and what index it is in.
Please see :ref:`func-autograd-function` for more details.
"""
raise NotImplementedError(
"To use autograd.Function with vmap, you must either override the "
"vmap staticmethod or set generate_vmap_rule=True."
)
@classmethod
def apply(cls, *args, **kwargs):
def bind_default_args(func, *args, **kwargs):
signature = inspect.signature(func)
bound_args = signature.bind(*args, **kwargs)
bound_args.apply_defaults()
return bound_args.args
is_setup_ctx_defined = _is_setup_context_defined(cls.setup_context)
if is_setup_ctx_defined:
args = bind_default_args(cls.forward, *args, **kwargs)
if not torch._C._are_functorch_transforms_active():
# See NOTE: [functorch vjp and autograd interaction]
args = _functorch.utils.unwrap_dead_wrappers(args)
return super().apply(*args, **kwargs) # type: ignore[misc]
if not is_setup_ctx_defined:
raise RuntimeError(
"In order to use an autograd.Function with functorch transforms "
"(vmap, grad, jvp, jacrev, ...), it must override the setup_context "
"staticmethod. For more details, please see "
"https://pytorch.org/docs/main/notes/extending.func.html"
)
return custom_function_call(cls, *args, **kwargs)
@staticmethod
def _compiled_autograd_key(ctx):
return (ctx._autograd_function_id,)
def _is_setup_context_defined(fn):
return fn != _SingleLevelFunction.setup_context
def once_differentiable(
fn: Callable[Concatenate[_T, _P], _R],
) -> Callable[Concatenate[_T, _P], _R]:
@functools.wraps(fn)
def wrapper(ctx: _T, *args: _P.args, **kwargs: _P.kwargs) -> _R:
with torch.no_grad():
outputs = fn(ctx, *args, **kwargs)
if not torch.is_grad_enabled():
return outputs
# If any of the inputs have requires_grad=True, we force the outputs
# to have requires_grad=True but point to a grad_fn which throws an
# error message during (double) back-propagation.
# XXX: this is only an approximation of requires_grad - there's no way
# to figure out if fn didn't use ctx.saved_tensors and as a result
# some Tensors might require grad, even if no args do.
# Unfortunately, this leads to unexpected error messages ("no nodes
# require computing gradients"), but I don't have a better idea.
# These functions would raise an error in backward anyway.
requires_grad = any(
isinstance(arg, torch.Tensor) and arg.requires_grad for arg in args
)
if not requires_grad:
return outputs
if not isinstance(outputs, tuple):
outputs_ = (outputs,)
else:
outputs_ = outputs
err_fn = _functions.DelayedError(
b"trying to differentiate twice a function that was marked "
b"with @once_differentiable",
len(outputs_),
)
# Create aliases of each output that has requires_grad=True. We need
# at least one of the inputs to err_fn to require grad so that the
# output will have a grad_fn.
def fake_requires_grad(var):
if var is not None:
var = var.detach()
var.requires_grad = True
return var
return err_fn(*[fake_requires_grad(v) for v in outputs_]) # type: ignore[return-value]
return wrapper
| Function |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_details.py | {
"start": 8776,
"end": 12923
} | class ____(UserDetailsTest):
method = "put"
def test_superuser_can_change_is_active(self) -> None:
self.user.update(is_active=True)
self.login_as(user=self.superuser, superuser=True)
resp = self.get_success_response(
self.user.id,
isActive="false",
)
assert resp.data["id"] == str(self.user.id)
user = User.objects.get(id=self.user.id)
assert not user.is_active
def test_superuser_with_permission_can_change_is_active(self) -> None:
self.user.update(is_active=True)
UserPermission.objects.create(user=self.superuser, permission="users.admin")
self.login_as(user=self.superuser, superuser=True)
resp = self.get_success_response(
self.user.id,
isActive="false",
)
assert resp.data["id"] == str(self.user.id)
user = User.objects.get(id=self.user.id)
assert not user.is_active
@override_settings(SENTRY_SELF_HOSTED=False)
@override_options({"superuser.read-write.ga-rollout": True})
def test_superuser_read_cannot_change_is_active(self) -> None:
self.user.update(is_active=True)
superuser = self.create_user(email="b@example.com", is_superuser=True)
self.login_as(user=superuser, superuser=True)
self.get_error_response(
self.user.id,
isActive="false",
status_code=403,
)
self.user.refresh_from_db()
assert self.user.is_active
@override_settings(SENTRY_SELF_HOSTED=False)
@override_options({"superuser.read-write.ga-rollout": True})
def test_superuser_write_can_change_is_active(self) -> None:
self.user.update(is_active=True)
superuser = self.create_user(email="b@example.com", is_superuser=True)
self.add_user_permission(superuser, "superuser.write")
self.login_as(user=superuser, superuser=True)
resp = self.get_success_response(
self.user.id,
isActive="false",
)
assert resp.data["id"] == str(self.user.id)
self.user.refresh_from_db()
assert not self.user.is_active
def test_superuser_cannot_add_superuser(self) -> None:
self.user.update(is_superuser=False)
self.login_as(user=self.superuser, superuser=True)
resp = self.get_error_response(
self.user.id,
isSuperuser="true",
status_code=403,
)
assert resp.data["detail"] == "Missing required permission to add superuser."
user = User.objects.get(id=self.user.id)
assert not user.is_superuser
def test_superuser_cannot_add_staff(self) -> None:
self.user.update(is_staff=False)
self.login_as(user=self.superuser, superuser=True)
resp = self.get_error_response(
self.user.id,
isStaff="true",
status_code=403,
)
assert resp.data["detail"] == "Missing required permission to add admin."
user = User.objects.get(id=self.user.id)
assert not user.is_staff
def test_superuser_with_permission_can_add_superuser(self) -> None:
self.user.update(is_superuser=False)
UserPermission.objects.create(user=self.superuser, permission="users.admin")
self.login_as(user=self.superuser, superuser=True)
resp = self.get_success_response(
self.user.id,
isSuperuser="true",
)
assert resp.data["id"] == str(self.user.id)
user = User.objects.get(id=self.user.id)
assert user.is_superuser
def test_superuser_with_permission_can_add_staff(self) -> None:
self.user.update(is_staff=False)
UserPermission.objects.create(user=self.superuser, permission="users.admin")
self.login_as(user=self.superuser, superuser=True)
resp = self.get_success_response(
self.user.id,
isStaff="true",
)
assert resp.data["id"] == str(self.user.id)
user = User.objects.get(id=self.user.id)
assert user.is_staff
@control_silo_test
| UserDetailsSuperuserUpdateTest |
python | walkccc__LeetCode | solutions/401. Binary Watch/401.py | {
"start": 0,
"end": 614
} | class ____:
def readBinaryWatch(self, turnedOn: int) -> list[str]:
ans = []
hours = [1, 2, 4, 8]
minutes = [1, 2, 4, 8, 16, 32]
def dfs(turnedOn: int, s: int, h: int, m: int) -> None:
if turnedOn == 0:
time = str(h) + ":" + (str(m).zfill(2))
ans.append(time)
return
for i in range(s, len(hours) + len(minutes)):
if i < 4 and h + hours[i] < 12:
dfs(turnedOn - 1, i + 1, h + hours[i], m)
elif i >= 4 and m + minutes[i - 4] < 60:
dfs(turnedOn - 1, i + 1, h, m + minutes[i - 4])
dfs(turnedOn, 0, 0, 0)
return ans
| Solution |
python | pytorch__pytorch | tools/setup_helpers/env.py | {
"start": 1165,
"end": 3504
} | class ____:
"""Checks build type. The build type will be given in :attr:`cmake_build_type_env`. If :attr:`cmake_build_type_env`
is ``None``, then the build type will be inferred from ``CMakeCache.txt``. If ``CMakeCache.txt`` does not exist,
os.environ['CMAKE_BUILD_TYPE'] will be used.
Args:
cmake_build_type_env (str): The value of os.environ['CMAKE_BUILD_TYPE']. If None, the actual build type will be
inferred.
"""
def __init__(self, cmake_build_type_env: str | None = None) -> None:
if cmake_build_type_env is not None:
self.build_type_string = cmake_build_type_env
return
cmake_cache_txt = os.path.join(BUILD_DIR, "CMakeCache.txt")
if os.path.isfile(cmake_cache_txt):
# Found CMakeCache.txt. Use the build type specified in it.
from .cmake_utils import get_cmake_cache_variables_from_file
with open(cmake_cache_txt) as f:
cmake_cache_vars = get_cmake_cache_variables_from_file(f)
# Normally it is anti-pattern to determine build type from CMAKE_BUILD_TYPE because it is not used for
# multi-configuration build tools, such as Visual Studio and XCode. But since we always communicate with
# CMake using CMAKE_BUILD_TYPE from our Python scripts, this is OK here.
self.build_type_string = cast(str, cmake_cache_vars["CMAKE_BUILD_TYPE"])
else:
self.build_type_string = os.environ.get("CMAKE_BUILD_TYPE", "Release")
def is_debug(self) -> bool:
"Checks Debug build."
return self.build_type_string == "Debug"
def is_rel_with_deb_info(self) -> bool:
"Checks RelWithDebInfo build."
return self.build_type_string == "RelWithDebInfo"
def is_release(self) -> bool:
"Checks Release build."
return self.build_type_string == "Release"
# hotpatch environment variable 'CMAKE_BUILD_TYPE'. 'CMAKE_BUILD_TYPE' always prevails over DEBUG or REL_WITH_DEB_INFO.
if "CMAKE_BUILD_TYPE" not in os.environ:
if check_env_flag("DEBUG"):
os.environ["CMAKE_BUILD_TYPE"] = "Debug"
elif check_env_flag("REL_WITH_DEB_INFO"):
os.environ["CMAKE_BUILD_TYPE"] = "RelWithDebInfo"
else:
os.environ["CMAKE_BUILD_TYPE"] = "Release"
build_type = BuildType()
| BuildType |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 40231,
"end": 40745
} | class ____:
"""Test hi_IN address provider methods"""
def test_city_name(self, faker, num_samples):
for _ in range(num_samples):
city_name = faker.city_name()
assert isinstance(city_name, str)
assert city_name in HiInAddressProvider.cities
def test_state(self, faker, num_samples):
for _ in range(num_samples):
state = faker.state()
assert isinstance(state, str)
assert state in HiInAddressProvider.states
| TestHiIn |
python | encode__django-rest-framework | tests/test_serializer_nested.py | {
"start": 1571,
"end": 2498
} | class ____:
def setup_method(self):
class NestedSerializer(serializers.Serializer):
one = serializers.IntegerField(max_value=10)
class TestSerializer(serializers.Serializer):
nested = NestedSerializer(required=False)
self.Serializer = TestSerializer
def test_json_validate(self):
input_data = {}
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
input_data = {'nested': {'one': '1'}}
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
def test_multipart_validate(self):
input_data = QueryDict('')
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
input_data = QueryDict('nested[one]=1')
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
| TestNotRequiredNestedSerializer |
python | spyder-ide__spyder | spyder/api/widgets/dialogs.py | {
"start": 414,
"end": 1182
} | class ____(QProxyStyle):
"""Style adjustments for SpyderDialogButtonBox."""
def styleHint(self, hint, option=None, widget=None, return_data=None):
if hint == QStyle.SH_DialogButtonLayout:
# Use the Windows buttons layout to have a uniform layout in all
# platforms. We selected that layout because Windows is our most
# popular platform.
# Solution found in https://stackoverflow.com/a/35907926/438386
if QT6: # PySide6/PyQt6
return QDialogButtonBox.ButtonLayout.WinLayout.value
else: # PySide2/PyQt5
return int(QDialogButtonBox.ButtonLayout.WinLayout)
return super().styleHint(hint, option, widget, return_data)
| _SpyderButtonsProxyStyle |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/data_adapter.py | {
"start": 22992,
"end": 24904
} | class ____(DataAdapter):
"""Adapter that handles lists of scalars and lists of lists of scalars."""
@staticmethod
def can_handle(x, y=None):
handles_x = ListsOfScalarsDataAdapter._is_list_of_scalars(x)
handles_y = True
if y is not None:
handles_y = ListsOfScalarsDataAdapter._is_list_of_scalars(y)
return handles_x and handles_y
@staticmethod
def _is_list_of_scalars(inp):
if isinstance(inp, (float, int, str, bytes, bytearray)):
return True
if isinstance(inp, (list, tuple)) and inp:
return ListsOfScalarsDataAdapter._is_list_of_scalars(inp[0])
return False
def __init__(self,
x,
y=None,
sample_weights=None,
sample_weight_modes=None,
batch_size=None,
shuffle=False,
**kwargs):
super(ListsOfScalarsDataAdapter, self).__init__(x, y, **kwargs)
x = numpy_compat.np_asarray(x)
if y is not None:
y = numpy_compat.np_asarray(y)
if sample_weights is not None:
sample_weights = numpy_compat.np_asarray(sample_weights)
sample_weight_modes = broadcast_sample_weight_modes(
sample_weights, sample_weight_modes)
self._internal_adapter = TensorLikeDataAdapter(
x,
y=y,
sample_weights=sample_weights,
sample_weight_modes=sample_weight_modes,
batch_size=batch_size,
shuffle=shuffle,
**kwargs)
def get_dataset(self):
return self._internal_adapter.get_dataset()
def get_size(self):
return self._internal_adapter.get_size()
def batch_size(self):
return self._internal_adapter.batch_size()
def has_partial_batch(self):
return self._internal_adapter.has_partial_batch()
def partial_batch_size(self):
return self._internal_adapter.partial_batch_size()
def should_recreate_iterator(self):
return True
| ListsOfScalarsDataAdapter |
python | realpython__materials | python-constants/strict_constants.py | {
"start": 513,
"end": 615
} | class ____:
PI = 3.141592653589793
EULER_NUMBER = 2.718281828459045
| ConstantsNamespace_dataclass |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 30481,
"end": 30649
} | class ____(RaySystemError):
"""Raised when the Compiled Graph channel's buffer is at max capacity"""
pass
@PublicAPI(stability="alpha")
| RayCgraphCapacityExceeded |
python | spack__spack | lib/spack/spack/util/file_cache.py | {
"start": 1037,
"end": 1736
} | class ____:
def __init__(self, path: str) -> None:
self.path = path
self.tmp_path = f"{self.path}.tmp"
def __enter__(self) -> Tuple[Optional[IO[str]], IO[str]]:
"""Return (old_file, new_file) file objects, where old_file is optional."""
self.old_file = _maybe_open(self.path)
self.new_file = open(self.tmp_path, "w", encoding="utf-8")
return self.old_file, self.new_file
def __exit__(self, type, value, traceback):
if self.old_file:
self.old_file.close()
self.new_file.close()
if value:
os.remove(self.tmp_path)
else:
rename(self.tmp_path, self.path)
| WriteContextManager |
python | apache__airflow | providers/imap/tests/unit/imap/hooks/test_imap.py | {
"start": 2232,
"end": 16462
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="imap_default",
conn_type="imap",
host="imap_server_address",
login="imap_user",
password="imap_password",
port=1993,
)
)
create_connection_without_db(
Connection(
conn_id="imap_nonssl",
conn_type="imap",
host="imap_server_address",
login="imap_user",
password="imap_password",
port=1143,
extra=json.dumps(dict(use_ssl=False)),
)
)
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect(self, create_default_context, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib)
with ImapHook():
pass
assert create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with(
"imap_server_address", 1993, ssl_context=create_default_context.return_value
)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect_imap_ssl_context_none(self, create_default_context, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib)
with conf_vars({("imap", "ssl_context"): "none"}):
with ImapHook():
pass
assert not create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with("imap_server_address", 1993, ssl_context=None)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect_imap_ssl_context_from_extra(
self, create_default_context, mock_imaplib, create_connection_without_db
):
mock_conn = _create_fake_imap(mock_imaplib)
create_connection_without_db(
Connection(
conn_id="imap_ssl_context_from_extra",
conn_type="imap",
host="imap_server_address",
login="imap_user",
password="imap_password",
port=1993,
extra=json.dumps(dict(use_ssl=True, ssl_context="default")),
)
)
with conf_vars({("imap", "ssl_context"): "none"}):
with ImapHook(imap_conn_id="imap_ssl_context_from_extra"):
pass
assert create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with(
"imap_server_address", 1993, ssl_context=create_default_context.return_value
)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect_imap_ssl_context_default(self, create_default_context, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib)
with conf_vars({("imap", "ssl_context"): "default"}):
with ImapHook():
pass
assert create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with(
"imap_server_address", 1993, ssl_context=create_default_context.return_value
)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect_email_ssl_context_none(self, create_default_context, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib)
with conf_vars({("email", "ssl_context"): "none"}):
with ImapHook():
pass
assert not create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with("imap_server_address", 1993, ssl_context=None)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
@patch("ssl.create_default_context")
def test_connect_and_disconnect_imap_ssl_context_override(self, create_default_context, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib)
with conf_vars({("email", "ssl_context"): "none", ("imap", "ssl_context"): "default"}):
with ImapHook():
pass
assert create_default_context.called
mock_imaplib.IMAP4_SSL.assert_called_once_with(
"imap_server_address", 1993, ssl_context=create_default_context.return_value
)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
def test_connect_and_disconnect_via_nonssl(self, mock_imaplib):
mock_conn = _create_fake_imap(mock_imaplib, use_ssl=False)
with ImapHook(imap_conn_id="imap_nonssl"):
pass
mock_imaplib.IMAP4.assert_called_once_with("imap_server_address", 1143)
mock_conn.login.assert_called_once_with("imap_user", "imap_password")
assert mock_conn.logout.call_count == 1
@patch(imaplib_string)
def test_has_mail_attachment_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
has_attachment_in_inbox = imap_hook.has_mail_attachment("test1.csv")
assert has_attachment_in_inbox
@patch(imaplib_string)
def test_has_mail_attachment_not_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
has_attachment_in_inbox = imap_hook.has_mail_attachment("test1.txt")
assert not has_attachment_in_inbox
@patch(imaplib_string)
def test_has_mail_attachment_with_regex_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
has_attachment_in_inbox = imap_hook.has_mail_attachment(name=r"test(\d+).csv", check_regex=True)
assert has_attachment_in_inbox
@patch(imaplib_string)
def test_has_mail_attachment_with_regex_not_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
has_attachment_in_inbox = imap_hook.has_mail_attachment(name=r"test_(\d+).csv", check_regex=True)
assert not has_attachment_in_inbox
@patch(imaplib_string)
def test_has_mail_attachment_with_mail_filter(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
mail_filter = '(SINCE "01-Jan-2019")'
with ImapHook() as imap_hook:
imap_hook.has_mail_attachment(name="test1.csv", mail_filter=mail_filter)
mock_imaplib.IMAP4_SSL.return_value.search.assert_called_once_with(None, mail_filter)
@patch(imaplib_string)
def test_retrieve_mail_attachments_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
attachments_in_inbox = imap_hook.retrieve_mail_attachments("test1.csv")
assert attachments_in_inbox == [("test1.csv", b"SWQsTmFtZQoxLEZlbGl4")]
@patch(imaplib_string)
def test_retrieve_mail_attachments_not_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
with pytest.raises(AirflowException):
imap_hook.retrieve_mail_attachments("test1.txt")
@patch(imaplib_string)
def test_retrieve_mail_attachments_with_regex_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
attachments_in_inbox = imap_hook.retrieve_mail_attachments(
name=r"test(\d+).csv", check_regex=True
)
assert attachments_in_inbox == [("test1.csv", b"SWQsTmFtZQoxLEZlbGl4")]
@patch(imaplib_string)
def test_retrieve_mail_attachments_with_regex_not_found(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
with pytest.raises(AirflowException):
imap_hook.retrieve_mail_attachments(
name=r"test_(\d+).csv",
check_regex=True,
)
@patch(imaplib_string)
def test_retrieve_mail_attachments_latest_only(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
attachments_in_inbox = imap_hook.retrieve_mail_attachments(name="test1.csv", latest_only=True)
assert attachments_in_inbox == [("test1.csv", b"SWQsTmFtZQoxLEZlbGl4")]
@patch(imaplib_string)
def test_retrieve_mail_attachments_with_mail_filter(self, mock_imaplib):
_create_fake_imap(mock_imaplib, with_mail=True)
mail_filter = '(SINCE "01-Jan-2019")'
with ImapHook() as imap_hook:
imap_hook.retrieve_mail_attachments(name="test1.csv", mail_filter=mail_filter)
mock_imaplib.IMAP4_SSL.return_value.search.assert_called_once_with(None, mail_filter)
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_found(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments("test1.csv", "test_directory")
mock_open_method.assert_called_once_with("test_directory/test1.csv", "wb")
mock_open_method.return_value.write.assert_called_once_with(b"SWQsTmFtZQoxLEZlbGl4")
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_not_found(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
with pytest.raises(AirflowException):
imap_hook.download_mail_attachments("test1.txt", "test_directory")
mock_open_method.assert_not_called()
mock_open_method.return_value.write.assert_not_called()
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_regex_found(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments(
name=r"test(\d+).csv", local_output_directory="test_directory", check_regex=True
)
mock_open_method.assert_called_once_with("test_directory/test1.csv", "wb")
mock_open_method.return_value.write.assert_called_once_with(b"SWQsTmFtZQoxLEZlbGl4")
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_regex_not_found(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
with pytest.raises(AirflowException):
imap_hook.download_mail_attachments(
name=r"test_(\d+).csv",
local_output_directory="test_directory",
check_regex=True,
)
mock_open_method.assert_not_called()
mock_open_method.return_value.write.assert_not_called()
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_latest_only(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments(
name="test1.csv", local_output_directory="test_directory", latest_only=True
)
mock_open_method.assert_called_once_with("test_directory/test1.csv", "wb")
mock_open_method.return_value.write.assert_called_once_with(b"SWQsTmFtZQoxLEZlbGl4")
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_escaping_chars(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True, attachment_name="../test1.csv")
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments(name="../test1.csv", local_output_directory="test_directory")
mock_open_method.assert_not_called()
mock_open_method.return_value.write.assert_not_called()
@patch("airflow.providers.imap.hooks.imap.os.path.islink", return_value=True)
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_symlink(self, mock_imaplib, mock_open_method, mock_is_symlink):
_create_fake_imap(mock_imaplib, with_mail=True, attachment_name="symlink")
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments(name="symlink", local_output_directory="test_directory")
assert mock_is_symlink.call_count == 1
mock_open_method.assert_not_called()
mock_open_method.return_value.write.assert_not_called()
@patch(open_string, new_callable=mock_open)
@patch(imaplib_string)
def test_download_mail_attachments_with_mail_filter(self, mock_imaplib, mock_open_method):
_create_fake_imap(mock_imaplib, with_mail=True)
mail_filter = '(SINCE "01-Jan-2019")'
with ImapHook() as imap_hook:
imap_hook.download_mail_attachments(
name="test1.csv", local_output_directory="test_directory", mail_filter=mail_filter
)
mock_imaplib.IMAP4_SSL.return_value.search.assert_called_once_with(None, mail_filter)
assert mock_open_method.call_count == 1
| TestImapHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1374026,
"end": 1377332
} | class ____(
sgqlc.types.Type, Node, Comment, Deletable, Minimizable, Updatable, UpdatableComment, Reactable, RepositoryNode
):
"""A review comment associated with a given repository pull request."""
__schema__ = github_schema
__field_names__ = (
"commit",
"diff_hunk",
"drafted_at",
"line",
"original_commit",
"original_line",
"original_start_line",
"outdated",
"path",
"pull_request",
"pull_request_review",
"reply_to",
"resource_path",
"start_line",
"state",
"subject_type",
"url",
)
commit = sgqlc.types.Field(Commit, graphql_name="commit")
"""Identifies the commit associated with the comment."""
diff_hunk = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="diffHunk")
"""The diff hunk to which the comment applies."""
drafted_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="draftedAt")
"""Identifies when the comment was created in a draft state."""
line = sgqlc.types.Field(Int, graphql_name="line")
"""The end line number on the file to which the comment applies"""
original_commit = sgqlc.types.Field(Commit, graphql_name="originalCommit")
"""Identifies the original commit associated with the comment."""
original_line = sgqlc.types.Field(Int, graphql_name="originalLine")
"""The end line number on the file to which the comment applied when
it was first created
"""
original_start_line = sgqlc.types.Field(Int, graphql_name="originalStartLine")
"""The start line number on the file to which the comment applied
when it was first created
"""
outdated = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="outdated")
"""Identifies when the comment body is outdated"""
path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path")
"""The path to which the comment applies."""
pull_request = sgqlc.types.Field(sgqlc.types.non_null(PullRequest), graphql_name="pullRequest")
"""The pull request associated with this review comment."""
pull_request_review = sgqlc.types.Field(PullRequestReview, graphql_name="pullRequestReview")
"""The pull request review associated with this review comment."""
reply_to = sgqlc.types.Field("PullRequestReviewComment", graphql_name="replyTo")
"""The comment this is a reply to."""
resource_path = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="resourcePath")
"""The HTTP path permalink for this review comment."""
start_line = sgqlc.types.Field(Int, graphql_name="startLine")
"""The start line number on the file to which the comment applies"""
state = sgqlc.types.Field(sgqlc.types.non_null(PullRequestReviewCommentState), graphql_name="state")
"""Identifies the state of the comment."""
subject_type = sgqlc.types.Field(sgqlc.types.non_null(PullRequestReviewThreadSubjectType), graphql_name="subjectType")
"""The level at which the comments in the corresponding thread are
targeted, can be a diff line or a file
"""
url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="url")
"""The HTTP URL permalink for this review comment."""
| PullRequestReviewComment |
python | getsentry__sentry | tests/sentry/uptime/migrations/test_0045_backfill_detector_thresholds.py | {
"start": 87,
"end": 5870
} | class ____(TestMigrations):
migrate_from = "0044_remove_project_uptime_subscription"
migrate_to = "0045_backfill_detector_thresholds"
app = "uptime"
def setup_initial_state(self) -> None:
# Create test organization and project
self.organization = self.create_organization(name="test-org")
self.project = self.create_project(organization=self.organization)
# Create uptime detectors with various config states
# Detector 1: Minimal valid config without thresholds (should get both thresholds)
self.detector_no_config = self.create_detector(
project=self.project,
name="uptime-detector-no-config",
type="uptime_domain_failure",
config={"mode": 1, "environment": "production"},
)
# Detector 2: Basic config without thresholds (should get both thresholds)
self.detector_empty_config = self.create_detector(
project=self.project,
name="uptime-detector-empty-config",
type="uptime_domain_failure",
config={"mode": 1, "environment": None},
)
# Detector 3: Has some config but no thresholds (should get both thresholds)
self.detector_partial_config = self.create_detector(
project=self.project,
name="uptime-detector-partial-config",
type="uptime_domain_failure",
config={"mode": 1, "environment": "production"},
)
# Detector 4: Has only recovery_threshold (should get downtime_threshold)
self.detector_has_recovery = self.create_detector(
project=self.project,
name="uptime-detector-has-recovery",
type="uptime_domain_failure",
config={"mode": 1, "environment": None, "recovery_threshold": 2},
)
# Detector 5: Has only downtime_threshold (should get recovery_threshold)
self.detector_has_downtime = self.create_detector(
project=self.project,
name="uptime-detector-has-downtime",
type="uptime_domain_failure",
config={"mode": 1, "environment": None, "downtime_threshold": 5},
)
# Detector 6: Has both thresholds already (should not change)
self.detector_has_both = self.create_detector(
project=self.project,
name="uptime-detector-has-both",
type="uptime_domain_failure",
config={
"mode": 1,
"environment": None,
"recovery_threshold": 3,
"downtime_threshold": 7,
},
)
# Detector 7: Non-uptime detector (should not change)
self.detector_non_uptime = self.create_detector(
project=self.project,
name="regular-detector",
type="monitor_check_in_failure",
config={},
)
def test_migration(self) -> None:
# Test detector with basic config gets both thresholds
self.detector_no_config.refresh_from_db()
assert self.detector_no_config.config is not None
assert self.detector_no_config.config["recovery_threshold"] == 1
assert self.detector_no_config.config["downtime_threshold"] == 3
assert self.detector_no_config.config["mode"] == 1 # Preserved
assert self.detector_no_config.config["environment"] == "production" # Preserved
# Test detector with basic config gets both thresholds
self.detector_empty_config.refresh_from_db()
assert self.detector_empty_config.config["recovery_threshold"] == 1
assert self.detector_empty_config.config["downtime_threshold"] == 3
assert self.detector_empty_config.config["mode"] == 1 # Preserved
assert self.detector_empty_config.config["environment"] is None # Preserved
# Test detector with partial config gets both thresholds and preserves existing
self.detector_partial_config.refresh_from_db()
assert self.detector_partial_config.config["recovery_threshold"] == 1
assert self.detector_partial_config.config["downtime_threshold"] == 3
assert self.detector_partial_config.config["mode"] == 1
assert self.detector_partial_config.config["environment"] == "production"
# Test detector with only recovery_threshold gets downtime_threshold
self.detector_has_recovery.refresh_from_db()
assert self.detector_has_recovery.config["recovery_threshold"] == 2 # Preserved
assert self.detector_has_recovery.config["downtime_threshold"] == 3 # Added
assert self.detector_has_recovery.config["mode"] == 1 # Preserved
# Test detector with only downtime_threshold gets recovery_threshold
self.detector_has_downtime.refresh_from_db()
assert self.detector_has_downtime.config["recovery_threshold"] == 1 # Added
assert self.detector_has_downtime.config["downtime_threshold"] == 5 # Preserved
assert self.detector_has_downtime.config["mode"] == 1 # Preserved
# Test detector with both thresholds is unchanged
self.detector_has_both.refresh_from_db()
assert self.detector_has_both.config["recovery_threshold"] == 3 # Unchanged
assert self.detector_has_both.config["downtime_threshold"] == 7 # Unchanged
assert self.detector_has_both.config["mode"] == 1 # Unchanged
# Test non-uptime detector is not affected
self.detector_non_uptime.refresh_from_db()
assert "recovery_threshold" not in self.detector_non_uptime.config
assert "downtime_threshold" not in self.detector_non_uptime.config
# Config should remain empty for cron detector
assert self.detector_non_uptime.config == {}
| BackfillDetectorThresholdsTest |
python | redis__redis-py | tests/test_connect.py | {
"start": 4820,
"end": 6829
} | class ____(socketserver.TCPServer):
def __init__(
self,
*args,
certfile=None,
keyfile=None,
minimum_ssl_version=ssl.TLSVersion.TLSv1_2,
maximum_ssl_version=ssl.TLSVersion.TLSv1_3,
**kw,
) -> None:
self._ready_event = threading.Event()
self._stop_requested = False
self._certfile = certfile
self._keyfile = keyfile
self._minimum_ssl_version = minimum_ssl_version
self._maximum_ssl_version = maximum_ssl_version
super().__init__(*args, **kw)
def service_actions(self):
self._ready_event.set()
def wait_online(self):
self._ready_event.wait()
def stop(self):
self._stop_requested = True
self.shutdown()
def is_serving(self):
return not self._stop_requested
def get_request(self):
if self._certfile is None:
return super().get_request()
newsocket, fromaddr = self.socket.accept()
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=self._certfile, keyfile=self._keyfile)
context.minimum_version = self._minimum_ssl_version
context.maximum_version = self._maximum_ssl_version
connstream = context.wrap_socket(newsocket, server_side=True)
return connstream, fromaddr
if hasattr(socketserver, "UnixStreamServer"):
class _RedisUDSServer(socketserver.UnixStreamServer):
def __init__(self, *args, **kw) -> None:
self._ready_event = threading.Event()
self._stop_requested = False
super().__init__(*args, **kw)
def service_actions(self):
self._ready_event.set()
def wait_online(self):
self._ready_event.wait()
def stop(self):
self._stop_requested = True
self.shutdown()
def is_serving(self):
return not self._stop_requested
else:
_RedisUDSServer = None
| _RedisTCPServer |
python | django__django | django/test/runner.py | {
"start": 5001,
"end": 12516
} | class ____(unittest.TestResult):
"""
Extend unittest.TestResult to record events in the child processes so they
can be replayed in the parent process. Events include things like which
tests succeeded or failed.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Fake storage of results to reduce memory usage. These are used by the
# unittest default methods, but here 'events' is used instead.
dummy_list = DummyList()
self.failures = dummy_list
self.errors = dummy_list
self.skipped = dummy_list
self.expectedFailures = dummy_list
self.unexpectedSuccesses = dummy_list
if tblib is not None:
tblib.pickling_support.install()
self.events = []
def __getstate__(self):
# Make this class picklable by removing the file-like buffer
# attributes. This is possible since they aren't used after unpickling
# after being sent to ParallelTestSuite.
state = self.__dict__.copy()
state.pop("_stdout_buffer", None)
state.pop("_stderr_buffer", None)
state.pop("_original_stdout", None)
state.pop("_original_stderr", None)
return state
@property
def test_index(self):
return self.testsRun - 1
def _confirm_picklable(self, obj):
"""
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
"""
pickle.loads(pickle.dumps(obj))
def _print_unpicklable_subtest(self, test, subtest, pickle_exc):
print(
"""
Subtest failed:
test: {}
subtest: {}
Unfortunately, the subtest that failed cannot be pickled, so the parallel
test runner cannot handle it cleanly. Here is the pickling error:
> {}
You should re-run this test with --parallel=1 to reproduce the failure
with a cleaner failure message.
""".format(
test, subtest, pickle_exc
)
)
def check_picklable(self, test, err):
# Ensure that sys.exc_info() tuples are picklable. This displays a
# clear multiprocessing.pool.RemoteTraceback generated in the child
# process instead of a multiprocessing.pool.MaybeEncodingError, making
# the root cause easier to figure out for users who aren't familiar
# with the multiprocessing module. Since we're in a forked process,
# our best chance to communicate with them is to print to stdout.
try:
self._confirm_picklable(err)
except Exception as exc:
original_exc_txt = repr(err[1])
original_exc_txt = textwrap.fill(
original_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
)
pickle_exc_txt = repr(exc)
pickle_exc_txt = textwrap.fill(
pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
)
if tblib is None:
print(
"""
{} failed:
{}
Unfortunately, tracebacks cannot be pickled, making it impossible for the
parallel test runner to handle this exception cleanly.
In order to see the traceback, you should install tblib:
python -m pip install tblib
""".format(
test, original_exc_txt
)
)
else:
print(
"""
{} failed:
{}
Unfortunately, the exception it raised cannot be pickled, making it impossible
for the parallel test runner to handle it cleanly.
Here's the error encountered while trying to pickle the exception:
{}
You should re-run this test with the --parallel=1 option to reproduce the
failure and get a correct traceback.
""".format(
test, original_exc_txt, pickle_exc_txt
)
)
raise
def check_subtest_picklable(self, test, subtest):
try:
self._confirm_picklable(subtest)
except Exception as exc:
self._print_unpicklable_subtest(test, subtest, exc)
raise
def startTestRun(self):
super().startTestRun()
self.events.append(("startTestRun",))
def stopTestRun(self):
super().stopTestRun()
self.events.append(("stopTestRun",))
def startTest(self, test):
super().startTest(test)
self.events.append(("startTest", self.test_index))
def stopTest(self, test):
super().stopTest(test)
self.events.append(("stopTest", self.test_index))
def addDuration(self, test, elapsed):
super().addDuration(test, elapsed)
self.events.append(("addDuration", self.test_index, elapsed))
def addError(self, test, err):
self.check_picklable(test, err)
event_occurred_before_first_test = self.test_index == -1
if event_occurred_before_first_test and isinstance(
test, unittest.suite._ErrorHolder
):
self.events.append(("addError", self.test_index, test.id(), err))
else:
self.events.append(("addError", self.test_index, err))
super().addError(test, err)
def addFailure(self, test, err):
self.check_picklable(test, err)
self.events.append(("addFailure", self.test_index, err))
super().addFailure(test, err)
def addSubTest(self, test, subtest, err):
# Follow Python's implementation of unittest.TestResult.addSubTest() by
# not doing anything when a subtest is successful.
if err is not None:
# Call check_picklable() before check_subtest_picklable() since
# check_picklable() performs the tblib check.
self.check_picklable(test, err)
self.check_subtest_picklable(test, subtest)
self.events.append(("addSubTest", self.test_index, subtest, err))
super().addSubTest(test, subtest, err)
def addSuccess(self, test):
self.events.append(("addSuccess", self.test_index))
super().addSuccess(test)
def addSkip(self, test, reason):
self.events.append(("addSkip", self.test_index, reason))
super().addSkip(test, reason)
def addExpectedFailure(self, test, err):
# If tblib isn't installed, pickling the traceback will always fail.
# However we don't want tblib to be required for running the tests
# when they pass or fail as expected. Drop the traceback when an
# expected failure occurs.
if tblib is None:
err = err[0], err[1], None
self.check_picklable(test, err)
self.events.append(("addExpectedFailure", self.test_index, err))
super().addExpectedFailure(test, err)
def addUnexpectedSuccess(self, test):
self.events.append(("addUnexpectedSuccess", self.test_index))
super().addUnexpectedSuccess(test)
def wasSuccessful(self):
"""Tells whether or not this result was a success."""
failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"}
return all(e[0] not in failure_types for e in self.events)
def _exc_info_to_string(self, err, test):
# Make this method no-op. It only powers the default unittest behavior
# for recording errors, but this class pickles errors into 'events'
# instead.
return ""
| RemoteTestResult |
python | doocs__leetcode | solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/Solution.py | {
"start": 0,
"end": 487
} | class ____:
def minimumOperations(self, nums: List[int]) -> int:
i, j = 0, len(nums) - 1
a, b = nums[i], nums[j]
ans = 0
while i < j:
if a < b:
i += 1
a += nums[i]
ans += 1
elif b < a:
j -= 1
b += nums[j]
ans += 1
else:
i, j = i + 1, j - 1
a, b = nums[i], nums[j]
return ans
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec41.py | {
"start": 200,
"end": 522
} | class ____:
def __init__(self, x: int, y: int, z: str) -> None:
self.a = x
# This should generate an error.
@classmethod
def f(cls: Callable[P, Self], *args: P.args, **kwargs: P.kwargs) -> int:
return cls(*args, **kwargs).a
reveal_type(A.f, expected_text="(x: int, y: int, z: str) -> int")
| A |
python | h5py__h5py | h5py/_hl/base.py | {
"start": 13826,
"end": 14068
} | class ____(MappingHDF5, MutableMapping):
"""
Wraps a Group or AttributeManager object to provide a mutable
mapping interface, in contrast to the read-only mapping of
MappingHDF5.
"""
pass
| MutableMappingHDF5 |
python | facelessuser__soupsieve | tests/test_level3/test_checked.py | {
"start": 52,
"end": 1001
} | class ____(util.TestCase):
"""Test checked selectors."""
def test_checked(self):
"""Test checked."""
markup = """
<body>
<div>
<input type="radio" name="my-input" id="yes" checked>
<label for="yes">Yes</label>
<input type="radio" name="my-input" id="no">
<label for="no">No</label>
</div>
<div>
<input type="checkbox" name="my-checkbox" id="opt-in" checked>
<label for="opt-in">Check me!</label>
</div>
<select name="my-select" id="fruit">
<option id="1" value="opt1">Apples</option>
<option id="2" value="opt2" selected>Grapes</option>
<option id="3" value="opt3">Pears</option>
</select>
</body>
"""
self.assert_selector(
markup,
":checked",
['yes', 'opt-in', '2'],
flags=util.HTML
)
| TestChecked |
python | optuna__optuna | optuna/samplers/_qmc.py | {
"start": 869,
"end": 13435
} | class ____(BaseSampler):
"""A Quasi Monte Carlo Sampler that generates low-discrepancy sequences.
Quasi Monte Carlo (QMC) sequences are designed to have lower discrepancies than
standard random sequences. They are known to perform better than the standard
random sequences in hyperparameter optimization.
For further information about the use of QMC sequences for hyperparameter optimization,
please refer to the following paper:
- `Bergstra, James, and Yoshua Bengio. Random search for hyper-parameter optimization.
Journal of machine learning research 13.2, 2012.
<https://jmlr.org/papers/v13/bergstra12a.html>`__
We use the QMC implementations in Scipy. For the details of the QMC algorithm,
see the Scipy API references on `scipy.stats.qmc
<https://scipy.github.io/devdocs/reference/stats.qmc.html>`__.
.. note:
If your search space contains categorical parameters, it samples the categorical
parameters by its `independent_sampler` without using QMC algorithm.
.. note::
The search space of the sampler is determined by either previous trials in the study or
the first trial that this sampler samples.
If there are previous trials in the study, :class:`~optuna.samplers.QMCSampler` infers its
search space using the trial which was created first in the study.
Otherwise (if the study has no previous trials), :class:`~optuna.samplers.QMCSampler`
samples the first trial using its `independent_sampler` and then infers the search space
in the second trial.
As mentioned above, the search space of the :class:`~optuna.samplers.QMCSampler` is
determined by the first trial of the study. Once the search space is determined, it cannot
be changed afterwards.
Args:
qmc_type:
The type of QMC sequence to be sampled. This must be one of
`"halton"` and `"sobol"`. Default is `"sobol"`.
.. note::
Sobol' sequence is designed to have low-discrepancy property when the number of
samples is :math:`n=2^m` for each positive integer :math:`m`. When it is possible
to pre-specify the number of trials suggested by `QMCSampler`, it is recommended
that the number of trials should be set as power of two.
scramble:
If this option is :obj:`True`, scrambling (randomization) is applied to the QMC
sequences.
seed:
A seed for ``QMCSampler``. This argument is used only when ``scramble`` is :obj:`True`.
If this is :obj:`None`, the seed is initialized randomly. Default is :obj:`None`.
.. note::
When using multiple :class:`~optuna.samplers.QMCSampler`'s in parallel and/or
distributed optimization, all the samplers must share the same seed when the
`scrambling` is enabled. Otherwise, the low-discrepancy property of the samples
will be degraded.
independent_sampler:
A :class:`~optuna.samplers.BaseSampler` instance that is used for independent
sampling. The first trial of the study and the parameters not contained in the
relative search space are sampled by this sampler.
If :obj:`None` is specified, :class:`~optuna.samplers.RandomSampler` is used
as the default.
.. seealso::
:class:`~optuna.samplers` module provides built-in independent samplers
such as :class:`~optuna.samplers.RandomSampler` and
:class:`~optuna.samplers.TPESampler`.
warn_independent_sampling:
If this is :obj:`True`, a warning message is emitted when
the value of a parameter is sampled by using an independent sampler.
Note that the parameters of the first trial in a study are sampled via an
independent sampler in most cases, so no warning messages are emitted in such cases.
warn_asynchronous_seeding:
If this is :obj:`True`, a warning message is emitted when the scrambling
(randomization) is applied to the QMC sequence and the random seed of the sampler is
not set manually.
.. note::
When using parallel and/or distributed optimization without manually
setting the seed, the seed is set randomly for each instances of
:class:`~optuna.samplers.QMCSampler` for different workers, which ends up
asynchronous seeding for multiple samplers used in the optimization.
.. seealso::
See parameter ``seed`` in :class:`~optuna.samplers.QMCSampler`.
Example:
Optimize a simple quadratic function by using :class:`~optuna.samplers.QMCSampler`.
.. testcode::
import optuna
def objective(trial):
x = trial.suggest_float("x", -1, 1)
y = trial.suggest_int("y", -1, 1)
return x**2 + y
sampler = optuna.samplers.QMCSampler()
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=8)
"""
def __init__(
self,
*,
qmc_type: str = "sobol",
scramble: bool = False, # default is False for simplicity in distributed environment.
seed: int | None = None,
independent_sampler: BaseSampler | None = None,
warn_asynchronous_seeding: bool = True,
warn_independent_sampling: bool = True,
) -> None:
self._scramble = scramble
self._seed = np.random.PCG64().random_raw() if seed is None else seed
self._independent_sampler = independent_sampler or optuna.samplers.RandomSampler(seed=seed)
self._initial_search_space: dict[str, BaseDistribution] | None = None
self._warn_independent_sampling = warn_independent_sampling
if qmc_type in ("halton", "sobol"):
self._qmc_type = qmc_type
else:
message = (
f'The `qmc_type`, "{qmc_type}", is not a valid. '
'It must be one of "halton" and "sobol".'
)
raise ValueError(message)
if seed is None and scramble and warn_asynchronous_seeding:
# Sobol/Halton sequences without scrambling do not use seed.
self._log_asynchronous_seeding()
def reseed_rng(self) -> None:
# We must not reseed the `self._seed` like below. Otherwise, workers will have different
# seed under parallel execution because `self.reseed_rng()` is called when starting each
# parallel executor.
# >>> self._seed = np.random.MT19937().random_raw()
self._independent_sampler.reseed_rng()
def infer_relative_search_space(
self, study: Study, trial: FrozenTrial
) -> dict[str, BaseDistribution]:
if self._initial_search_space is not None:
return self._initial_search_space
past_trials = study._get_trials(deepcopy=False, states=_SUGGESTED_STATES, use_cache=True)
# The initial trial is sampled by the independent sampler.
if len(past_trials) == 0:
return {}
# If an initial trial was already made,
# construct search_space of this sampler from the initial trial.
first_trial = min(past_trials, key=lambda t: t.number)
self._initial_search_space = self._infer_initial_search_space(first_trial)
return self._initial_search_space
def _infer_initial_search_space(self, trial: FrozenTrial) -> dict[str, BaseDistribution]:
search_space: dict[str, BaseDistribution] = {}
for param_name, distribution in trial.distributions.items():
if isinstance(distribution, CategoricalDistribution):
continue
search_space[param_name] = distribution
return search_space
@staticmethod
def _log_asynchronous_seeding() -> None:
_logger.warning(
"No seed is provided for `QMCSampler` and the seed is set randomly. "
"If you are running multiple `QMCSampler`s in parallel and/or distributed "
" environment, the same seed must be used in all samplers to ensure that resulting "
"samples are taken from the same QMC sequence. "
)
def _log_independent_sampling(self, trial: FrozenTrial, param_name: str) -> None:
_logger.warning(
_INDEPENDENT_SAMPLING_WARNING_TEMPLATE.format(
param_name=param_name,
trial_number=trial.number,
independent_sampler_name=self._independent_sampler.__class__.__name__,
sampler_name=self.__class__.__name__,
fallback_reason=(
"dynamic search space and `CategoricalDistribution` are not supported "
"by `QMCSampler`"
),
)
)
def sample_independent(
self,
study: Study,
trial: FrozenTrial,
param_name: str,
param_distribution: BaseDistribution,
) -> Any:
if self._initial_search_space is not None:
if self._warn_independent_sampling:
self._log_independent_sampling(trial, param_name)
return self._independent_sampler.sample_independent(
study, trial, param_name, param_distribution
)
def sample_relative(
self, study: Study, trial: FrozenTrial, search_space: dict[str, BaseDistribution]
) -> dict[str, Any]:
if search_space == {}:
return {}
sample = self._sample_qmc(study, search_space)
trans = _SearchSpaceTransform(search_space)
sample = trans.bounds[:, 0] + sample * (trans.bounds[:, 1] - trans.bounds[:, 0])
return trans.untransform(sample[0, :])
def before_trial(self, study: Study, trial: FrozenTrial) -> None:
self._independent_sampler.before_trial(study, trial)
def after_trial(
self,
study: Study,
trial: "optuna.trial.FrozenTrial",
state: TrialState,
values: Sequence[float] | None,
) -> None:
self._independent_sampler.after_trial(study, trial, state, values)
def _sample_qmc(self, study: Study, search_space: dict[str, BaseDistribution]) -> np.ndarray:
# Lazy import because the `scipy.stats.qmc` is slow to import.
qmc_module = _LazyImport("scipy.stats.qmc")
sample_id = self._find_sample_id(study)
d = len(search_space)
if self._qmc_type == "halton":
qmc_engine = qmc_module.Halton(d, seed=self._seed, scramble=self._scramble)
elif self._qmc_type == "sobol":
# Sobol engine likely shares its internal state among threads.
# Without threading.Lock, ValueError exceptions are raised in Sobol engine as discussed
# in https://github.com/optuna/optunahub-registry/pull/168#pullrequestreview-2404054969
with _threading_lock:
qmc_engine = qmc_module.Sobol(d, seed=self._seed, scramble=self._scramble)
else:
raise ValueError("Invalid `qmc_type`")
forward_size = sample_id # `sample_id` starts from 0.
# Skip fast_forward with forward_size==0 because Sobol doesn't support the case,
# and fast_forward(0) doesn't affect sampling.
if forward_size > 0:
qmc_engine.fast_forward(forward_size)
sample = qmc_engine.random(1)
return sample
def _find_sample_id(self, study: Study) -> int:
qmc_id = ""
qmc_id += self._qmc_type
# Sobol/Halton sequences without scrambling do not use seed.
if self._scramble:
qmc_id += f" (scramble=True, seed={self._seed})"
else:
qmc_id += " (scramble=False)"
key_qmc_id = qmc_id + "'s last sample id"
# TODO(kstoneriv3): Here, we ideally assume that the following block is
# an atomic transaction. Without such an assumption, the current implementation
# only ensures that each `sample_id` is sampled at least once.
system_attrs = study._storage.get_study_system_attrs(study._study_id)
if key_qmc_id in system_attrs.keys():
sample_id = system_attrs[key_qmc_id]
sample_id += 1
else:
sample_id = 0
study._storage.set_study_system_attr(study._study_id, key_qmc_id, sample_id)
return sample_id
| QMCSampler |
python | eventlet__eventlet | eventlet/hubs/__init__.py | {
"start": 527,
"end": 5979
} | class ____(Exception):
pass
def get_default_hub():
"""Select the default hub implementation based on what multiplexing
libraries are installed. The order that the hubs are tried is:
* epoll
* kqueue
* poll
* select
.. include:: ../../doc/source/common.txt
.. note :: |internal|
"""
for mod in builtin_hub_modules:
if mod.is_available():
return mod
raise HubError('no built-in hubs are available: {}'.format(builtin_hub_modules))
def use_hub(mod=None):
"""Use the module *mod*, containing a class called Hub, as the
event hub. Usually not required; the default hub is usually fine.
`mod` can be an actual hub class, a module, a string, or None.
If `mod` is a class, use it directly.
If `mod` is a module, use `module.Hub` class
If `mod` is a string and contains either '.' or ':'
then `use_hub` uses 'package.subpackage.module:Class' convention,
otherwise imports `eventlet.hubs.mod`.
If `mod` is None, `use_hub` uses the default hub.
Only call use_hub during application initialization,
because it resets the hub's state and any existing
timers or listeners will never be resumed.
These two threadlocal attributes are not part of Eventlet public API:
- `threadlocal.Hub` (capital H) is hub constructor, used when no hub is currently active
- `threadlocal.hub` (lowercase h) is active hub instance
"""
if mod is None:
mod = os.environ.get('EVENTLET_HUB', None)
if mod is None:
mod = get_default_hub()
if hasattr(_threadlocal, 'hub'):
del _threadlocal.hub
classname = ''
if isinstance(mod, str):
if mod.strip() == "":
raise RuntimeError("Need to specify a hub")
if '.' in mod or ':' in mod:
modulename, _, classname = mod.strip().partition(':')
else:
modulename = 'eventlet.hubs.' + mod
mod = importlib.import_module(modulename)
if hasattr(mod, 'is_available'):
if not mod.is_available():
raise Exception('selected hub is not available on this system mod={}'.format(mod))
else:
msg = '''Please provide `is_available()` function in your custom Eventlet hub {mod}.
It must return bool: whether hub supports current platform. See eventlet/hubs/{{epoll,kqueue}} for example.
'''.format(mod=mod)
warnings.warn(msg, DeprecationWarning, stacklevel=3)
hubclass = mod
if not inspect.isclass(mod):
hubclass = getattr(mod, classname or 'Hub')
_threadlocal.Hub = hubclass
def get_hub():
"""Get the current event hub singleton object.
.. note :: |internal|
"""
try:
hub = _threadlocal.hub
except AttributeError:
try:
_threadlocal.Hub
except AttributeError:
use_hub()
hub = _threadlocal.hub = _threadlocal.Hub()
return hub
# Lame middle file import because complex dependencies in import graph
from eventlet import timeout
def trampoline(fd, read=None, write=None, timeout=None,
timeout_exc=timeout.Timeout,
mark_as_closed=None):
"""Suspend the current coroutine until the given socket object or file
descriptor is ready to *read*, ready to *write*, or the specified
*timeout* elapses, depending on arguments specified.
To wait for *fd* to be ready to read, pass *read* ``=True``; ready to
write, pass *write* ``=True``. To specify a timeout, pass the *timeout*
argument in seconds.
If the specified *timeout* elapses before the socket is ready to read or
write, *timeout_exc* will be raised instead of ``trampoline()``
returning normally.
.. note :: |internal|
"""
t = None
hub = get_hub()
current = greenlet.getcurrent()
if hub.greenlet is current:
raise RuntimeError('do not call blocking functions from the mainloop')
if (read and write):
raise RuntimeError('not allowed to trampoline for reading and writing')
try:
fileno = fd.fileno()
except AttributeError:
fileno = fd
if timeout is not None:
def _timeout(exc):
# This is only useful to insert debugging
current.throw(exc)
t = hub.schedule_call_global(timeout, _timeout, timeout_exc)
try:
if read:
listener = hub.add(hub.READ, fileno, current.switch, current.throw, mark_as_closed)
elif write:
listener = hub.add(hub.WRITE, fileno, current.switch, current.throw, mark_as_closed)
try:
return hub.switch()
finally:
hub.remove(listener)
finally:
if t is not None:
t.cancel()
def notify_close(fd):
"""
A particular file descriptor has been explicitly closed. Register for any
waiting listeners to be notified on the next run loop.
"""
hub = get_hub()
hub.notify_close(fd)
def notify_opened(fd):
"""
Some file descriptors may be closed 'silently' - that is, by the garbage
collector, by an external library, etc. When the OS returns a file descriptor
from an open call (or something similar), this may be the only indication we
have that the FD has been closed and then recycled.
We let the hub know that the old file descriptor is dead; any stuck listeners
will be disabled and notified in turn.
"""
hub = get_hub()
hub.mark_as_reopened(fd)
| HubError |
python | openai__openai-python | src/openai/types/beta/realtime/session.py | {
"start": 4272,
"end": 10183
} | class ____(BaseModel):
id: Optional[str] = None
"""Unique identifier for the session that looks like `sess_1234567890abcdef`."""
input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None
"""The format of input audio.
Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must
be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian
byte order.
"""
input_audio_noise_reduction: Optional[InputAudioNoiseReduction] = None
"""Configuration for input audio noise reduction.
This can be set to `null` to turn off. Noise reduction filters audio added to
the input audio buffer before it is sent to VAD and the model. Filtering the
audio can improve VAD and turn detection accuracy (reducing false positives) and
model performance by improving perception of the input audio.
"""
input_audio_transcription: Optional[InputAudioTranscription] = None
"""
Configuration for input audio transcription, defaults to off and can be set to
`null` to turn off once on. Input audio transcription is not native to the
model, since the model consumes audio directly. Transcription runs
asynchronously through
[the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)
and should be treated as guidance of input audio content rather than precisely
what the model heard. The client can optionally set the language and prompt for
transcription, these offer additional guidance to the transcription service.
"""
instructions: Optional[str] = None
"""The default system instructions (i.e.
system message) prepended to model calls. This field allows the client to guide
the model on desired responses. The model can be instructed on response content
and format, (e.g. "be extremely succinct", "act friendly", "here are examples of
good responses") and on audio behavior (e.g. "talk quickly", "inject emotion
into your voice", "laugh frequently"). The instructions are not guaranteed to be
followed by the model, but they provide guidance to the model on the desired
behavior.
Note that the server sets default instructions which will be used if this field
is not set and are visible in the `session.created` event at the start of the
session.
"""
max_response_output_tokens: Union[int, Literal["inf"], None] = None
"""
Maximum number of output tokens for a single assistant response, inclusive of
tool calls. Provide an integer between 1 and 4096 to limit output tokens, or
`inf` for the maximum available tokens for a given model. Defaults to `inf`.
"""
modalities: Optional[List[Literal["text", "audio"]]] = None
"""The set of modalities the model can respond with.
To disable audio, set this to ["text"].
"""
model: Optional[
Literal[
"gpt-realtime",
"gpt-realtime-2025-08-28",
"gpt-4o-realtime-preview",
"gpt-4o-realtime-preview-2024-10-01",
"gpt-4o-realtime-preview-2024-12-17",
"gpt-4o-realtime-preview-2025-06-03",
"gpt-4o-mini-realtime-preview",
"gpt-4o-mini-realtime-preview-2024-12-17",
]
] = None
"""The Realtime model used for this session."""
output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None
"""The format of output audio.
Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is
sampled at a rate of 24kHz.
"""
speed: Optional[float] = None
"""The speed of the model's spoken response.
1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed.
This value can only be changed in between model turns, not while a response is
in progress.
"""
temperature: Optional[float] = None
"""Sampling temperature for the model, limited to [0.6, 1.2].
For audio models a temperature of 0.8 is highly recommended for best
performance.
"""
tool_choice: Optional[str] = None
"""How the model chooses tools.
Options are `auto`, `none`, `required`, or specify a function.
"""
tools: Optional[List[Tool]] = None
"""Tools (functions) available to the model."""
tracing: Optional[Tracing] = None
"""Configuration options for tracing.
Set to null to disable tracing. Once tracing is enabled for a session, the
configuration cannot be modified.
`auto` will create a trace for the session with default values for the workflow
name, group id, and metadata.
"""
turn_detection: Optional[TurnDetection] = None
"""Configuration for turn detection, ether Server VAD or Semantic VAD.
This can be set to `null` to turn off, in which case the client must manually
trigger model response. Server VAD means that the model will detect the start
and end of speech based on audio volume and respond at the end of user speech.
Semantic VAD is more advanced and uses a turn detection model (in conjunction
with VAD) to semantically estimate whether the user has finished speaking, then
dynamically sets a timeout based on this probability. For example, if user audio
trails off with "uhhm", the model will score a low probability of turn end and
wait longer for the user to continue speaking. This can be useful for more
natural conversations, but may have a higher latency.
"""
voice: Union[str, Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"], None] = None
"""The voice the model uses to respond.
Voice cannot be changed during the session once the model has responded with
audio at least once. Current voice options are `alloy`, `ash`, `ballad`,
`coral`, `echo`, `sage`, `shimmer`, and `verse`.
"""
| Session |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 134792,
"end": 136762
} | class ____(Scope):
# Scope holding the __get__, __set__ and __del__ methods for
# a property of an extension type.
#
# parent_type PyExtensionType The type to which the property belongs
is_property_scope = 1
def __init__(self, name, class_scope):
# outer scope is None for some internal properties
outer_scope = class_scope.global_scope() if class_scope.outer_scope else None
Scope.__init__(self, name, outer_scope, parent_scope=class_scope)
self.parent_type = class_scope.parent_type
self.directives = class_scope.directives
def declare_cfunction(self, name, type, pos, *args, **kwargs):
"""Declare a C property function.
"""
if type.return_type.is_void:
error(pos, "C property method cannot return 'void'")
if type.args and type.args[0].type is py_object_type:
# Set 'self' argument type to extension type.
type.args[0].type = self.parent_scope.parent_type
elif len(type.args) != 1:
error(pos, "C property method must have a single (self) argument")
elif not (type.args[0].type.is_pyobject or type.args[0].type is self.parent_scope.parent_type):
error(pos, "C property method must have a single (object) argument")
entry = Scope.declare_cfunction(self, name, type, pos, *args, **kwargs)
entry.is_cproperty = True
return entry
def declare_pyfunction(self, name, pos, allow_redefine=False):
# Add an entry for a method.
signature = get_property_accessor_signature(name)
if signature:
entry = self.declare(name, name, py_object_type, pos, 'private')
entry.is_special = 1
entry.signature = signature
return entry
else:
error(pos, "Only __get__, __set__ and __del__ methods allowed "
"in a property declaration")
return None
| PropertyScope |
python | doocs__leetcode | solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py | {
"start": 0,
"end": 964
} | class ____:
def minimumChanges(self, s: str, k: int) -> int:
n = len(s)
g = [[inf] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1):
m = j - i + 1
for d in range(1, m):
if m % d == 0:
cnt = 0
for l in range(m):
r = (m // d - 1 - l // d) * d + l % d
if l >= r:
break
if s[i - 1 + l] != s[i - 1 + r]:
cnt += 1
g[i][j] = min(g[i][j], cnt)
f = [[inf] * (k + 1) for _ in range(n + 1)]
f[0][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
for h in range(i - 1):
f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i])
return f[n][k]
| Solution |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 10579,
"end": 16381
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
config: MoonshineConfig,
layer_idx: int,
is_causal: bool,
num_attention_heads: int,
num_key_value_heads: int,
):
super().__init__()
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_causal = is_causal
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
self.rotary_fn = apply_rotary_pos_emb
# Pad head dimension to the next specified multiple.
if self.config.pad_head_dim_to_multiple_of is not None:
target_multiple = self.config.pad_head_dim_to_multiple_of
target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
self.head_dim_padding = target_head_dim - self.head_dim
else:
self.head_dim_padding = 0
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
key_value_states: Optional[torch.Tensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
bsz, q_len = hidden_states.shape[:-1]
query_states = (
self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
)
is_cross_attention = key_value_states is not None
if past_key_values is not None:
is_updated = past_key_values.is_updated.get(self.layer_idx)
if is_cross_attention:
# after the first generated id, we can subsequently re-use all key/value_states from cache
past_key_values.is_updated[self.layer_idx] = True
past_key_values = past_key_values.cross_attention_cache
else:
past_key_values = past_key_values.self_attention_cache
# use key_value_states if cross attention
current_states = key_value_states if key_value_states is not None else hidden_states
if is_cross_attention and past_key_values and is_updated:
key_states = past_key_values.layers[self.layer_idx].keys
value_states = past_key_values.layers[self.layer_idx].values
else:
key_states = (
self.k_proj(current_states)
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
.transpose(1, 2)
)
value_states = (
self.v_proj(current_states)
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
.transpose(1, 2)
)
if is_cross_attention and past_key_values is not None:
key_states, value_states = past_key_values.update(
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
)
if not is_cross_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(
key_states, value_states, self.layer_idx, cache_kwargs
)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
is_causal = self.is_causal and attention_mask is None and q_len > 1
if self.head_dim_padding > 0:
query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
is_causal=is_causal,
**kwargs,
)
if self.head_dim_padding > 0:
attn_output = attn_output[..., : -self.head_dim_padding]
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| MoonshineAttention |
python | numpy__numpy | numpy/ma/tests/test_extras.py | {
"start": 56752,
"end": 58815
} | class ____:
def test_polyfit(self):
# Tests polyfit
# On ndarrays
x = np.random.rand(10)
y = np.random.rand(20).reshape(-1, 2)
assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3))
# ON 1D maskedarrays
x = x.view(MaskedArray)
x[0] = masked
y = y.view(MaskedArray)
y[0, 0] = y[-1, -1] = masked
#
(C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True)
(c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3,
full=True)
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
assert_almost_equal(a, a_)
#
(C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True)
(c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True)
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
assert_almost_equal(a, a_)
#
(C, R, K, S, D) = polyfit(x, y, 3, full=True)
(c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, :], 3, full=True)
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
assert_almost_equal(a, a_)
#
w = np.random.rand(10) + 1
wo = w.copy()
xs = x[1:-1]
ys = y[1:-1]
ws = w[1:-1]
(C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w)
(c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws)
assert_equal(w, wo)
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
assert_almost_equal(a, a_)
def test_polyfit_with_masked_NaNs(self):
x = np.random.rand(10)
y = np.random.rand(20).reshape(-1, 2)
x[0] = np.nan
y[-1, -1] = np.nan
x = x.view(MaskedArray)
y = y.view(MaskedArray)
x[0] = masked
y[-1, -1] = masked
(C, R, K, S, D) = polyfit(x, y, 3, full=True)
(c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, :], 3, full=True)
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
assert_almost_equal(a, a_)
| TestPolynomial |
python | kamyu104__LeetCode-Solutions | Python/word-abbreviation.py | {
"start": 73,
"end": 1194
} | class ____(object):
def wordsAbbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
def isUnique(prefix, words):
return sum(word.startswith(prefix) for word in words) == 1
def toAbbr(prefix, word):
abbr = prefix + str(len(word) - 1 - len(prefix)) + word[-1]
return abbr if len(abbr) < len(word) else word
abbr_to_word = collections.defaultdict(set)
word_to_abbr = {}
for word in dict:
prefix = word[:1]
abbr_to_word[toAbbr(prefix, word)].add(word)
for abbr, conflicts in abbr_to_word.iteritems():
if len(conflicts) > 1:
for word in conflicts:
for i in xrange(2, len(word)):
prefix = word[:i]
if isUnique(prefix, conflicts):
word_to_abbr[word] = toAbbr(prefix, word)
break
else:
word_to_abbr[conflicts.pop()] = abbr
return [word_to_abbr[word] for word in dict]
| Solution |
python | huggingface__transformers | tests/models/cpmant/test_modeling_cpmant.py | {
"start": 6234,
"end": 6907
} | class ____(unittest.TestCase):
@tooslow
def test_inference_masked_lm(self):
texts = "今天天气真好!"
model_path = "openbmb/cpm-ant-10b"
model = CpmAntModel.from_pretrained(model_path)
tokenizer = CpmAntTokenizer.from_pretrained(model_path)
inputs = tokenizer(texts, return_tensors="pt")
hidden_states = model(**inputs).last_hidden_state
expected_slice = torch.tensor(
[[[6.1708, 5.9244, 1.0835], [6.5207, 6.2893, -11.3324], [-1.0107, -0.0576, -5.9577]]],
)
torch.testing.assert_close(hidden_states[:, :3, :3], expected_slice, rtol=1e-2, atol=1e-2)
@require_torch
| CpmAntModelIntegrationTest |
python | mitmproxy__pdoc | test/testdata/misc.py | {
"start": 7905,
"end": 8803
} | class ____:
@functools.singledispatchmethod
def fancymethod(self, str_or_int: str | int):
"""A fancy method which is capable of handling either `str` or `int`.
:param str_or_int: string or integer to handle
"""
raise NotImplementedError(f"{type(str_or_int)=} not implemented!")
@fancymethod.register
def fancymethod_handle_str(self, str_to_handle: str):
"""Fancy method handles a string.
:param str_to_handle: string which will be handled
"""
print(f"{type(str_to_handle)} = '{str_to_handle}")
@fancymethod.register
def _fancymethod_handle_int(self, int_to_handle: int):
"""Fancy method handles int (not shown in doc).
:param int_to_handle: int which will be handled
"""
print(f"{type(int_to_handle)} = '{int_to_handle:x}'")
@dataclass(init=False)
| SingleDispatchMethodExample |
python | ray-project__ray | python/ray/train/examples/pytorch/torch_fashion_mnist_example.py | {
"start": 1257,
"end": 4851
} | class ____(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Dropout(0.25),
nn.Linear(512, 512),
nn.ReLU(),
nn.Dropout(0.25),
nn.Linear(512, 10),
nn.ReLU(),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
def train_func_per_worker(config: Dict):
ray.train.torch.enable_reproducibility()
lr = config["lr"]
epochs = config["epochs"]
batch_size = config["batch_size_per_worker"]
# Get dataloaders inside the worker training function
train_dataloader, test_dataloader = get_dataloaders(batch_size=batch_size)
# [1] Prepare Dataloader for distributed training
# Shard the datasets among workers and move batches to the correct device
# =======================================================================
train_dataloader = ray.train.torch.prepare_data_loader(train_dataloader)
test_dataloader = ray.train.torch.prepare_data_loader(test_dataloader)
model = NeuralNetwork()
# [2] Prepare and wrap your model with DistributedDataParallel
# Move the model to the correct GPU/CPU device
# ============================================================
model = ray.train.torch.prepare_model(model)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
# Model training loop
for epoch in range(epochs):
if ray.train.get_context().get_world_size() > 1:
# Required for the distributed sampler to shuffle properly across epochs.
train_dataloader.sampler.set_epoch(epoch)
model.train()
for X, y in tqdm(train_dataloader, desc=f"Train Epoch {epoch}"):
pred = model(X)
loss = loss_fn(pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
test_loss, num_correct, num_total = 0, 0, 0
with torch.no_grad():
for X, y in tqdm(test_dataloader, desc=f"Test Epoch {epoch}"):
pred = model(X)
loss = loss_fn(pred, y)
test_loss += loss.item()
num_total += y.shape[0]
num_correct += (pred.argmax(1) == y).sum().item()
test_loss /= len(test_dataloader)
accuracy = num_correct / num_total
# [3] Report metrics to Ray Train
# ===============================
ray.train.report(metrics={"loss": test_loss, "accuracy": accuracy})
def train_fashion_mnist(num_workers=2, use_gpu=False):
global_batch_size = 32
train_config = {
"lr": 1e-3,
"epochs": 10,
"batch_size_per_worker": global_batch_size // num_workers,
}
# Configure computation resources
scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu)
# Initialize a Ray TorchTrainer
trainer = TorchTrainer(
train_loop_per_worker=train_func_per_worker,
train_loop_config=train_config,
scaling_config=scaling_config,
)
# [4] Start distributed training
# Run `train_func_per_worker` on all workers
# =============================================
result = trainer.fit()
print(f"Training result: {result}")
if __name__ == "__main__":
train_fashion_mnist(num_workers=4, use_gpu=True)
| NeuralNetwork |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 1538,
"end": 1891
} | class ____(BaseEvent):
"""Event emitted when attachment processing begins."""
page_id: str
attachment_id: str
attachment_name: str
attachment_type: str
attachment_size: int
attachment_link: str
@classmethod
def class_name(cls) -> str:
return "AttachmentProcessingStartedEvent"
| AttachmentProcessingStartedEvent |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 39725,
"end": 42787
} | class ____(FNetPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.fnet = FNetModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, QuestionAnsweringModelOutput]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.fnet(
input_ids,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states
)
__all__ = [
"FNetForMaskedLM",
"FNetForMultipleChoice",
"FNetForNextSentencePrediction",
"FNetForPreTraining",
"FNetForQuestionAnswering",
"FNetForSequenceClassification",
"FNetForTokenClassification",
"FNetLayer",
"FNetModel",
"FNetPreTrainedModel",
]
| FNetForQuestionAnswering |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.