本文整理汇总了Python中dataclasses.astuple方法的典型用法代码示例。如果您正苦于以下问题:Python dataclasses.astuple方法的具体用法?Python dataclasses.astuple怎么用?Python dataclasses.astuple使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dataclasses
的用法示例。
在下文中一共展示了dataclasses.astuple方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hands
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def hands(h: int, c: int) -> Tuple[Dict[str, Any], int]:
if h == 0 or c == 0:
return jsonify(
status="Bad Request", error=[f"hands={h!r}, dominoes={c!r} is invalid"]
), HTTPStatus.BAD_REQUEST
if app.env == "development":
random.seed(2)
b = Boneyard(limit=6)
try:
hand_list = b.deal(c, h)
except ValueError as ex:
return jsonify(status="Bad Request", error=ex.args), HTTPStatus.BAD_REQUEST
app.logger.info("Send %r", hand_list)
return jsonify(
status="OK", dominoes=[[astuple(d) for d in hand] for hand in hand_list]
), HTTPStatus.OK
示例2: __iter__
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def __iter__(self) -> Iterator[Tuple]:
"""Yield statistical samples."""
x, y = self.table.payout
blackjack_payout = x / y
for count in range(self.samples):
self.player.reset()
while self.player.stake > 0 and self.player.rounds > 0:
self.player.rounds -= 1
outcome = random.random()
if outcome < 0.579:
self.player.stake -= 1
elif 0.579 <= outcome < 0.883:
self.player.stake += 1
elif 0.883 <= outcome < 0.943:
# a "push"
pass
else:
# 0.943 <= outcome
self.player.stake += blackjack_payout
yield astuple(self.table) + astuple(self.player)
开发者ID:PacktPublishing,项目名称:Mastering-Object-Oriented-Python-Second-Edition,代码行数:24,代码来源:simulation_model.py
示例3: simulate
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def simulate(initial_state, config, intervention=None, seed=None):
"""Simulate a run of the Lotka volterra model.
Parameters
----------
initial_state: whynot.lotka_volterra.State
config: whynot.lotka_volterra.Config
Base parameters for the simulator run
intervention: whynot.lotka_volterra.Intervention
(Optional) Parameters specifying a change in dynamics
seed: int
Unused since the simulator is deterministic.
Returns
-------
run: whynot.dynamics.Run
Simulator rollout
"""
# pylint: disable-msg=unused-argument
t_eval = np.arange(
config.start_time, config.end_time + config.delta_t, config.delta_t
)
solution = odeint(
dynamics,
y0=dataclasses.astuple(initial_state),
t=t_eval,
args=(config, intervention),
rtol=1e-4,
atol=1e-4,
)
states = [initial_state] + [State(*state) for state in solution[1:]]
return wn.dynamics.Run(states=states, times=t_eval)
示例4: simulate
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def simulate(initial_state, config, intervention=None, seed=None):
"""Simulate a run of the Adams HIV simulator model.
The simulation starts at initial_state at time 0, and evolves the state
using dynamics whose parameters are specified in config.
Parameters
----------
initial_state: `whynot.simulators.hiv.State`
Initial State object, which is used as x_{t_0} for the simulator.
config: `whynot.simulators.hiv.Config`
Config object that encapsulates the parameters that define the dynamics.
intervention: `whynot.simulators.hiv.Intervention`
Intervention object that specifies what, if any, intervention to perform.
seed: int
Seed to set internal randomness. The simulator is deterministic, so
the seed parameter is ignored.
Returns
-------
run: `whynot.dynamics.Run`
Rollout of the model.
"""
# Simulator is deterministic, so seed is ignored
# pylint: disable-msg=unused-argument
t_eval = np.arange(
config.start_time, config.end_time + config.delta_t, config.delta_t
)
solution = odeint(
dynamics,
y0=dataclasses.astuple(initial_state),
t=t_eval,
args=(config, intervention),
rtol=config.rtol,
atol=config.atol,
)
states = [initial_state] + [State(*state) for state in solution[1:]]
return wn.dynamics.Run(states=states, times=t_eval)
示例5: simulate
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def simulate(initial_state, config, intervention=None, seed=None):
"""Simulate a run of the Zika simulator model.
The simulation starts at initial_state at time 0, and evolves the state
using dynamics whose parameters are specified in config.
Parameters
----------
initial_state: `whynot.simulators.zika.State`
Initial State object, which is used as x_{t_0} for the simulator.
config: `whynot.simulators.zika.Config`
Config object that encapsulates the parameters that define the dynamics.
intervention: `whynot.simulators.zika.Intervention`
Intervention object that specifies what, if any, intervention to perform.
seed: int
Seed to set internal randomness. The simulator is deterministic, so
the seed parameter is ignored.
Returns
-------
run: `whynot.dynamics.Run`
Rollout of the model.
"""
# Simulator is deterministic, so seed is ignored
# pylint: disable-msg=unused-argument
t_eval = np.arange(
config.start_time, config.end_time + config.delta_t, config.delta_t
)
solution = odeint(
dynamics,
y0=dataclasses.astuple(initial_state),
t=t_eval,
args=(config, intervention),
rtol=config.rtol,
atol=config.atol,
)
states = [initial_state] + [State(*state) for state in solution[1:]]
return wn.dynamics.Run(states=states, times=t_eval)
示例6: simulate
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def simulate(initial_state, config, intervention=None, seed=None):
"""Simulate a run of the Chen et al. model opioid epidemic model.
Parameters
----------
initial_state: whynot.simulator.opioid.State
Initial state of the dynamics
config: whynot.simulator.opioid.Config
Config object to determine simulation dynamics.
intervention: whynot.simulator.opioid.Intervention
(Optional) Intervention object to determine what, if any,
intervention to perform during the rollout of the dynamics.
seed: int
The simulator is deterministic, so the seed parameter is ignored.
Returns
-------
run: whynot.dynamics.Run
Run object produced by running simulate for the opioid simulator
"""
# pylint: disable-msg=unused-argument
# pylint:disable-msg=no-member
t_eval = np.arange(
config.start_time, config.end_time + config.delta_t, config.delta_t
)
solution = odeint(
dynamics,
y0=dataclasses.astuple(initial_state),
t=t_eval,
args=(config, intervention),
rtol=1e-4,
atol=1e-4,
)
states = [initial_state] + [State(*state) for state in solution[1:]]
return wn.dynamics.Run(states=states, times=t_eval)
示例7: simulate
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def simulate(initial_state, config, intervention=None, seed=None):
"""Run a simulation of the world2 dynamics from the given initial state.
Parameters
----------
initial_state: whynot.simulators.world2.State
State object to initialize the simulation
config: whynot.simulators.world2.Config
Configuration object to determine coefficients of the dynamics.
intervention: whynot.simulators.world2.Intervention
(Optional) Specify what, if any, intervention to perform during execution.
seed: int
(Optional) The simulator is deterministic, and the seed parameter is ignored.
Returns
-------
run: whynot.dynamics.Run
Rollout sequence of states and measurement times produced by the simulator.
"""
# Simulator is deterministic, so seed is ignored
# pylint: disable-msg=unused-argument
t_eval = np.arange(
config.start_time, config.end_time + config.delta_t, config.delta_t
)
solution = odeint(
dynamics,
y0=dataclasses.astuple(initial_state),
t=t_eval,
args=(config, intervention),
rtol=config.rtol,
atol=config.atol,
)
states = [initial_state] + [State(*state) for state in solution[1:]]
return wn.dynamics.Run(states=states, times=t_eval)
示例8: id3Encode
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def id3Encode(self):
return "\t".join([(o if o else "") for o in dataclasses.astuple(self)])
示例9: test_default_v23
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def test_default_v23():
f = RelVolAdjFrameV23()
assert f.id == b"RVAD"
f.adjustments = RelVolAdjFrameV23.VolumeAdjustments()
f.render()
f2 = RelVolAdjFrameV23()
f2.parse(f.data, f.header)
assert f.adjustments == f2.adjustments
assert set(dataclasses.astuple(f.adjustments)) == {0}
示例10: to_device
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def to_device(data, device=None, dtype=None, non_blocking=False, copy=False):
"""Change the device of object recursively"""
if isinstance(data, dict):
return {
k: to_device(v, device, dtype, non_blocking, copy) for k, v in data.items()
}
elif dataclasses.is_dataclass(data) and not isinstance(data, type):
return type(data)(
*[
to_device(v, device, dtype, non_blocking, copy)
for v in dataclasses.astuple(data)
]
)
# maybe namedtuple. I don't know the correct way to judge namedtuple.
elif isinstance(data, tuple) and type(data) is not tuple:
return type(data)(
*[to_device(o, device, dtype, non_blocking, copy) for o in data]
)
elif isinstance(data, (list, tuple)):
return type(data)(to_device(v, device, dtype, non_blocking, copy) for v in data)
elif isinstance(data, np.ndarray):
return to_device(torch.from_numpy(data), device, dtype, non_blocking, copy)
elif isinstance(data, torch.Tensor):
return data.to(device, dtype, non_blocking, copy)
else:
return data
示例11: copy
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def copy(self):
"""Make a copy of preference data."""
return Preferences(*astuple(self))
示例12: edit_point
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def edit_point(self, row: int, arg: PointArgs) -> None:
"""Edit a point."""
for i, e in enumerate((f'Point{row}',)
+ astuple(arg)
+ (f"({arg.x}, {arg.y})",)):
item = QTableWidgetItem(str(e))
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
if i == 3:
item.setIcon(color_icon(e))
self.setItem(row, i, item)
示例13: edit_link
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def edit_link(self, row: int, arg: LinkArgs):
"""Edit a link."""
for i, e in enumerate(astuple(arg)):
item = QTableWidgetItem(e)
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
if i == 1:
item.setIcon(color_icon(e))
self.setItem(row, i, item)
示例14: render_coordinates_to_rows
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def render_coordinates_to_rows(
tile_to_physical_coordinates: Mapping[
TileIdentifier, Mapping[Coordinates, CoordinateValue]],
) -> Sequence[Mapping[str, str]]:
results: MutableSequence[Mapping[str, str]] = list()
for tile_identifier, physical_coordinates in tile_to_physical_coordinates.items():
rowdata: MutableMapping[str, str] = dict()
for tile_coordinate_name, tile_coordinate_value in zip(
TILE_COORDINATE_NAMES, dataclasses.astuple(tile_identifier)
):
rowdata[tile_coordinate_name] = str(tile_coordinate_value)
for coordinate_name in list(Coordinates):
coordinate_value = physical_coordinates.get(coordinate_name, None)
if coordinate_value is None and coordinate_name == Coordinates.Z:
# Z coordinates may be legitimately missing
continue
if isinstance(coordinate_value, tuple):
rowdata[f'{coordinate_name}_min'] = str(coordinate_value[0])
rowdata[f'{coordinate_name}_max'] = str(coordinate_value[1])
else:
rowdata[f'{coordinate_name}_min'] = str(coordinate_value)
results.append(rowdata)
return results
示例15: __eq__
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import astuple [as 别名]
def __eq__(self, other: "Flow") -> bool:
"""Checks if two dataclasses are equal to which other.
We need to implement equality operator separately to handle NumPy
arrays, which require calling `.all()` to indicate equality.
Args:
other: Flow to compare to.
Returns:
`True` only if `self` and `other` are the same type and their
values are equal.
Raises:
NotImplemented: If the flow types are different between `self`
and `other`.
"""
if self is other:
return True
if self.__class__ != other.__class__:
raise NotImplemented(
"Cannot compare flow types, got {} and {}".format(self, other))
for val1, val2 in zip(dataclasses.astuple(self),
dataclasses.astuple(other)):
if val1 is val2:
equal = True
elif isinstance(val1, np.ndarray) and isinstance(val2, np.ndarray):
equal = (val1.shape == val2.shape) and (val1 == val2).all()
else:
equal = val1 == val2
if not equal:
return False
return True