repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
libtcod/python-tcod
tcod/libtcodpy.py
map_set_properties
def map_set_properties( m: tcod.map.Map, x: int, y: int, isTrans: bool, isWalk: bool ) -> None: """Set the properties of a single cell. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ lib.TCOD_map_set_properties(m.map_c, x, y, isTrans, isWalk)
python
def map_set_properties( m: tcod.map.Map, x: int, y: int, isTrans: bool, isWalk: bool ) -> None: """Set the properties of a single cell. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ lib.TCOD_map_set_properties(m.map_c, x, y, isTrans, isWalk)
[ "def", "map_set_properties", "(", "m", ":", "tcod", ".", "map", ".", "Map", ",", "x", ":", "int", ",", "y", ":", "int", ",", "isTrans", ":", "bool", ",", "isWalk", ":", "bool", ")", "->", "None", ":", "lib", ".", "TCOD_map_set_properties", "(", "m", ".", "map_c", ",", "x", ",", "y", ",", "isTrans", ",", "isWalk", ")" ]
Set the properties of a single cell. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties.
[ "Set", "the", "properties", "of", "a", "single", "cell", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3187-L3198
train
libtcod/python-tcod
tcod/libtcodpy.py
map_clear
def map_clear( m: tcod.map.Map, transparent: bool = False, walkable: bool = False ) -> None: """Change all map cells to a specific value. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ m.transparent[:] = transparent m.walkable[:] = walkable
python
def map_clear( m: tcod.map.Map, transparent: bool = False, walkable: bool = False ) -> None: """Change all map cells to a specific value. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ m.transparent[:] = transparent m.walkable[:] = walkable
[ "def", "map_clear", "(", "m", ":", "tcod", ".", "map", ".", "Map", ",", "transparent", ":", "bool", "=", "False", ",", "walkable", ":", "bool", "=", "False", ")", "->", "None", ":", "m", ".", "transparent", "[", ":", "]", "=", "transparent", "m", ".", "walkable", "[", ":", "]", "=", "walkable" ]
Change all map cells to a specific value. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties.
[ "Change", "all", "map", "cells", "to", "a", "specific", "value", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3202-L3212
train
libtcod/python-tcod
tcod/libtcodpy.py
map_compute_fov
def map_compute_fov( m: tcod.map.Map, x: int, y: int, radius: int = 0, light_walls: bool = True, algo: int = FOV_RESTRICTIVE, ) -> None: """Compute the field-of-view for a map instance. .. deprecated:: 4.5 Use :any:`tcod.map.Map.compute_fov` instead. """ m.compute_fov(x, y, radius, light_walls, algo)
python
def map_compute_fov( m: tcod.map.Map, x: int, y: int, radius: int = 0, light_walls: bool = True, algo: int = FOV_RESTRICTIVE, ) -> None: """Compute the field-of-view for a map instance. .. deprecated:: 4.5 Use :any:`tcod.map.Map.compute_fov` instead. """ m.compute_fov(x, y, radius, light_walls, algo)
[ "def", "map_compute_fov", "(", "m", ":", "tcod", ".", "map", ".", "Map", ",", "x", ":", "int", ",", "y", ":", "int", ",", "radius", ":", "int", "=", "0", ",", "light_walls", ":", "bool", "=", "True", ",", "algo", ":", "int", "=", "FOV_RESTRICTIVE", ",", ")", "->", "None", ":", "m", ".", "compute_fov", "(", "x", ",", "y", ",", "radius", ",", "light_walls", ",", "algo", ")" ]
Compute the field-of-view for a map instance. .. deprecated:: 4.5 Use :any:`tcod.map.Map.compute_fov` instead.
[ "Compute", "the", "field", "-", "of", "-", "view", "for", "a", "map", "instance", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3216-L3229
train
libtcod/python-tcod
tcod/libtcodpy.py
map_is_in_fov
def map_is_in_fov(m: tcod.map.Map, x: int, y: int) -> bool: """Return True if the cell at x,y is lit by the last field-of-view algorithm. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.fov` to check this property. """ return bool(lib.TCOD_map_is_in_fov(m.map_c, x, y))
python
def map_is_in_fov(m: tcod.map.Map, x: int, y: int) -> bool: """Return True if the cell at x,y is lit by the last field-of-view algorithm. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.fov` to check this property. """ return bool(lib.TCOD_map_is_in_fov(m.map_c, x, y))
[ "def", "map_is_in_fov", "(", "m", ":", "tcod", ".", "map", ".", "Map", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "lib", ".", "TCOD_map_is_in_fov", "(", "m", ".", "map_c", ",", "x", ",", "y", ")", ")" ]
Return True if the cell at x,y is lit by the last field-of-view algorithm. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.fov` to check this property.
[ "Return", "True", "if", "the", "cell", "at", "x", "y", "is", "lit", "by", "the", "last", "field", "-", "of", "-", "view", "algorithm", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3233-L3242
train
libtcod/python-tcod
tcod/libtcodpy.py
noise_new
def noise_new( dim: int, h: float = NOISE_DEFAULT_HURST, l: float = NOISE_DEFAULT_LACUNARITY, # noqa: E741 random: Optional[tcod.random.Random] = None, ) -> tcod.noise.Noise: """Return a new Noise instance. Args: dim (int): Number of dimensions. From 1 to 4. h (float): The hurst exponent. Should be in the 0.0-1.0 range. l (float): The noise lacunarity. random (Optional[Random]): A Random instance, or None. Returns: Noise: The new Noise instance. """ return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random)
python
def noise_new( dim: int, h: float = NOISE_DEFAULT_HURST, l: float = NOISE_DEFAULT_LACUNARITY, # noqa: E741 random: Optional[tcod.random.Random] = None, ) -> tcod.noise.Noise: """Return a new Noise instance. Args: dim (int): Number of dimensions. From 1 to 4. h (float): The hurst exponent. Should be in the 0.0-1.0 range. l (float): The noise lacunarity. random (Optional[Random]): A Random instance, or None. Returns: Noise: The new Noise instance. """ return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random)
[ "def", "noise_new", "(", "dim", ":", "int", ",", "h", ":", "float", "=", "NOISE_DEFAULT_HURST", ",", "l", ":", "float", "=", "NOISE_DEFAULT_LACUNARITY", ",", "# noqa: E741", "random", ":", "Optional", "[", "tcod", ".", "random", ".", "Random", "]", "=", "None", ",", ")", "->", "tcod", ".", "noise", ".", "Noise", ":", "return", "tcod", ".", "noise", ".", "Noise", "(", "dim", ",", "hurst", "=", "h", ",", "lacunarity", "=", "l", ",", "seed", "=", "random", ")" ]
Return a new Noise instance. Args: dim (int): Number of dimensions. From 1 to 4. h (float): The hurst exponent. Should be in the 0.0-1.0 range. l (float): The noise lacunarity. random (Optional[Random]): A Random instance, or None. Returns: Noise: The new Noise instance.
[ "Return", "a", "new", "Noise", "instance", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3356-L3373
train
libtcod/python-tcod
tcod/libtcodpy.py
noise_set_type
def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: """Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant. """ n.algorithm = typ
python
def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: """Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant. """ n.algorithm = typ
[ "def", "noise_set_type", "(", "n", ":", "tcod", ".", "noise", ".", "Noise", ",", "typ", ":", "int", ")", "->", "None", ":", "n", ".", "algorithm", "=", "typ" ]
Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant.
[ "Set", "a", "Noise", "objects", "default", "noise", "algorithm", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3377-L3383
train
libtcod/python-tcod
tcod/libtcodpy.py
noise_get
def noise_get( n: tcod.noise.Noise, f: Sequence[float], typ: int = NOISE_DEFAULT ) -> float: """Return the noise value sampled from the ``f`` coordinate. ``f`` should be a tuple or list with a length matching :any:`Noise.dimensions`. If ``f`` is shoerter than :any:`Noise.dimensions` the missing coordinates will be filled with zeros. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. Returns: float: The sampled noise value. """ return float(lib.TCOD_noise_get_ex(n.noise_c, ffi.new("float[4]", f), typ))
python
def noise_get( n: tcod.noise.Noise, f: Sequence[float], typ: int = NOISE_DEFAULT ) -> float: """Return the noise value sampled from the ``f`` coordinate. ``f`` should be a tuple or list with a length matching :any:`Noise.dimensions`. If ``f`` is shoerter than :any:`Noise.dimensions` the missing coordinates will be filled with zeros. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. Returns: float: The sampled noise value. """ return float(lib.TCOD_noise_get_ex(n.noise_c, ffi.new("float[4]", f), typ))
[ "def", "noise_get", "(", "n", ":", "tcod", ".", "noise", ".", "Noise", ",", "f", ":", "Sequence", "[", "float", "]", ",", "typ", ":", "int", "=", "NOISE_DEFAULT", ")", "->", "float", ":", "return", "float", "(", "lib", ".", "TCOD_noise_get_ex", "(", "n", ".", "noise_c", ",", "ffi", ".", "new", "(", "\"float[4]\"", ",", "f", ")", ",", "typ", ")", ")" ]
Return the noise value sampled from the ``f`` coordinate. ``f`` should be a tuple or list with a length matching :any:`Noise.dimensions`. If ``f`` is shoerter than :any:`Noise.dimensions` the missing coordinates will be filled with zeros. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. Returns: float: The sampled noise value.
[ "Return", "the", "noise", "value", "sampled", "from", "the", "f", "coordinate", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3387-L3405
train
libtcod/python-tcod
tcod/libtcodpy.py
noise_get_fbm
def noise_get_fbm( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new("float[4]", f), oc, typ) )
python
def noise_get_fbm( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new("float[4]", f), oc, typ) )
[ "def", "noise_get_fbm", "(", "n", ":", "tcod", ".", "noise", ".", "Noise", ",", "f", ":", "Sequence", "[", "float", "]", ",", "oc", ":", "float", ",", "typ", ":", "int", "=", "NOISE_DEFAULT", ",", ")", "->", "float", ":", "return", "float", "(", "lib", ".", "TCOD_noise_get_fbm_ex", "(", "n", ".", "noise_c", ",", "ffi", ".", "new", "(", "\"float[4]\"", ",", "f", ")", ",", "oc", ",", "typ", ")", ")" ]
Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value.
[ "Return", "the", "fractal", "Brownian", "motion", "sampled", "from", "the", "f", "coordinate", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3409-L3428
train
libtcod/python-tcod
tcod/libtcodpy.py
noise_get_turbulence
def noise_get_turbulence( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the turbulence noise sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_turbulence_ex( n.noise_c, ffi.new("float[4]", f), oc, typ ) )
python
def noise_get_turbulence( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the turbulence noise sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_turbulence_ex( n.noise_c, ffi.new("float[4]", f), oc, typ ) )
[ "def", "noise_get_turbulence", "(", "n", ":", "tcod", ".", "noise", ".", "Noise", ",", "f", ":", "Sequence", "[", "float", "]", ",", "oc", ":", "float", ",", "typ", ":", "int", "=", "NOISE_DEFAULT", ",", ")", "->", "float", ":", "return", "float", "(", "lib", ".", "TCOD_noise_get_turbulence_ex", "(", "n", ".", "noise_c", ",", "ffi", ".", "new", "(", "\"float[4]\"", ",", "f", ")", ",", "oc", ",", "typ", ")", ")" ]
Return the turbulence noise sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value.
[ "Return", "the", "turbulence", "noise", "sampled", "from", "the", "f", "coordinate", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3432-L3453
train
libtcod/python-tcod
tcod/libtcodpy.py
random_get_instance
def random_get_instance() -> tcod.random.Random: """Return the default Random instance. Returns: Random: A Random instance using the default random number generator. """ return tcod.random.Random._new_from_cdata( ffi.cast("mersenne_data_t*", lib.TCOD_random_get_instance()) )
python
def random_get_instance() -> tcod.random.Random: """Return the default Random instance. Returns: Random: A Random instance using the default random number generator. """ return tcod.random.Random._new_from_cdata( ffi.cast("mersenne_data_t*", lib.TCOD_random_get_instance()) )
[ "def", "random_get_instance", "(", ")", "->", "tcod", ".", "random", ".", "Random", ":", "return", "tcod", ".", "random", ".", "Random", ".", "_new_from_cdata", "(", "ffi", ".", "cast", "(", "\"mersenne_data_t*\"", ",", "lib", ".", "TCOD_random_get_instance", "(", ")", ")", ")" ]
Return the default Random instance. Returns: Random: A Random instance using the default random number generator.
[ "Return", "the", "default", "Random", "instance", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3635-L3643
train
libtcod/python-tcod
tcod/libtcodpy.py
random_new
def random_new(algo: int = RNG_CMWC) -> tcod.random.Random: """Return a new Random instance. Using ``algo``. Args: algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo)
python
def random_new(algo: int = RNG_CMWC) -> tcod.random.Random: """Return a new Random instance. Using ``algo``. Args: algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo)
[ "def", "random_new", "(", "algo", ":", "int", "=", "RNG_CMWC", ")", "->", "tcod", ".", "random", ".", "Random", ":", "return", "tcod", ".", "random", ".", "Random", "(", "algo", ")" ]
Return a new Random instance. Using ``algo``. Args: algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm.
[ "Return", "a", "new", "Random", "instance", ".", "Using", "algo", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3647-L3656
train
libtcod/python-tcod
tcod/libtcodpy.py
random_new_from_seed
def random_new_from_seed( seed: Hashable, algo: int = RNG_CMWC ) -> tcod.random.Random: """Return a new Random instance. Using the given ``seed`` and ``algo``. Args: seed (Hashable): The RNG seed. Should be a 32-bit integer, but any hashable object is accepted. algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo, seed)
python
def random_new_from_seed( seed: Hashable, algo: int = RNG_CMWC ) -> tcod.random.Random: """Return a new Random instance. Using the given ``seed`` and ``algo``. Args: seed (Hashable): The RNG seed. Should be a 32-bit integer, but any hashable object is accepted. algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo, seed)
[ "def", "random_new_from_seed", "(", "seed", ":", "Hashable", ",", "algo", ":", "int", "=", "RNG_CMWC", ")", "->", "tcod", ".", "random", ".", "Random", ":", "return", "tcod", ".", "random", ".", "Random", "(", "algo", ",", "seed", ")" ]
Return a new Random instance. Using the given ``seed`` and ``algo``. Args: seed (Hashable): The RNG seed. Should be a 32-bit integer, but any hashable object is accepted. algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm.
[ "Return", "a", "new", "Random", "instance", ".", "Using", "the", "given", "seed", "and", "algo", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3660-L3673
train
libtcod/python-tcod
tcod/libtcodpy.py
random_set_distribution
def random_set_distribution( rnd: Optional[tcod.random.Random], dist: int ) -> None: """Change the distribution mode of a random number generator. Args: rnd (Optional[Random]): A Random instance, or None to use the default. dist (int): The distribution mode to use. Should be DISTRIBUTION_*. """ lib.TCOD_random_set_distribution(rnd.random_c if rnd else ffi.NULL, dist)
python
def random_set_distribution( rnd: Optional[tcod.random.Random], dist: int ) -> None: """Change the distribution mode of a random number generator. Args: rnd (Optional[Random]): A Random instance, or None to use the default. dist (int): The distribution mode to use. Should be DISTRIBUTION_*. """ lib.TCOD_random_set_distribution(rnd.random_c if rnd else ffi.NULL, dist)
[ "def", "random_set_distribution", "(", "rnd", ":", "Optional", "[", "tcod", ".", "random", ".", "Random", "]", ",", "dist", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_random_set_distribution", "(", "rnd", ".", "random_c", "if", "rnd", "else", "ffi", ".", "NULL", ",", "dist", ")" ]
Change the distribution mode of a random number generator. Args: rnd (Optional[Random]): A Random instance, or None to use the default. dist (int): The distribution mode to use. Should be DISTRIBUTION_*.
[ "Change", "the", "distribution", "mode", "of", "a", "random", "number", "generator", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3677-L3686
train
libtcod/python-tcod
tcod/libtcodpy.py
random_save
def random_save(rnd: Optional[tcod.random.Random]) -> tcod.random.Random: """Return a copy of a random number generator. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state. """ return tcod.random.Random._new_from_cdata( ffi.gc( ffi.cast( "mersenne_data_t*", lib.TCOD_random_save(rnd.random_c if rnd else ffi.NULL), ), lib.TCOD_random_delete, ) )
python
def random_save(rnd: Optional[tcod.random.Random]) -> tcod.random.Random: """Return a copy of a random number generator. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state. """ return tcod.random.Random._new_from_cdata( ffi.gc( ffi.cast( "mersenne_data_t*", lib.TCOD_random_save(rnd.random_c if rnd else ffi.NULL), ), lib.TCOD_random_delete, ) )
[ "def", "random_save", "(", "rnd", ":", "Optional", "[", "tcod", ".", "random", ".", "Random", "]", ")", "->", "tcod", ".", "random", ".", "Random", ":", "return", "tcod", ".", "random", ".", "Random", ".", "_new_from_cdata", "(", "ffi", ".", "gc", "(", "ffi", ".", "cast", "(", "\"mersenne_data_t*\"", ",", "lib", ".", "TCOD_random_save", "(", "rnd", ".", "random_c", "if", "rnd", "else", "ffi", ".", "NULL", ")", ",", ")", ",", "lib", ".", "TCOD_random_delete", ",", ")", ")" ]
Return a copy of a random number generator. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state.
[ "Return", "a", "copy", "of", "a", "random", "number", "generator", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3812-L3827
train
libtcod/python-tcod
tcod/libtcodpy.py
random_restore
def random_restore( rnd: Optional[tcod.random.Random], backup: tcod.random.Random ) -> None: """Restore a random number generator from a backed up copy. Args: rnd (Optional[Random]): A Random instance, or None to use the default. backup (Random): The Random instance which was used as a backup. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state. """ lib.TCOD_random_restore(rnd.random_c if rnd else ffi.NULL, backup.random_c)
python
def random_restore( rnd: Optional[tcod.random.Random], backup: tcod.random.Random ) -> None: """Restore a random number generator from a backed up copy. Args: rnd (Optional[Random]): A Random instance, or None to use the default. backup (Random): The Random instance which was used as a backup. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state. """ lib.TCOD_random_restore(rnd.random_c if rnd else ffi.NULL, backup.random_c)
[ "def", "random_restore", "(", "rnd", ":", "Optional", "[", "tcod", ".", "random", ".", "Random", "]", ",", "backup", ":", "tcod", ".", "random", ".", "Random", ")", "->", "None", ":", "lib", ".", "TCOD_random_restore", "(", "rnd", ".", "random_c", "if", "rnd", "else", "ffi", ".", "NULL", ",", "backup", ".", "random_c", ")" ]
Restore a random number generator from a backed up copy. Args: rnd (Optional[Random]): A Random instance, or None to use the default. backup (Random): The Random instance which was used as a backup. .. deprecated:: 8.4 You can use the standard library copy and pickle modules to save a random state.
[ "Restore", "a", "random", "number", "generator", "from", "a", "backed", "up", "copy", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3831-L3844
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_set_renderer
def sys_set_renderer(renderer: int) -> None: """Change the current rendering mode to renderer. .. deprecated:: 2.0 RENDERER_GLSL and RENDERER_OPENGL are not currently available. """ lib.TCOD_sys_set_renderer(renderer) if tcod.console._root_console is not None: tcod.console.Console._get_root()
python
def sys_set_renderer(renderer: int) -> None: """Change the current rendering mode to renderer. .. deprecated:: 2.0 RENDERER_GLSL and RENDERER_OPENGL are not currently available. """ lib.TCOD_sys_set_renderer(renderer) if tcod.console._root_console is not None: tcod.console.Console._get_root()
[ "def", "sys_set_renderer", "(", "renderer", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_sys_set_renderer", "(", "renderer", ")", "if", "tcod", ".", "console", ".", "_root_console", "is", "not", "None", ":", "tcod", ".", "console", ".", "Console", ".", "_get_root", "(", ")" ]
Change the current rendering mode to renderer. .. deprecated:: 2.0 RENDERER_GLSL and RENDERER_OPENGL are not currently available.
[ "Change", "the", "current", "rendering", "mode", "to", "renderer", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3973-L3981
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_save_screenshot
def sys_save_screenshot(name: Optional[str] = None) -> None: """Save a screenshot to a file. By default this will automatically save screenshots in the working directory. The automatic names are formatted as screenshotNNN.png. For example: screenshot000.png, screenshot001.png, etc. Whichever is available first. Args: file Optional[AnyStr]: File path to save screenshot. """ lib.TCOD_sys_save_screenshot( _bytes(name) if name is not None else ffi.NULL )
python
def sys_save_screenshot(name: Optional[str] = None) -> None: """Save a screenshot to a file. By default this will automatically save screenshots in the working directory. The automatic names are formatted as screenshotNNN.png. For example: screenshot000.png, screenshot001.png, etc. Whichever is available first. Args: file Optional[AnyStr]: File path to save screenshot. """ lib.TCOD_sys_save_screenshot( _bytes(name) if name is not None else ffi.NULL )
[ "def", "sys_save_screenshot", "(", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "lib", ".", "TCOD_sys_save_screenshot", "(", "_bytes", "(", "name", ")", "if", "name", "is", "not", "None", "else", "ffi", ".", "NULL", ")" ]
Save a screenshot to a file. By default this will automatically save screenshots in the working directory. The automatic names are formatted as screenshotNNN.png. For example: screenshot000.png, screenshot001.png, etc. Whichever is available first. Args: file Optional[AnyStr]: File path to save screenshot.
[ "Save", "a", "screenshot", "to", "a", "file", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3992-L4006
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_update_char
def sys_update_char( asciiCode: int, fontx: int, fonty: int, img: tcod.image.Image, x: int, y: int, ) -> None: """Dynamically update the current font with img. All cells using this asciiCode will be updated at the next call to :any:`tcod.console_flush`. Args: asciiCode (int): Ascii code corresponding to the character to update. fontx (int): Left coordinate of the character in the bitmap font (in tiles) fonty (int): Top coordinate of the character in the bitmap font (in tiles) img (Image): An image containing the new character bitmap. x (int): Left pixel of the character in the image. y (int): Top pixel of the character in the image. """ lib.TCOD_sys_update_char(_int(asciiCode), fontx, fonty, img, x, y)
python
def sys_update_char( asciiCode: int, fontx: int, fonty: int, img: tcod.image.Image, x: int, y: int, ) -> None: """Dynamically update the current font with img. All cells using this asciiCode will be updated at the next call to :any:`tcod.console_flush`. Args: asciiCode (int): Ascii code corresponding to the character to update. fontx (int): Left coordinate of the character in the bitmap font (in tiles) fonty (int): Top coordinate of the character in the bitmap font (in tiles) img (Image): An image containing the new character bitmap. x (int): Left pixel of the character in the image. y (int): Top pixel of the character in the image. """ lib.TCOD_sys_update_char(_int(asciiCode), fontx, fonty, img, x, y)
[ "def", "sys_update_char", "(", "asciiCode", ":", "int", ",", "fontx", ":", "int", ",", "fonty", ":", "int", ",", "img", ":", "tcod", ".", "image", ".", "Image", ",", "x", ":", "int", ",", "y", ":", "int", ",", ")", "->", "None", ":", "lib", ".", "TCOD_sys_update_char", "(", "_int", "(", "asciiCode", ")", ",", "fontx", ",", "fonty", ",", "img", ",", "x", ",", "y", ")" ]
Dynamically update the current font with img. All cells using this asciiCode will be updated at the next call to :any:`tcod.console_flush`. Args: asciiCode (int): Ascii code corresponding to the character to update. fontx (int): Left coordinate of the character in the bitmap font (in tiles) fonty (int): Top coordinate of the character in the bitmap font (in tiles) img (Image): An image containing the new character bitmap. x (int): Left pixel of the character in the image. y (int): Top pixel of the character in the image.
[ "Dynamically", "update", "the", "current", "font", "with", "img", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L4054-L4077
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_register_SDL_renderer
def sys_register_SDL_renderer(callback: Callable[[Any], None]) -> None: """Register a custom randering function with libtcod. Note: This callback will only be called by the SDL renderer. The callack will receive a :any:`CData <ffi-cdata>` void* to an SDL_Surface* struct. The callback is called on every call to :any:`tcod.console_flush`. Args: callback Callable[[CData], None]: A function which takes a single argument. """ with _PropagateException() as propagate: @ffi.def_extern(onerror=propagate) # type: ignore def _pycall_sdl_hook(sdl_surface: Any) -> None: callback(sdl_surface) lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook)
python
def sys_register_SDL_renderer(callback: Callable[[Any], None]) -> None: """Register a custom randering function with libtcod. Note: This callback will only be called by the SDL renderer. The callack will receive a :any:`CData <ffi-cdata>` void* to an SDL_Surface* struct. The callback is called on every call to :any:`tcod.console_flush`. Args: callback Callable[[CData], None]: A function which takes a single argument. """ with _PropagateException() as propagate: @ffi.def_extern(onerror=propagate) # type: ignore def _pycall_sdl_hook(sdl_surface: Any) -> None: callback(sdl_surface) lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook)
[ "def", "sys_register_SDL_renderer", "(", "callback", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", ")", "->", "None", ":", "with", "_PropagateException", "(", ")", "as", "propagate", ":", "@", "ffi", ".", "def_extern", "(", "onerror", "=", "propagate", ")", "# type: ignore", "def", "_pycall_sdl_hook", "(", "sdl_surface", ":", "Any", ")", "->", "None", ":", "callback", "(", "sdl_surface", ")", "lib", ".", "TCOD_sys_register_SDL_renderer", "(", "lib", ".", "_pycall_sdl_hook", ")" ]
Register a custom randering function with libtcod. Note: This callback will only be called by the SDL renderer. The callack will receive a :any:`CData <ffi-cdata>` void* to an SDL_Surface* struct. The callback is called on every call to :any:`tcod.console_flush`. Args: callback Callable[[CData], None]: A function which takes a single argument.
[ "Register", "a", "custom", "randering", "function", "with", "libtcod", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L4081-L4102
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_check_for_event
def sys_check_for_event( mask: int, k: Optional[Key], m: Optional[Mouse] ) -> int: """Check for and return an event. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. .. deprecated:: 9.3 Use the :any:`tcod.event.get` function to check for events. """ return int( lib.TCOD_sys_check_for_event( mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL ) )
python
def sys_check_for_event( mask: int, k: Optional[Key], m: Optional[Mouse] ) -> int: """Check for and return an event. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. .. deprecated:: 9.3 Use the :any:`tcod.event.get` function to check for events. """ return int( lib.TCOD_sys_check_for_event( mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL ) )
[ "def", "sys_check_for_event", "(", "mask", ":", "int", ",", "k", ":", "Optional", "[", "Key", "]", ",", "m", ":", "Optional", "[", "Mouse", "]", ")", "->", "int", ":", "return", "int", "(", "lib", ".", "TCOD_sys_check_for_event", "(", "mask", ",", "k", ".", "key_p", "if", "k", "else", "ffi", ".", "NULL", ",", "m", ".", "mouse_p", "if", "m", "else", "ffi", ".", "NULL", ")", ")" ]
Check for and return an event. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. .. deprecated:: 9.3 Use the :any:`tcod.event.get` function to check for events.
[ "Check", "for", "and", "return", "an", "event", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L4106-L4125
train
libtcod/python-tcod
tcod/libtcodpy.py
sys_wait_for_event
def sys_wait_for_event( mask: int, k: Optional[Key], m: Optional[Mouse], flush: bool ) -> int: """Wait for an event then return. If flush is True then the buffer will be cleared before waiting. Otherwise each available event will be returned in the order they're recieved. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. flush (bool): Clear the event buffer before waiting. .. deprecated:: 9.3 Use the :any:`tcod.event.wait` function to wait for events. """ return int( lib.TCOD_sys_wait_for_event( mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL, flush, ) )
python
def sys_wait_for_event( mask: int, k: Optional[Key], m: Optional[Mouse], flush: bool ) -> int: """Wait for an event then return. If flush is True then the buffer will be cleared before waiting. Otherwise each available event will be returned in the order they're recieved. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. flush (bool): Clear the event buffer before waiting. .. deprecated:: 9.3 Use the :any:`tcod.event.wait` function to wait for events. """ return int( lib.TCOD_sys_wait_for_event( mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL, flush, ) )
[ "def", "sys_wait_for_event", "(", "mask", ":", "int", ",", "k", ":", "Optional", "[", "Key", "]", ",", "m", ":", "Optional", "[", "Mouse", "]", ",", "flush", ":", "bool", ")", "->", "int", ":", "return", "int", "(", "lib", ".", "TCOD_sys_wait_for_event", "(", "mask", ",", "k", ".", "key_p", "if", "k", "else", "ffi", ".", "NULL", ",", "m", ".", "mouse_p", "if", "m", "else", "ffi", ".", "NULL", ",", "flush", ",", ")", ")" ]
Wait for an event then return. If flush is True then the buffer will be cleared before waiting. Otherwise each available event will be returned in the order they're recieved. Args: mask (int): :any:`Event types` to wait for. k (Optional[Key]): A tcod.Key instance which might be updated with an event. Can be None. m (Optional[Mouse]): A tcod.Mouse instance which might be updated with an event. Can be None. flush (bool): Clear the event buffer before waiting. .. deprecated:: 9.3 Use the :any:`tcod.event.wait` function to wait for events.
[ "Wait", "for", "an", "event", "then", "return", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L4129-L4155
train
libtcod/python-tcod
tcod/libtcodpy.py
_atexit_verify
def _atexit_verify() -> None: """Warns if the libtcod root console is implicitly deleted.""" if lib.TCOD_ctx.root: warnings.warn( "The libtcod root console was implicitly deleted.\n" "Make sure the 'with' statement is used with the root console to" " ensure that it closes properly.", ResourceWarning, stacklevel=2, ) lib.TCOD_console_delete(ffi.NULL)
python
def _atexit_verify() -> None: """Warns if the libtcod root console is implicitly deleted.""" if lib.TCOD_ctx.root: warnings.warn( "The libtcod root console was implicitly deleted.\n" "Make sure the 'with' statement is used with the root console to" " ensure that it closes properly.", ResourceWarning, stacklevel=2, ) lib.TCOD_console_delete(ffi.NULL)
[ "def", "_atexit_verify", "(", ")", "->", "None", ":", "if", "lib", ".", "TCOD_ctx", ".", "root", ":", "warnings", ".", "warn", "(", "\"The libtcod root console was implicitly deleted.\\n\"", "\"Make sure the 'with' statement is used with the root console to\"", "\" ensure that it closes properly.\"", ",", "ResourceWarning", ",", "stacklevel", "=", "2", ",", ")", "lib", ".", "TCOD_console_delete", "(", "ffi", ".", "NULL", ")" ]
Warns if the libtcod root console is implicitly deleted.
[ "Warns", "if", "the", "libtcod", "root", "console", "is", "implicitly", "deleted", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L4179-L4189
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.clear
def clear( self, back_r: int = 0, back_g: int = 0, back_b: int = 0, fore_r: int = 0, fore_g: int = 0, fore_b: int = 0, char: str = " ", ) -> None: """Clears the console. Values to fill it with are optional, defaults to black with no characters. Args: back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ n = self.width * self.height self.back_r = [back_r] * n self.back_g = [back_g] * n self.back_b = [back_b] * n self.fore_r = [fore_r] * n self.fore_g = [fore_g] * n self.fore_b = [fore_b] * n self.char = [ord(char)] * n
python
def clear( self, back_r: int = 0, back_g: int = 0, back_b: int = 0, fore_r: int = 0, fore_g: int = 0, fore_b: int = 0, char: str = " ", ) -> None: """Clears the console. Values to fill it with are optional, defaults to black with no characters. Args: back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ n = self.width * self.height self.back_r = [back_r] * n self.back_g = [back_g] * n self.back_b = [back_b] * n self.fore_r = [fore_r] * n self.fore_g = [fore_g] * n self.fore_b = [fore_b] * n self.char = [ord(char)] * n
[ "def", "clear", "(", "self", ",", "back_r", ":", "int", "=", "0", ",", "back_g", ":", "int", "=", "0", ",", "back_b", ":", "int", "=", "0", ",", "fore_r", ":", "int", "=", "0", ",", "fore_g", ":", "int", "=", "0", ",", "fore_b", ":", "int", "=", "0", ",", "char", ":", "str", "=", "\" \"", ",", ")", "->", "None", ":", "n", "=", "self", ".", "width", "*", "self", ".", "height", "self", ".", "back_r", "=", "[", "back_r", "]", "*", "n", "self", ".", "back_g", "=", "[", "back_g", "]", "*", "n", "self", ".", "back_b", "=", "[", "back_b", "]", "*", "n", "self", ".", "fore_r", "=", "[", "fore_r", "]", "*", "n", "self", ".", "fore_g", "=", "[", "fore_g", "]", "*", "n", "self", ".", "fore_b", "=", "[", "fore_b", "]", "*", "n", "self", ".", "char", "=", "[", "ord", "(", "char", ")", "]", "*", "n" ]
Clears the console. Values to fill it with are optional, defaults to black with no characters. Args: back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object.
[ "Clears", "the", "console", ".", "Values", "to", "fill", "it", "with", "are", "optional", "defaults", "to", "black", "with", "no", "characters", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L120-L149
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.copy
def copy(self) -> "ConsoleBuffer": """Returns a copy of this ConsoleBuffer. Returns: ConsoleBuffer: A new ConsoleBuffer copy. """ other = ConsoleBuffer(0, 0) # type: "ConsoleBuffer" other.width = self.width other.height = self.height other.back_r = list(self.back_r) # make explicit copies of all lists other.back_g = list(self.back_g) other.back_b = list(self.back_b) other.fore_r = list(self.fore_r) other.fore_g = list(self.fore_g) other.fore_b = list(self.fore_b) other.char = list(self.char) return other
python
def copy(self) -> "ConsoleBuffer": """Returns a copy of this ConsoleBuffer. Returns: ConsoleBuffer: A new ConsoleBuffer copy. """ other = ConsoleBuffer(0, 0) # type: "ConsoleBuffer" other.width = self.width other.height = self.height other.back_r = list(self.back_r) # make explicit copies of all lists other.back_g = list(self.back_g) other.back_b = list(self.back_b) other.fore_r = list(self.fore_r) other.fore_g = list(self.fore_g) other.fore_b = list(self.fore_b) other.char = list(self.char) return other
[ "def", "copy", "(", "self", ")", "->", "\"ConsoleBuffer\"", ":", "other", "=", "ConsoleBuffer", "(", "0", ",", "0", ")", "# type: \"ConsoleBuffer\"", "other", ".", "width", "=", "self", ".", "width", "other", ".", "height", "=", "self", ".", "height", "other", ".", "back_r", "=", "list", "(", "self", ".", "back_r", ")", "# make explicit copies of all lists", "other", ".", "back_g", "=", "list", "(", "self", ".", "back_g", ")", "other", ".", "back_b", "=", "list", "(", "self", ".", "back_b", ")", "other", ".", "fore_r", "=", "list", "(", "self", ".", "fore_r", ")", "other", ".", "fore_g", "=", "list", "(", "self", ".", "fore_g", ")", "other", ".", "fore_b", "=", "list", "(", "self", ".", "fore_b", ")", "other", ".", "char", "=", "list", "(", "self", ".", "char", ")", "return", "other" ]
Returns a copy of this ConsoleBuffer. Returns: ConsoleBuffer: A new ConsoleBuffer copy.
[ "Returns", "a", "copy", "of", "this", "ConsoleBuffer", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L151-L167
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.set_fore
def set_fore( self, x: int, y: int, r: int, g: int, b: int, char: str ) -> None: """Set the character and foreground color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red foreground color, from 0 to 255. g (int): Green foreground color, from 0 to 255. b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ i = self.width * y + x self.fore_r[i] = r self.fore_g[i] = g self.fore_b[i] = b self.char[i] = ord(char)
python
def set_fore( self, x: int, y: int, r: int, g: int, b: int, char: str ) -> None: """Set the character and foreground color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red foreground color, from 0 to 255. g (int): Green foreground color, from 0 to 255. b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ i = self.width * y + x self.fore_r[i] = r self.fore_g[i] = g self.fore_b[i] = b self.char[i] = ord(char)
[ "def", "set_fore", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "r", ":", "int", ",", "g", ":", "int", ",", "b", ":", "int", ",", "char", ":", "str", ")", "->", "None", ":", "i", "=", "self", ".", "width", "*", "y", "+", "x", "self", ".", "fore_r", "[", "i", "]", "=", "r", "self", ".", "fore_g", "[", "i", "]", "=", "g", "self", ".", "fore_b", "[", "i", "]", "=", "b", "self", ".", "char", "[", "i", "]", "=", "ord", "(", "char", ")" ]
Set the character and foreground color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red foreground color, from 0 to 255. g (int): Green foreground color, from 0 to 255. b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object.
[ "Set", "the", "character", "and", "foreground", "color", "of", "one", "cell", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L169-L186
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.set_back
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None: """Set the background color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red background color, from 0 to 255. g (int): Green background color, from 0 to 255. b (int): Blue background color, from 0 to 255. """ i = self.width * y + x self.back_r[i] = r self.back_g[i] = g self.back_b[i] = b
python
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None: """Set the background color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red background color, from 0 to 255. g (int): Green background color, from 0 to 255. b (int): Blue background color, from 0 to 255. """ i = self.width * y + x self.back_r[i] = r self.back_g[i] = g self.back_b[i] = b
[ "def", "set_back", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "r", ":", "int", ",", "g", ":", "int", ",", "b", ":", "int", ")", "->", "None", ":", "i", "=", "self", ".", "width", "*", "y", "+", "x", "self", ".", "back_r", "[", "i", "]", "=", "r", "self", ".", "back_g", "[", "i", "]", "=", "g", "self", ".", "back_b", "[", "i", "]", "=", "b" ]
Set the background color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red background color, from 0 to 255. g (int): Green background color, from 0 to 255. b (int): Blue background color, from 0 to 255.
[ "Set", "the", "background", "color", "of", "one", "cell", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L188-L201
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.set
def set( self, x: int, y: int, back_r: int, back_g: int, back_b: int, fore_r: int, fore_g: int, fore_b: int, char: str, ) -> None: """Set the background color, foreground color and character of one cell. Args: x (int): X position to change. y (int): Y position to change. back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ i = self.width * y + x self.back_r[i] = back_r self.back_g[i] = back_g self.back_b[i] = back_b self.fore_r[i] = fore_r self.fore_g[i] = fore_g self.fore_b[i] = fore_b self.char[i] = ord(char)
python
def set( self, x: int, y: int, back_r: int, back_g: int, back_b: int, fore_r: int, fore_g: int, fore_b: int, char: str, ) -> None: """Set the background color, foreground color and character of one cell. Args: x (int): X position to change. y (int): Y position to change. back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object. """ i = self.width * y + x self.back_r[i] = back_r self.back_g[i] = back_g self.back_b[i] = back_b self.fore_r[i] = fore_r self.fore_g[i] = fore_g self.fore_b[i] = fore_b self.char[i] = ord(char)
[ "def", "set", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "back_r", ":", "int", ",", "back_g", ":", "int", ",", "back_b", ":", "int", ",", "fore_r", ":", "int", ",", "fore_g", ":", "int", ",", "fore_b", ":", "int", ",", "char", ":", "str", ",", ")", "->", "None", ":", "i", "=", "self", ".", "width", "*", "y", "+", "x", "self", ".", "back_r", "[", "i", "]", "=", "back_r", "self", ".", "back_g", "[", "i", "]", "=", "back_g", "self", ".", "back_b", "[", "i", "]", "=", "back_b", "self", ".", "fore_r", "[", "i", "]", "=", "fore_r", "self", ".", "fore_g", "[", "i", "]", "=", "fore_g", "self", ".", "fore_b", "[", "i", "]", "=", "fore_b", "self", ".", "char", "[", "i", "]", "=", "ord", "(", "char", ")" ]
Set the background color, foreground color and character of one cell. Args: x (int): X position to change. y (int): Y position to change. back_r (int): Red background color, from 0 to 255. back_g (int): Green background color, from 0 to 255. back_b (int): Blue background color, from 0 to 255. fore_r (int): Red foreground color, from 0 to 255. fore_g (int): Green foreground color, from 0 to 255. fore_b (int): Blue foreground color, from 0 to 255. char (AnyStr): A single character str or bytes object.
[ "Set", "the", "background", "color", "foreground", "color", "and", "character", "of", "one", "cell", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L203-L235
train
libtcod/python-tcod
tcod/libtcodpy.py
ConsoleBuffer.blit
def blit( self, dest: tcod.console.Console, fill_fore: bool = True, fill_back: bool = True, ) -> None: """Use libtcod's "fill" functions to write the buffer to a console. Args: dest (Console): Console object to modify. fill_fore (bool): If True, fill the foreground color and characters. fill_back (bool): If True, fill the background color. """ if not dest: dest = tcod.console.Console._from_cdata(ffi.NULL) if dest.width != self.width or dest.height != self.height: raise ValueError( "ConsoleBuffer.blit: " "Destination console has an incorrect size." ) if fill_back: bg = dest.bg.ravel() bg[0::3] = self.back_r bg[1::3] = self.back_g bg[2::3] = self.back_b if fill_fore: fg = dest.fg.ravel() fg[0::3] = self.fore_r fg[1::3] = self.fore_g fg[2::3] = self.fore_b dest.ch.ravel()[:] = self.char
python
def blit( self, dest: tcod.console.Console, fill_fore: bool = True, fill_back: bool = True, ) -> None: """Use libtcod's "fill" functions to write the buffer to a console. Args: dest (Console): Console object to modify. fill_fore (bool): If True, fill the foreground color and characters. fill_back (bool): If True, fill the background color. """ if not dest: dest = tcod.console.Console._from_cdata(ffi.NULL) if dest.width != self.width or dest.height != self.height: raise ValueError( "ConsoleBuffer.blit: " "Destination console has an incorrect size." ) if fill_back: bg = dest.bg.ravel() bg[0::3] = self.back_r bg[1::3] = self.back_g bg[2::3] = self.back_b if fill_fore: fg = dest.fg.ravel() fg[0::3] = self.fore_r fg[1::3] = self.fore_g fg[2::3] = self.fore_b dest.ch.ravel()[:] = self.char
[ "def", "blit", "(", "self", ",", "dest", ":", "tcod", ".", "console", ".", "Console", ",", "fill_fore", ":", "bool", "=", "True", ",", "fill_back", ":", "bool", "=", "True", ",", ")", "->", "None", ":", "if", "not", "dest", ":", "dest", "=", "tcod", ".", "console", ".", "Console", ".", "_from_cdata", "(", "ffi", ".", "NULL", ")", "if", "dest", ".", "width", "!=", "self", ".", "width", "or", "dest", ".", "height", "!=", "self", ".", "height", ":", "raise", "ValueError", "(", "\"ConsoleBuffer.blit: \"", "\"Destination console has an incorrect size.\"", ")", "if", "fill_back", ":", "bg", "=", "dest", ".", "bg", ".", "ravel", "(", ")", "bg", "[", "0", ":", ":", "3", "]", "=", "self", ".", "back_r", "bg", "[", "1", ":", ":", "3", "]", "=", "self", ".", "back_g", "bg", "[", "2", ":", ":", "3", "]", "=", "self", ".", "back_b", "if", "fill_fore", ":", "fg", "=", "dest", ".", "fg", ".", "ravel", "(", ")", "fg", "[", "0", ":", ":", "3", "]", "=", "self", ".", "fore_r", "fg", "[", "1", ":", ":", "3", "]", "=", "self", ".", "fore_g", "fg", "[", "2", ":", ":", "3", "]", "=", "self", ".", "fore_b", "dest", ".", "ch", ".", "ravel", "(", ")", "[", ":", "]", "=", "self", ".", "char" ]
Use libtcod's "fill" functions to write the buffer to a console. Args: dest (Console): Console object to modify. fill_fore (bool): If True, fill the foreground color and characters. fill_back (bool): If True, fill the background color.
[ "Use", "libtcod", "s", "fill", "functions", "to", "write", "the", "buffer", "to", "a", "console", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L237-L271
train
libtcod/python-tcod
tcod/image.py
Image.clear
def clear(self, color: Tuple[int, int, int]) -> None: """Fill this entire Image with color. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_clear(self.image_c, color)
python
def clear(self, color: Tuple[int, int, int]) -> None: """Fill this entire Image with color. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_clear(self.image_c, color)
[ "def", "clear", "(", "self", ",", "color", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_image_clear", "(", "self", ".", "image_c", ",", "color", ")" ]
Fill this entire Image with color. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
[ "Fill", "this", "entire", "Image", "with", "color", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L59-L66
train
libtcod/python-tcod
tcod/image.py
Image.scale
def scale(self, width: int, height: int) -> None: """Scale this Image to the new width and height. Args: width (int): The new width of the Image after scaling. height (int): The new height of the Image after scaling. """ lib.TCOD_image_scale(self.image_c, width, height) self.width, self.height = width, height
python
def scale(self, width: int, height: int) -> None: """Scale this Image to the new width and height. Args: width (int): The new width of the Image after scaling. height (int): The new height of the Image after scaling. """ lib.TCOD_image_scale(self.image_c, width, height) self.width, self.height = width, height
[ "def", "scale", "(", "self", ",", "width", ":", "int", ",", "height", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_image_scale", "(", "self", ".", "image_c", ",", "width", ",", "height", ")", "self", ".", "width", ",", "self", ".", "height", "=", "width", ",", "height" ]
Scale this Image to the new width and height. Args: width (int): The new width of the Image after scaling. height (int): The new height of the Image after scaling.
[ "Scale", "this", "Image", "to", "the", "new", "width", "and", "height", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L88-L96
train
libtcod/python-tcod
tcod/image.py
Image.set_key_color
def set_key_color(self, color: Tuple[int, int, int]) -> None: """Set a color to be transparent during blitting functions. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_set_key_color(self.image_c, color)
python
def set_key_color(self, color: Tuple[int, int, int]) -> None: """Set a color to be transparent during blitting functions. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_set_key_color(self.image_c, color)
[ "def", "set_key_color", "(", "self", ",", "color", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_image_set_key_color", "(", "self", ".", "image_c", ",", "color", ")" ]
Set a color to be transparent during blitting functions. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
[ "Set", "a", "color", "to", "be", "transparent", "during", "blitting", "functions", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L98-L105
train
libtcod/python-tcod
tcod/image.py
Image.get_alpha
def get_alpha(self, x: int, y: int) -> int: """Get the Image alpha of the pixel at x, y. Args: x (int): X pixel of the image. Starting from the left at 0. y (int): Y pixel of the image. Starting from the top at 0. Returns: int: The alpha value of the pixel. With 0 being fully transparent and 255 being fully opaque. """ return lib.TCOD_image_get_alpha(self.image_c, x, y)
python
def get_alpha(self, x: int, y: int) -> int: """Get the Image alpha of the pixel at x, y. Args: x (int): X pixel of the image. Starting from the left at 0. y (int): Y pixel of the image. Starting from the top at 0. Returns: int: The alpha value of the pixel. With 0 being fully transparent and 255 being fully opaque. """ return lib.TCOD_image_get_alpha(self.image_c, x, y)
[ "def", "get_alpha", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "lib", ".", "TCOD_image_get_alpha", "(", "self", ".", "image_c", ",", "x", ",", "y", ")" ]
Get the Image alpha of the pixel at x, y. Args: x (int): X pixel of the image. Starting from the left at 0. y (int): Y pixel of the image. Starting from the top at 0. Returns: int: The alpha value of the pixel. With 0 being fully transparent and 255 being fully opaque.
[ "Get", "the", "Image", "alpha", "of", "the", "pixel", "at", "x", "y", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L107-L118
train
libtcod/python-tcod
tcod/image.py
Image.get_pixel
def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]: """Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the pixels color value. Values are in a 0 to 255 range. """ color = lib.TCOD_image_get_pixel(self.image_c, x, y) return color.r, color.g, color.b
python
def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]: """Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the pixels color value. Values are in a 0 to 255 range. """ color = lib.TCOD_image_get_pixel(self.image_c, x, y) return color.r, color.g, color.b
[ "def", "get_pixel", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", "]", ":", "color", "=", "lib", ".", "TCOD_image_get_pixel", "(", "self", ".", "image_c", ",", "x", ",", "y", ")", "return", "color", ".", "r", ",", "color", ".", "g", ",", "color", ".", "b" ]
Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the pixels color value. Values are in a 0 to 255 range.
[ "Get", "the", "color", "of", "a", "pixel", "in", "this", "Image", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L145-L158
train
libtcod/python-tcod
tcod/image.py
Image.get_mipmap_pixel
def get_mipmap_pixel( self, left: float, top: float, right: float, bottom: float ) -> Tuple[int, int, int]: """Get the average color of a rectangle in this Image. Parameters should stay within the following limits: * 0 <= left < right < Image.width * 0 <= top < bottom < Image.height Args: left (float): Left corner of the region. top (float): Top corner of the region. right (float): Right corner of the region. bottom (float): Bottom corner of the region. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the averaged color value. Values are in a 0 to 255 range. """ color = lib.TCOD_image_get_mipmap_pixel( self.image_c, left, top, right, bottom ) return (color.r, color.g, color.b)
python
def get_mipmap_pixel( self, left: float, top: float, right: float, bottom: float ) -> Tuple[int, int, int]: """Get the average color of a rectangle in this Image. Parameters should stay within the following limits: * 0 <= left < right < Image.width * 0 <= top < bottom < Image.height Args: left (float): Left corner of the region. top (float): Top corner of the region. right (float): Right corner of the region. bottom (float): Bottom corner of the region. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the averaged color value. Values are in a 0 to 255 range. """ color = lib.TCOD_image_get_mipmap_pixel( self.image_c, left, top, right, bottom ) return (color.r, color.g, color.b)
[ "def", "get_mipmap_pixel", "(", "self", ",", "left", ":", "float", ",", "top", ":", "float", ",", "right", ":", "float", ",", "bottom", ":", "float", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", "]", ":", "color", "=", "lib", ".", "TCOD_image_get_mipmap_pixel", "(", "self", ".", "image_c", ",", "left", ",", "top", ",", "right", ",", "bottom", ")", "return", "(", "color", ".", "r", ",", "color", ".", "g", ",", "color", ".", "b", ")" ]
Get the average color of a rectangle in this Image. Parameters should stay within the following limits: * 0 <= left < right < Image.width * 0 <= top < bottom < Image.height Args: left (float): Left corner of the region. top (float): Top corner of the region. right (float): Right corner of the region. bottom (float): Bottom corner of the region. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the averaged color value. Values are in a 0 to 255 range.
[ "Get", "the", "average", "color", "of", "a", "rectangle", "in", "this", "Image", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L160-L183
train
libtcod/python-tcod
tcod/image.py
Image.put_pixel
def put_pixel(self, x: int, y: int, color: Tuple[int, int, int]) -> None: """Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_put_pixel(self.image_c, x, y, color)
python
def put_pixel(self, x: int, y: int, color: Tuple[int, int, int]) -> None: """Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. """ lib.TCOD_image_put_pixel(self.image_c, x, y, color)
[ "def", "put_pixel", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "color", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_image_put_pixel", "(", "self", ".", "image_c", ",", "x", ",", "y", ",", "color", ")" ]
Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
[ "Change", "a", "pixel", "on", "this", "Image", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L185-L194
train
libtcod/python-tcod
tcod/image.py
Image.blit
def blit( self, console: tcod.console.Console, x: float, y: float, bg_blend: int, scale_x: float, scale_y: float, angle: float, ) -> None: """Blit onto a Console using scaling and rotation. Args: console (Console): Blit destination Console. x (float): Console X position for the center of the Image blit. y (float): Console Y position for the center of the Image blit. The Image blit is centered on this position. bg_blend (int): Background blending mode to use. scale_x (float): Scaling along Image x axis. Set to 1 for no scaling. Must be over 0. scale_y (float): Scaling along Image y axis. Set to 1 for no scaling. Must be over 0. angle (float): Rotation angle in radians. (Clockwise?) """ lib.TCOD_image_blit( self.image_c, _console(console), x, y, bg_blend, scale_x, scale_y, angle, )
python
def blit( self, console: tcod.console.Console, x: float, y: float, bg_blend: int, scale_x: float, scale_y: float, angle: float, ) -> None: """Blit onto a Console using scaling and rotation. Args: console (Console): Blit destination Console. x (float): Console X position for the center of the Image blit. y (float): Console Y position for the center of the Image blit. The Image blit is centered on this position. bg_blend (int): Background blending mode to use. scale_x (float): Scaling along Image x axis. Set to 1 for no scaling. Must be over 0. scale_y (float): Scaling along Image y axis. Set to 1 for no scaling. Must be over 0. angle (float): Rotation angle in radians. (Clockwise?) """ lib.TCOD_image_blit( self.image_c, _console(console), x, y, bg_blend, scale_x, scale_y, angle, )
[ "def", "blit", "(", "self", ",", "console", ":", "tcod", ".", "console", ".", "Console", ",", "x", ":", "float", ",", "y", ":", "float", ",", "bg_blend", ":", "int", ",", "scale_x", ":", "float", ",", "scale_y", ":", "float", ",", "angle", ":", "float", ",", ")", "->", "None", ":", "lib", ".", "TCOD_image_blit", "(", "self", ".", "image_c", ",", "_console", "(", "console", ")", ",", "x", ",", "y", ",", "bg_blend", ",", "scale_x", ",", "scale_y", ",", "angle", ",", ")" ]
Blit onto a Console using scaling and rotation. Args: console (Console): Blit destination Console. x (float): Console X position for the center of the Image blit. y (float): Console Y position for the center of the Image blit. The Image blit is centered on this position. bg_blend (int): Background blending mode to use. scale_x (float): Scaling along Image x axis. Set to 1 for no scaling. Must be over 0. scale_y (float): Scaling along Image y axis. Set to 1 for no scaling. Must be over 0. angle (float): Rotation angle in radians. (Clockwise?)
[ "Blit", "onto", "a", "Console", "using", "scaling", "and", "rotation", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L196-L229
train
libtcod/python-tcod
tcod/image.py
Image.blit_rect
def blit_rect( self, console: tcod.console.Console, x: int, y: int, width: int, height: int, bg_blend: int, ) -> None: """Blit onto a Console without scaling or rotation. Args: console (Console): Blit destination Console. x (int): Console tile X position starting from the left at 0. y (int): Console tile Y position starting from the top at 0. width (int): Use -1 for Image width. height (int): Use -1 for Image height. bg_blend (int): Background blending mode to use. """ lib.TCOD_image_blit_rect( self.image_c, _console(console), x, y, width, height, bg_blend )
python
def blit_rect( self, console: tcod.console.Console, x: int, y: int, width: int, height: int, bg_blend: int, ) -> None: """Blit onto a Console without scaling or rotation. Args: console (Console): Blit destination Console. x (int): Console tile X position starting from the left at 0. y (int): Console tile Y position starting from the top at 0. width (int): Use -1 for Image width. height (int): Use -1 for Image height. bg_blend (int): Background blending mode to use. """ lib.TCOD_image_blit_rect( self.image_c, _console(console), x, y, width, height, bg_blend )
[ "def", "blit_rect", "(", "self", ",", "console", ":", "tcod", ".", "console", ".", "Console", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "bg_blend", ":", "int", ",", ")", "->", "None", ":", "lib", ".", "TCOD_image_blit_rect", "(", "self", ".", "image_c", ",", "_console", "(", "console", ")", ",", "x", ",", "y", ",", "width", ",", "height", ",", "bg_blend", ")" ]
Blit onto a Console without scaling or rotation. Args: console (Console): Blit destination Console. x (int): Console tile X position starting from the left at 0. y (int): Console tile Y position starting from the top at 0. width (int): Use -1 for Image width. height (int): Use -1 for Image height. bg_blend (int): Background blending mode to use.
[ "Blit", "onto", "a", "Console", "without", "scaling", "or", "rotation", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L231-L252
train
libtcod/python-tcod
tcod/image.py
Image.blit_2x
def blit_2x( self, console: tcod.console.Console, dest_x: int, dest_y: int, img_x: int = 0, img_y: int = 0, img_width: int = -1, img_height: int = -1, ) -> None: """Blit onto a Console with double resolution. Args: console (Console): Blit destination Console. dest_x (int): Console tile X position starting from the left at 0. dest_y (int): Console tile Y position starting from the top at 0. img_x (int): Left corner pixel of the Image to blit img_y (int): Top corner pixel of the Image to blit img_width (int): Width of the Image to blit. Use -1 for the full Image width. img_height (int): Height of the Image to blit. Use -1 for the full Image height. """ lib.TCOD_image_blit_2x( self.image_c, _console(console), dest_x, dest_y, img_x, img_y, img_width, img_height, )
python
def blit_2x( self, console: tcod.console.Console, dest_x: int, dest_y: int, img_x: int = 0, img_y: int = 0, img_width: int = -1, img_height: int = -1, ) -> None: """Blit onto a Console with double resolution. Args: console (Console): Blit destination Console. dest_x (int): Console tile X position starting from the left at 0. dest_y (int): Console tile Y position starting from the top at 0. img_x (int): Left corner pixel of the Image to blit img_y (int): Top corner pixel of the Image to blit img_width (int): Width of the Image to blit. Use -1 for the full Image width. img_height (int): Height of the Image to blit. Use -1 for the full Image height. """ lib.TCOD_image_blit_2x( self.image_c, _console(console), dest_x, dest_y, img_x, img_y, img_width, img_height, )
[ "def", "blit_2x", "(", "self", ",", "console", ":", "tcod", ".", "console", ".", "Console", ",", "dest_x", ":", "int", ",", "dest_y", ":", "int", ",", "img_x", ":", "int", "=", "0", ",", "img_y", ":", "int", "=", "0", ",", "img_width", ":", "int", "=", "-", "1", ",", "img_height", ":", "int", "=", "-", "1", ",", ")", "->", "None", ":", "lib", ".", "TCOD_image_blit_2x", "(", "self", ".", "image_c", ",", "_console", "(", "console", ")", ",", "dest_x", ",", "dest_y", ",", "img_x", ",", "img_y", ",", "img_width", ",", "img_height", ",", ")" ]
Blit onto a Console with double resolution. Args: console (Console): Blit destination Console. dest_x (int): Console tile X position starting from the left at 0. dest_y (int): Console tile Y position starting from the top at 0. img_x (int): Left corner pixel of the Image to blit img_y (int): Top corner pixel of the Image to blit img_width (int): Width of the Image to blit. Use -1 for the full Image width. img_height (int): Height of the Image to blit. Use -1 for the full Image height.
[ "Blit", "onto", "a", "Console", "with", "double", "resolution", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L254-L286
train
libtcod/python-tcod
tcod/image.py
Image.save_as
def save_as(self, filename: str) -> None: """Save the Image to a 32-bit .bmp or .png file. Args: filename (Text): File path to same this Image. """ lib.TCOD_image_save(self.image_c, filename.encode("utf-8"))
python
def save_as(self, filename: str) -> None: """Save the Image to a 32-bit .bmp or .png file. Args: filename (Text): File path to same this Image. """ lib.TCOD_image_save(self.image_c, filename.encode("utf-8"))
[ "def", "save_as", "(", "self", ",", "filename", ":", "str", ")", "->", "None", ":", "lib", ".", "TCOD_image_save", "(", "self", ".", "image_c", ",", "filename", ".", "encode", "(", "\"utf-8\"", ")", ")" ]
Save the Image to a 32-bit .bmp or .png file. Args: filename (Text): File path to same this Image.
[ "Save", "the", "Image", "to", "a", "32", "-", "bit", ".", "bmp", "or", ".", "png", "file", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L288-L294
train
libtcod/python-tcod
examples/sdlevent.py
main
def main(): """Example program for tcod.event""" WIDTH, HEIGHT = 120, 60 TITLE = None with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F", renderer=tcod.RENDERER_SDL) as console: tcod.sys_set_fps(24) while True: tcod.console_flush() for event in tcod.event.wait(): print(event) if event.type == "QUIT": raise SystemExit() elif event.type == "MOUSEMOTION": console.ch[:, -1] = 0 console.print_(0, HEIGHT - 1, str(event)) else: console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2) console.ch[:, -3] = 0 console.print_(0, HEIGHT - 3, str(event))
python
def main(): """Example program for tcod.event""" WIDTH, HEIGHT = 120, 60 TITLE = None with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F", renderer=tcod.RENDERER_SDL) as console: tcod.sys_set_fps(24) while True: tcod.console_flush() for event in tcod.event.wait(): print(event) if event.type == "QUIT": raise SystemExit() elif event.type == "MOUSEMOTION": console.ch[:, -1] = 0 console.print_(0, HEIGHT - 1, str(event)) else: console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2) console.ch[:, -3] = 0 console.print_(0, HEIGHT - 3, str(event))
[ "def", "main", "(", ")", ":", "WIDTH", ",", "HEIGHT", "=", "120", ",", "60", "TITLE", "=", "None", "with", "tcod", ".", "console_init_root", "(", "WIDTH", ",", "HEIGHT", ",", "TITLE", ",", "order", "=", "\"F\"", ",", "renderer", "=", "tcod", ".", "RENDERER_SDL", ")", "as", "console", ":", "tcod", ".", "sys_set_fps", "(", "24", ")", "while", "True", ":", "tcod", ".", "console_flush", "(", ")", "for", "event", "in", "tcod", ".", "event", ".", "wait", "(", ")", ":", "print", "(", "event", ")", "if", "event", ".", "type", "==", "\"QUIT\"", ":", "raise", "SystemExit", "(", ")", "elif", "event", ".", "type", "==", "\"MOUSEMOTION\"", ":", "console", ".", "ch", "[", ":", ",", "-", "1", "]", "=", "0", "console", ".", "print_", "(", "0", ",", "HEIGHT", "-", "1", ",", "str", "(", "event", ")", ")", "else", ":", "console", ".", "blit", "(", "console", ",", "0", ",", "0", ",", "0", ",", "1", ",", "WIDTH", ",", "HEIGHT", "-", "2", ")", "console", ".", "ch", "[", ":", ",", "-", "3", "]", "=", "0", "console", ".", "print_", "(", "0", ",", "HEIGHT", "-", "3", ",", "str", "(", "event", ")", ")" ]
Example program for tcod.event
[ "Example", "program", "for", "tcod", ".", "event" ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/examples/sdlevent.py#L7-L27
train
libtcod/python-tcod
scripts/tag_release.py
parse_changelog
def parse_changelog(args: Any) -> Tuple[str, str]: """Return an updated changelog and and the list of changes.""" with open("CHANGELOG.rst", "r") as file: match = re.match( pattern=r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)", string=file.read(), flags=re.DOTALL, ) assert match header, changes, tail = match.groups() tag = "%s - %s" % (args.tag, datetime.date.today().isoformat()) tagged = "\n%s\n%s\n%s" % (tag, "-" * len(tag), changes) if args.verbose: print(tagged) return "".join((header, tagged, tail)), changes
python
def parse_changelog(args: Any) -> Tuple[str, str]: """Return an updated changelog and and the list of changes.""" with open("CHANGELOG.rst", "r") as file: match = re.match( pattern=r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)", string=file.read(), flags=re.DOTALL, ) assert match header, changes, tail = match.groups() tag = "%s - %s" % (args.tag, datetime.date.today().isoformat()) tagged = "\n%s\n%s\n%s" % (tag, "-" * len(tag), changes) if args.verbose: print(tagged) return "".join((header, tagged, tail)), changes
[ "def", "parse_changelog", "(", "args", ":", "Any", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "with", "open", "(", "\"CHANGELOG.rst\"", ",", "\"r\"", ")", "as", "file", ":", "match", "=", "re", ".", "match", "(", "pattern", "=", "r\"(.*?Unreleased\\n---+\\n)(.+?)(\\n*[^\\n]+\\n---+\\n.*)\"", ",", "string", "=", "file", ".", "read", "(", ")", ",", "flags", "=", "re", ".", "DOTALL", ",", ")", "assert", "match", "header", ",", "changes", ",", "tail", "=", "match", ".", "groups", "(", ")", "tag", "=", "\"%s - %s\"", "%", "(", "args", ".", "tag", ",", "datetime", ".", "date", ".", "today", "(", ")", ".", "isoformat", "(", ")", ")", "tagged", "=", "\"\\n%s\\n%s\\n%s\"", "%", "(", "tag", ",", "\"-\"", "*", "len", "(", "tag", ")", ",", "changes", ")", "if", "args", ".", "verbose", ":", "print", "(", "tagged", ")", "return", "\"\"", ".", "join", "(", "(", "header", ",", "tagged", ",", "tail", ")", ")", ",", "changes" ]
Return an updated changelog and and the list of changes.
[ "Return", "an", "updated", "changelog", "and", "and", "the", "list", "of", "changes", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/scripts/tag_release.py#L29-L45
train
libtcod/python-tcod
tcod/bsp.py
BSP.split_once
def split_once(self, horizontal: bool, position: int) -> None: """Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int): """ cdata = self._as_cdata() lib.TCOD_bsp_split_once(cdata, horizontal, position) self._unpack_bsp_tree(cdata)
python
def split_once(self, horizontal: bool, position: int) -> None: """Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int): """ cdata = self._as_cdata() lib.TCOD_bsp_split_once(cdata, horizontal, position) self._unpack_bsp_tree(cdata)
[ "def", "split_once", "(", "self", ",", "horizontal", ":", "bool", ",", "position", ":", "int", ")", "->", "None", ":", "cdata", "=", "self", ".", "_as_cdata", "(", ")", "lib", ".", "TCOD_bsp_split_once", "(", "cdata", ",", "horizontal", ",", "position", ")", "self", ".", "_unpack_bsp_tree", "(", "cdata", ")" ]
Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int):
[ "Split", "this", "partition", "into", "2", "sub", "-", "partitions", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L131-L140
train
libtcod/python-tcod
tcod/bsp.py
BSP.split_recursive
def split_recursive( self, depth: int, min_width: int, min_height: int, max_horizontal_ratio: float, max_vertical_ratio: float, seed: Optional[tcod.random.Random] = None, ) -> None: """Divide this partition recursively. Args: depth (int): The maximum depth to divide this object recursively. min_width (int): The minimum width of any individual partition. min_height (int): The minimum height of any individual partition. max_horizontal_ratio (float): Prevent creating a horizontal ratio more extreme than this. max_vertical_ratio (float): Prevent creating a vertical ratio more extreme than this. seed (Optional[tcod.random.Random]): The random number generator to use. """ cdata = self._as_cdata() lib.TCOD_bsp_split_recursive( cdata, seed or ffi.NULL, depth, min_width, min_height, max_horizontal_ratio, max_vertical_ratio, ) self._unpack_bsp_tree(cdata)
python
def split_recursive( self, depth: int, min_width: int, min_height: int, max_horizontal_ratio: float, max_vertical_ratio: float, seed: Optional[tcod.random.Random] = None, ) -> None: """Divide this partition recursively. Args: depth (int): The maximum depth to divide this object recursively. min_width (int): The minimum width of any individual partition. min_height (int): The minimum height of any individual partition. max_horizontal_ratio (float): Prevent creating a horizontal ratio more extreme than this. max_vertical_ratio (float): Prevent creating a vertical ratio more extreme than this. seed (Optional[tcod.random.Random]): The random number generator to use. """ cdata = self._as_cdata() lib.TCOD_bsp_split_recursive( cdata, seed or ffi.NULL, depth, min_width, min_height, max_horizontal_ratio, max_vertical_ratio, ) self._unpack_bsp_tree(cdata)
[ "def", "split_recursive", "(", "self", ",", "depth", ":", "int", ",", "min_width", ":", "int", ",", "min_height", ":", "int", ",", "max_horizontal_ratio", ":", "float", ",", "max_vertical_ratio", ":", "float", ",", "seed", ":", "Optional", "[", "tcod", ".", "random", ".", "Random", "]", "=", "None", ",", ")", "->", "None", ":", "cdata", "=", "self", ".", "_as_cdata", "(", ")", "lib", ".", "TCOD_bsp_split_recursive", "(", "cdata", ",", "seed", "or", "ffi", ".", "NULL", ",", "depth", ",", "min_width", ",", "min_height", ",", "max_horizontal_ratio", ",", "max_vertical_ratio", ",", ")", "self", ".", "_unpack_bsp_tree", "(", "cdata", ")" ]
Divide this partition recursively. Args: depth (int): The maximum depth to divide this object recursively. min_width (int): The minimum width of any individual partition. min_height (int): The minimum height of any individual partition. max_horizontal_ratio (float): Prevent creating a horizontal ratio more extreme than this. max_vertical_ratio (float): Prevent creating a vertical ratio more extreme than this. seed (Optional[tcod.random.Random]): The random number generator to use.
[ "Divide", "this", "partition", "recursively", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L142-L174
train
libtcod/python-tcod
tcod/bsp.py
BSP.in_order
def in_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in order. .. versionadded:: 8.3 """ if self.children: yield from self.children[0].in_order() yield self yield from self.children[1].in_order() else: yield self
python
def in_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in order. .. versionadded:: 8.3 """ if self.children: yield from self.children[0].in_order() yield self yield from self.children[1].in_order() else: yield self
[ "def", "in_order", "(", "self", ")", "->", "Iterator", "[", "\"BSP\"", "]", ":", "if", "self", ".", "children", ":", "yield", "from", "self", ".", "children", "[", "0", "]", ".", "in_order", "(", ")", "yield", "self", "yield", "from", "self", ".", "children", "[", "1", "]", ".", "in_order", "(", ")", "else", ":", "yield", "self" ]
Iterate over this BSP's hierarchy in order. .. versionadded:: 8.3
[ "Iterate", "over", "this", "BSP", "s", "hierarchy", "in", "order", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L194-L204
train
libtcod/python-tcod
tcod/bsp.py
BSP.level_order
def level_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in level order. .. versionadded:: 8.3 """ next = [self] # type: List['BSP'] while next: level = next # type: List['BSP'] next = [] yield from level for node in level: next.extend(node.children)
python
def level_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in level order. .. versionadded:: 8.3 """ next = [self] # type: List['BSP'] while next: level = next # type: List['BSP'] next = [] yield from level for node in level: next.extend(node.children)
[ "def", "level_order", "(", "self", ")", "->", "Iterator", "[", "\"BSP\"", "]", ":", "next", "=", "[", "self", "]", "# type: List['BSP']", "while", "next", ":", "level", "=", "next", "# type: List['BSP']", "next", "=", "[", "]", "yield", "from", "level", "for", "node", "in", "level", ":", "next", ".", "extend", "(", "node", ".", "children", ")" ]
Iterate over this BSP's hierarchy in level order. .. versionadded:: 8.3
[ "Iterate", "over", "this", "BSP", "s", "hierarchy", "in", "level", "order", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L215-L226
train
libtcod/python-tcod
tcod/bsp.py
BSP.inverted_level_order
def inverted_level_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in inverse level order. .. versionadded:: 8.3 """ levels = [] # type: List[List['BSP']] next = [self] # type: List['BSP'] while next: levels.append(next) level = next # type: List['BSP'] next = [] for node in level: next.extend(node.children) while levels: yield from levels.pop()
python
def inverted_level_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in inverse level order. .. versionadded:: 8.3 """ levels = [] # type: List[List['BSP']] next = [self] # type: List['BSP'] while next: levels.append(next) level = next # type: List['BSP'] next = [] for node in level: next.extend(node.children) while levels: yield from levels.pop()
[ "def", "inverted_level_order", "(", "self", ")", "->", "Iterator", "[", "\"BSP\"", "]", ":", "levels", "=", "[", "]", "# type: List[List['BSP']]", "next", "=", "[", "self", "]", "# type: List['BSP']", "while", "next", ":", "levels", ".", "append", "(", "next", ")", "level", "=", "next", "# type: List['BSP']", "next", "=", "[", "]", "for", "node", "in", "level", ":", "next", ".", "extend", "(", "node", ".", "children", ")", "while", "levels", ":", "yield", "from", "levels", ".", "pop", "(", ")" ]
Iterate over this BSP's hierarchy in inverse level order. .. versionadded:: 8.3
[ "Iterate", "over", "this", "BSP", "s", "hierarchy", "in", "inverse", "level", "order", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L228-L242
train
libtcod/python-tcod
tcod/bsp.py
BSP.contains
def contains(self, x: int, y: int) -> bool: """Returns True if this node contains these coordinates. Args: x (int): X position to check. y (int): Y position to check. Returns: bool: True if this node contains these coordinates. Otherwise False. """ return ( self.x <= x < self.x + self.width and self.y <= y < self.y + self.height )
python
def contains(self, x: int, y: int) -> bool: """Returns True if this node contains these coordinates. Args: x (int): X position to check. y (int): Y position to check. Returns: bool: True if this node contains these coordinates. Otherwise False. """ return ( self.x <= x < self.x + self.width and self.y <= y < self.y + self.height )
[ "def", "contains", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "bool", ":", "return", "(", "self", ".", "x", "<=", "x", "<", "self", ".", "x", "+", "self", ".", "width", "and", "self", ".", "y", "<=", "y", "<", "self", ".", "y", "+", "self", ".", "height", ")" ]
Returns True if this node contains these coordinates. Args: x (int): X position to check. y (int): Y position to check. Returns: bool: True if this node contains these coordinates. Otherwise False.
[ "Returns", "True", "if", "this", "node", "contains", "these", "coordinates", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L244-L258
train
libtcod/python-tcod
tcod/bsp.py
BSP.find_node
def find_node(self, x: int, y: int) -> Optional["BSP"]: """Return the deepest node which contains these coordinates. Returns: Optional[BSP]: BSP object or None. """ if not self.contains(x, y): return None for child in self.children: found = child.find_node(x, y) # type: Optional["BSP"] if found: return found return self
python
def find_node(self, x: int, y: int) -> Optional["BSP"]: """Return the deepest node which contains these coordinates. Returns: Optional[BSP]: BSP object or None. """ if not self.contains(x, y): return None for child in self.children: found = child.find_node(x, y) # type: Optional["BSP"] if found: return found return self
[ "def", "find_node", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Optional", "[", "\"BSP\"", "]", ":", "if", "not", "self", ".", "contains", "(", "x", ",", "y", ")", ":", "return", "None", "for", "child", "in", "self", ".", "children", ":", "found", "=", "child", ".", "find_node", "(", "x", ",", "y", ")", "# type: Optional[\"BSP\"]", "if", "found", ":", "return", "found", "return", "self" ]
Return the deepest node which contains these coordinates. Returns: Optional[BSP]: BSP object or None.
[ "Return", "the", "deepest", "node", "which", "contains", "these", "coordinates", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L260-L272
train
libtcod/python-tcod
tdl/style.py
backport
def backport(func): """ Backport a function name into an old style for compatibility. The docstring is updated to reflect that the new function returned is deprecated and that the other function is preferred. A DeprecationWarning is also raised for using this function. If the script is run with an optimization flag then the real function will be returned without being wrapped. """ if not __debug__: return func @_functools.wraps(func) def deprecated_function(*args, **kargs): _warnings.warn('This function name is deprecated', DeprecationWarning, 2) return func(*args, **kargs) deprecated_function.__doc__ = None return deprecated_function
python
def backport(func): """ Backport a function name into an old style for compatibility. The docstring is updated to reflect that the new function returned is deprecated and that the other function is preferred. A DeprecationWarning is also raised for using this function. If the script is run with an optimization flag then the real function will be returned without being wrapped. """ if not __debug__: return func @_functools.wraps(func) def deprecated_function(*args, **kargs): _warnings.warn('This function name is deprecated', DeprecationWarning, 2) return func(*args, **kargs) deprecated_function.__doc__ = None return deprecated_function
[ "def", "backport", "(", "func", ")", ":", "if", "not", "__debug__", ":", "return", "func", "@", "_functools", ".", "wraps", "(", "func", ")", "def", "deprecated_function", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "_warnings", ".", "warn", "(", "'This function name is deprecated'", ",", "DeprecationWarning", ",", "2", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kargs", ")", "deprecated_function", ".", "__doc__", "=", "None", "return", "deprecated_function" ]
Backport a function name into an old style for compatibility. The docstring is updated to reflect that the new function returned is deprecated and that the other function is preferred. A DeprecationWarning is also raised for using this function. If the script is run with an optimization flag then the real function will be returned without being wrapped.
[ "Backport", "a", "function", "name", "into", "an", "old", "style", "for", "compatibility", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/style.py#L9-L29
train
libtcod/python-tcod
tdl/map.py
_get_fov_type
def _get_fov_type(fov): "Return a FOV from a string" oldFOV = fov fov = str(fov).upper() if fov in _FOVTYPES: return _FOVTYPES[fov] if fov[:10] == 'PERMISSIVE' and fov[10].isdigit() and fov[10] != '9': return 4 + int(fov[10]) raise _tdl.TDLError('No such fov option as %s' % oldFOV)
python
def _get_fov_type(fov): "Return a FOV from a string" oldFOV = fov fov = str(fov).upper() if fov in _FOVTYPES: return _FOVTYPES[fov] if fov[:10] == 'PERMISSIVE' and fov[10].isdigit() and fov[10] != '9': return 4 + int(fov[10]) raise _tdl.TDLError('No such fov option as %s' % oldFOV)
[ "def", "_get_fov_type", "(", "fov", ")", ":", "oldFOV", "=", "fov", "fov", "=", "str", "(", "fov", ")", ".", "upper", "(", ")", "if", "fov", "in", "_FOVTYPES", ":", "return", "_FOVTYPES", "[", "fov", "]", "if", "fov", "[", ":", "10", "]", "==", "'PERMISSIVE'", "and", "fov", "[", "10", "]", ".", "isdigit", "(", ")", "and", "fov", "[", "10", "]", "!=", "'9'", ":", "return", "4", "+", "int", "(", "fov", "[", "10", "]", ")", "raise", "_tdl", ".", "TDLError", "(", "'No such fov option as %s'", "%", "oldFOV", ")" ]
Return a FOV from a string
[ "Return", "a", "FOV", "from", "a", "string" ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L29-L37
train
libtcod/python-tcod
tdl/map.py
quick_fov
def quick_fov(x, y, callback, fov='PERMISSIVE', radius=7.5, lightWalls=True, sphere=True): """All field-of-view functionality in one call. Before using this call be sure to make a function, lambda, or method that takes 2 positional parameters and returns True if light can pass through the tile or False for light-blocking tiles and for indexes that are out of bounds of the dungeon. This function is 'quick' as in no hassle but can quickly become a very slow function call if a large radius is used or the callback provided itself isn't optimized. Always check if the index is in bounds both in the callback and in the returned values. These values can go into the negatives as well. Args: x (int): x center of the field-of-view y (int): y center of the field-of-view callback (Callable[[int, int], bool]): This should be a function that takes two positional arguments x,y and returns True if the tile at that position is transparent or False if the tile blocks light or is out of bounds. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (float) Radius of the field-of-view. When sphere is True a floating point can be used to fine-tune the range. Otherwise the radius is just rounded up. Be careful as a large radius has an exponential affect on how long this function takes. lightWalls (bool): Include or exclude wall tiles in the field-of-view. sphere (bool): True for a spherical field-of-view. False for a square one. Returns: Set[Tuple[int, int]]: A set of (x, y) points that are within the field-of-view. """ trueRadius = radius radius = int(_math.ceil(radius)) mapSize = radius * 2 + 1 fov = _get_fov_type(fov) setProp = _lib.TCOD_map_set_properties # make local inFOV = _lib.TCOD_map_is_in_fov tcodMap = _lib.TCOD_map_new(mapSize, mapSize) try: # pass no.1, write callback data to the tcodMap for x_, y_ in _itertools.product(range(mapSize), range(mapSize)): pos = (x_ + x - radius, y_ + y - radius) transparent = bool(callback(*pos)) setProp(tcodMap, x_, y_, transparent, False) # pass no.2, compute fov and build a list of points _lib.TCOD_map_compute_fov(tcodMap, radius, radius, radius, lightWalls, fov) touched = set() # points touched by field of view for x_, y_ in _itertools.product(range(mapSize), range(mapSize)): if sphere and _math.hypot(x_ - radius, y_ - radius) > trueRadius: continue if inFOV(tcodMap, x_, y_): touched.add((x_ + x - radius, y_ + y - radius)) finally: _lib.TCOD_map_delete(tcodMap) return touched
python
def quick_fov(x, y, callback, fov='PERMISSIVE', radius=7.5, lightWalls=True, sphere=True): """All field-of-view functionality in one call. Before using this call be sure to make a function, lambda, or method that takes 2 positional parameters and returns True if light can pass through the tile or False for light-blocking tiles and for indexes that are out of bounds of the dungeon. This function is 'quick' as in no hassle but can quickly become a very slow function call if a large radius is used or the callback provided itself isn't optimized. Always check if the index is in bounds both in the callback and in the returned values. These values can go into the negatives as well. Args: x (int): x center of the field-of-view y (int): y center of the field-of-view callback (Callable[[int, int], bool]): This should be a function that takes two positional arguments x,y and returns True if the tile at that position is transparent or False if the tile blocks light or is out of bounds. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (float) Radius of the field-of-view. When sphere is True a floating point can be used to fine-tune the range. Otherwise the radius is just rounded up. Be careful as a large radius has an exponential affect on how long this function takes. lightWalls (bool): Include or exclude wall tiles in the field-of-view. sphere (bool): True for a spherical field-of-view. False for a square one. Returns: Set[Tuple[int, int]]: A set of (x, y) points that are within the field-of-view. """ trueRadius = radius radius = int(_math.ceil(radius)) mapSize = radius * 2 + 1 fov = _get_fov_type(fov) setProp = _lib.TCOD_map_set_properties # make local inFOV = _lib.TCOD_map_is_in_fov tcodMap = _lib.TCOD_map_new(mapSize, mapSize) try: # pass no.1, write callback data to the tcodMap for x_, y_ in _itertools.product(range(mapSize), range(mapSize)): pos = (x_ + x - radius, y_ + y - radius) transparent = bool(callback(*pos)) setProp(tcodMap, x_, y_, transparent, False) # pass no.2, compute fov and build a list of points _lib.TCOD_map_compute_fov(tcodMap, radius, radius, radius, lightWalls, fov) touched = set() # points touched by field of view for x_, y_ in _itertools.product(range(mapSize), range(mapSize)): if sphere and _math.hypot(x_ - radius, y_ - radius) > trueRadius: continue if inFOV(tcodMap, x_, y_): touched.add((x_ + x - radius, y_ + y - radius)) finally: _lib.TCOD_map_delete(tcodMap) return touched
[ "def", "quick_fov", "(", "x", ",", "y", ",", "callback", ",", "fov", "=", "'PERMISSIVE'", ",", "radius", "=", "7.5", ",", "lightWalls", "=", "True", ",", "sphere", "=", "True", ")", ":", "trueRadius", "=", "radius", "radius", "=", "int", "(", "_math", ".", "ceil", "(", "radius", ")", ")", "mapSize", "=", "radius", "*", "2", "+", "1", "fov", "=", "_get_fov_type", "(", "fov", ")", "setProp", "=", "_lib", ".", "TCOD_map_set_properties", "# make local", "inFOV", "=", "_lib", ".", "TCOD_map_is_in_fov", "tcodMap", "=", "_lib", ".", "TCOD_map_new", "(", "mapSize", ",", "mapSize", ")", "try", ":", "# pass no.1, write callback data to the tcodMap", "for", "x_", ",", "y_", "in", "_itertools", ".", "product", "(", "range", "(", "mapSize", ")", ",", "range", "(", "mapSize", ")", ")", ":", "pos", "=", "(", "x_", "+", "x", "-", "radius", ",", "y_", "+", "y", "-", "radius", ")", "transparent", "=", "bool", "(", "callback", "(", "*", "pos", ")", ")", "setProp", "(", "tcodMap", ",", "x_", ",", "y_", ",", "transparent", ",", "False", ")", "# pass no.2, compute fov and build a list of points", "_lib", ".", "TCOD_map_compute_fov", "(", "tcodMap", ",", "radius", ",", "radius", ",", "radius", ",", "lightWalls", ",", "fov", ")", "touched", "=", "set", "(", ")", "# points touched by field of view", "for", "x_", ",", "y_", "in", "_itertools", ".", "product", "(", "range", "(", "mapSize", ")", ",", "range", "(", "mapSize", ")", ")", ":", "if", "sphere", "and", "_math", ".", "hypot", "(", "x_", "-", "radius", ",", "y_", "-", "radius", ")", ">", "trueRadius", ":", "continue", "if", "inFOV", "(", "tcodMap", ",", "x_", ",", "y_", ")", ":", "touched", ".", "add", "(", "(", "x_", "+", "x", "-", "radius", ",", "y_", "+", "y", "-", "radius", ")", ")", "finally", ":", "_lib", ".", "TCOD_map_delete", "(", "tcodMap", ")", "return", "touched" ]
All field-of-view functionality in one call. Before using this call be sure to make a function, lambda, or method that takes 2 positional parameters and returns True if light can pass through the tile or False for light-blocking tiles and for indexes that are out of bounds of the dungeon. This function is 'quick' as in no hassle but can quickly become a very slow function call if a large radius is used or the callback provided itself isn't optimized. Always check if the index is in bounds both in the callback and in the returned values. These values can go into the negatives as well. Args: x (int): x center of the field-of-view y (int): y center of the field-of-view callback (Callable[[int, int], bool]): This should be a function that takes two positional arguments x,y and returns True if the tile at that position is transparent or False if the tile blocks light or is out of bounds. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (float) Radius of the field-of-view. When sphere is True a floating point can be used to fine-tune the range. Otherwise the radius is just rounded up. Be careful as a large radius has an exponential affect on how long this function takes. lightWalls (bool): Include or exclude wall tiles in the field-of-view. sphere (bool): True for a spherical field-of-view. False for a square one. Returns: Set[Tuple[int, int]]: A set of (x, y) points that are within the field-of-view.
[ "All", "field", "-", "of", "-", "view", "functionality", "in", "one", "call", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L235-L306
train
libtcod/python-tcod
tdl/map.py
bresenham
def bresenham(x1, y1, x2, y2): """ Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points. """ points = [] issteep = abs(y2-y1) > abs(x2-x1) if issteep: x1, y1 = y1, x1 x2, y2 = y2, x2 rev = False if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 rev = True deltax = x2 - x1 deltay = abs(y2-y1) error = int(deltax / 2) y = y1 ystep = None if y1 < y2: ystep = 1 else: ystep = -1 for x in range(x1, x2 + 1): if issteep: points.append((y, x)) else: points.append((x, y)) error -= deltay if error < 0: y += ystep error += deltax # Reverse the list if the coordinates were reversed if rev: points.reverse() return points
python
def bresenham(x1, y1, x2, y2): """ Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points. """ points = [] issteep = abs(y2-y1) > abs(x2-x1) if issteep: x1, y1 = y1, x1 x2, y2 = y2, x2 rev = False if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 rev = True deltax = x2 - x1 deltay = abs(y2-y1) error = int(deltax / 2) y = y1 ystep = None if y1 < y2: ystep = 1 else: ystep = -1 for x in range(x1, x2 + 1): if issteep: points.append((y, x)) else: points.append((x, y)) error -= deltay if error < 0: y += ystep error += deltax # Reverse the list if the coordinates were reversed if rev: points.reverse() return points
[ "def", "bresenham", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "points", "=", "[", "]", "issteep", "=", "abs", "(", "y2", "-", "y1", ")", ">", "abs", "(", "x2", "-", "x1", ")", "if", "issteep", ":", "x1", ",", "y1", "=", "y1", ",", "x1", "x2", ",", "y2", "=", "y2", ",", "x2", "rev", "=", "False", "if", "x1", ">", "x2", ":", "x1", ",", "x2", "=", "x2", ",", "x1", "y1", ",", "y2", "=", "y2", ",", "y1", "rev", "=", "True", "deltax", "=", "x2", "-", "x1", "deltay", "=", "abs", "(", "y2", "-", "y1", ")", "error", "=", "int", "(", "deltax", "/", "2", ")", "y", "=", "y1", "ystep", "=", "None", "if", "y1", "<", "y2", ":", "ystep", "=", "1", "else", ":", "ystep", "=", "-", "1", "for", "x", "in", "range", "(", "x1", ",", "x2", "+", "1", ")", ":", "if", "issteep", ":", "points", ".", "append", "(", "(", "y", ",", "x", ")", ")", "else", ":", "points", ".", "append", "(", "(", "x", ",", "y", ")", ")", "error", "-=", "deltay", "if", "error", "<", "0", ":", "y", "+=", "ystep", "error", "+=", "deltax", "# Reverse the list if the coordinates were reversed", "if", "rev", ":", "points", ".", "reverse", "(", ")", "return", "points" ]
Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points.
[ "Return", "a", "list", "of", "points", "in", "a", "bresenham", "line", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L308-L349
train
libtcod/python-tcod
tdl/map.py
Map.compute_fov
def compute_fov(self, x, y, fov='PERMISSIVE', radius=None, light_walls=True, sphere=True, cumulative=False): """Compute the field-of-view of this Map and return an iterator of the points touched. Args: x (int): Point of view, x-coordinate. y (int): Point of view, y-coordinate. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (Optional[int]): Maximum view distance from the point of view. A value of 0 will give an infinite distance. light_walls (bool): Light up walls, or only the floor. sphere (bool): If True the lit area will be round instead of square. cumulative (bool): If True the lit cells will accumulate instead of being cleared before the computation. Returns: Iterator[Tuple[int, int]]: An iterator of (x, y) points of tiles touched by the field-of-view. """ # refresh cdata if radius is None: # infinite radius radius = 0 if cumulative: fov_copy = self.fov.copy() lib.TCOD_map_compute_fov( self.map_c, x, y, radius, light_walls, _get_fov_type(fov)) if cumulative: self.fov[:] |= fov_copy return zip(*np.where(self.fov))
python
def compute_fov(self, x, y, fov='PERMISSIVE', radius=None, light_walls=True, sphere=True, cumulative=False): """Compute the field-of-view of this Map and return an iterator of the points touched. Args: x (int): Point of view, x-coordinate. y (int): Point of view, y-coordinate. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (Optional[int]): Maximum view distance from the point of view. A value of 0 will give an infinite distance. light_walls (bool): Light up walls, or only the floor. sphere (bool): If True the lit area will be round instead of square. cumulative (bool): If True the lit cells will accumulate instead of being cleared before the computation. Returns: Iterator[Tuple[int, int]]: An iterator of (x, y) points of tiles touched by the field-of-view. """ # refresh cdata if radius is None: # infinite radius radius = 0 if cumulative: fov_copy = self.fov.copy() lib.TCOD_map_compute_fov( self.map_c, x, y, radius, light_walls, _get_fov_type(fov)) if cumulative: self.fov[:] |= fov_copy return zip(*np.where(self.fov))
[ "def", "compute_fov", "(", "self", ",", "x", ",", "y", ",", "fov", "=", "'PERMISSIVE'", ",", "radius", "=", "None", ",", "light_walls", "=", "True", ",", "sphere", "=", "True", ",", "cumulative", "=", "False", ")", ":", "# refresh cdata", "if", "radius", "is", "None", ":", "# infinite radius", "radius", "=", "0", "if", "cumulative", ":", "fov_copy", "=", "self", ".", "fov", ".", "copy", "(", ")", "lib", ".", "TCOD_map_compute_fov", "(", "self", ".", "map_c", ",", "x", ",", "y", ",", "radius", ",", "light_walls", ",", "_get_fov_type", "(", "fov", ")", ")", "if", "cumulative", ":", "self", ".", "fov", "[", ":", "]", "|=", "fov_copy", "return", "zip", "(", "*", "np", ".", "where", "(", "self", ".", "fov", ")", ")" ]
Compute the field-of-view of this Map and return an iterator of the points touched. Args: x (int): Point of view, x-coordinate. y (int): Point of view, y-coordinate. fov (Text): The type of field-of-view to be used. Available types are: 'BASIC', 'DIAMOND', 'SHADOW', 'RESTRICTIVE', 'PERMISSIVE', 'PERMISSIVE0', 'PERMISSIVE1', ..., 'PERMISSIVE8' radius (Optional[int]): Maximum view distance from the point of view. A value of 0 will give an infinite distance. light_walls (bool): Light up walls, or only the floor. sphere (bool): If True the lit area will be round instead of square. cumulative (bool): If True the lit cells will accumulate instead of being cleared before the computation. Returns: Iterator[Tuple[int, int]]: An iterator of (x, y) points of tiles touched by the field-of-view.
[ "Compute", "the", "field", "-", "of", "-", "view", "of", "this", "Map", "and", "return", "an", "iterator", "of", "the", "points", "touched", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L94-L130
train
libtcod/python-tcod
tdl/map.py
Map.compute_path
def compute_path(self, start_x, start_y, dest_x, dest_y, diagonal_cost=_math.sqrt(2)): """Get the shortest path between two points. Args: start_x (int): Starting x-position. start_y (int): Starting y-position. dest_x (int): Destination x-position. dest_y (int): Destination y-position. diagonal_cost (float): Multiplier for diagonal movement. Can be set to zero to disable diagonal movement entirely. Returns: List[Tuple[int, int]]: The shortest list of points to the destination position from the starting position. The start point is not included in this list. """ return tcod.path.AStar(self, diagonal_cost).get_path(start_x, start_y, dest_x, dest_y)
python
def compute_path(self, start_x, start_y, dest_x, dest_y, diagonal_cost=_math.sqrt(2)): """Get the shortest path between two points. Args: start_x (int): Starting x-position. start_y (int): Starting y-position. dest_x (int): Destination x-position. dest_y (int): Destination y-position. diagonal_cost (float): Multiplier for diagonal movement. Can be set to zero to disable diagonal movement entirely. Returns: List[Tuple[int, int]]: The shortest list of points to the destination position from the starting position. The start point is not included in this list. """ return tcod.path.AStar(self, diagonal_cost).get_path(start_x, start_y, dest_x, dest_y)
[ "def", "compute_path", "(", "self", ",", "start_x", ",", "start_y", ",", "dest_x", ",", "dest_y", ",", "diagonal_cost", "=", "_math", ".", "sqrt", "(", "2", ")", ")", ":", "return", "tcod", ".", "path", ".", "AStar", "(", "self", ",", "diagonal_cost", ")", ".", "get_path", "(", "start_x", ",", "start_y", ",", "dest_x", ",", "dest_y", ")" ]
Get the shortest path between two points. Args: start_x (int): Starting x-position. start_y (int): Starting y-position. dest_x (int): Destination x-position. dest_y (int): Destination y-position. diagonal_cost (float): Multiplier for diagonal movement. Can be set to zero to disable diagonal movement entirely. Returns: List[Tuple[int, int]]: The shortest list of points to the destination position from the starting position. The start point is not included in this list.
[ "Get", "the", "shortest", "path", "between", "two", "points", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L133-L153
train
libtcod/python-tcod
tdl/map.py
AStar.get_path
def get_path(self, origX, origY, destX, destY): """ Get the shortest path from origXY to destXY. Returns: List[Tuple[int, int]]: Returns a list walking the path from orig to dest. This excludes the starting point and includes the destination. If no path is found then an empty list is returned. """ return super(AStar, self).get_path(origX, origY, destX, destY)
python
def get_path(self, origX, origY, destX, destY): """ Get the shortest path from origXY to destXY. Returns: List[Tuple[int, int]]: Returns a list walking the path from orig to dest. This excludes the starting point and includes the destination. If no path is found then an empty list is returned. """ return super(AStar, self).get_path(origX, origY, destX, destY)
[ "def", "get_path", "(", "self", ",", "origX", ",", "origY", ",", "destX", ",", "destY", ")", ":", "return", "super", "(", "AStar", ",", "self", ")", ".", "get_path", "(", "origX", ",", "origY", ",", "destX", ",", "destY", ")" ]
Get the shortest path from origXY to destXY. Returns: List[Tuple[int, int]]: Returns a list walking the path from orig to dest. This excludes the starting point and includes the destination. If no path is found then an empty list is returned.
[ "Get", "the", "shortest", "path", "from", "origXY", "to", "destXY", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/map.py#L220-L232
train
libtcod/python-tcod
setup.py
get_long_description
def get_long_description(): """Return this projects description.""" with open("README.rst", "r") as f: readme = f.read() with open("CHANGELOG.rst", "r") as f: changelog = f.read() changelog = changelog.replace("\nUnreleased\n------------------", "") return "\n".join([readme, changelog])
python
def get_long_description(): """Return this projects description.""" with open("README.rst", "r") as f: readme = f.read() with open("CHANGELOG.rst", "r") as f: changelog = f.read() changelog = changelog.replace("\nUnreleased\n------------------", "") return "\n".join([readme, changelog])
[ "def", "get_long_description", "(", ")", ":", "with", "open", "(", "\"README.rst\"", ",", "\"r\"", ")", "as", "f", ":", "readme", "=", "f", ".", "read", "(", ")", "with", "open", "(", "\"CHANGELOG.rst\"", ",", "\"r\"", ")", "as", "f", ":", "changelog", "=", "f", ".", "read", "(", ")", "changelog", "=", "changelog", ".", "replace", "(", "\"\\nUnreleased\\n------------------\"", ",", "\"\"", ")", "return", "\"\\n\"", ".", "join", "(", "[", "readme", ",", "changelog", "]", ")" ]
Return this projects description.
[ "Return", "this", "projects", "description", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/setup.py#L78-L85
train
libtcod/python-tcod
tcod/console.py
get_height_rect
def get_height_rect(width: int, string: str) -> int: """Return the number of lines which would be printed from these parameters. `width` is the width of the print boundary. `string` is a Unicode string which may include color control characters. .. versionadded:: 9.2 """ string_ = string.encode("utf-8") # type: bytes return int(lib.get_height_rect2(width, string_, len(string_)))
python
def get_height_rect(width: int, string: str) -> int: """Return the number of lines which would be printed from these parameters. `width` is the width of the print boundary. `string` is a Unicode string which may include color control characters. .. versionadded:: 9.2 """ string_ = string.encode("utf-8") # type: bytes return int(lib.get_height_rect2(width, string_, len(string_)))
[ "def", "get_height_rect", "(", "width", ":", "int", ",", "string", ":", "str", ")", "->", "int", ":", "string_", "=", "string", ".", "encode", "(", "\"utf-8\"", ")", "# type: bytes", "return", "int", "(", "lib", ".", "get_height_rect2", "(", "width", ",", "string_", ",", "len", "(", "string_", ")", ")", ")" ]
Return the number of lines which would be printed from these parameters. `width` is the width of the print boundary. `string` is a Unicode string which may include color control characters. .. versionadded:: 9.2
[ "Return", "the", "number", "of", "lines", "which", "would", "be", "printed", "from", "these", "parameters", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L1084-L1094
train
libtcod/python-tcod
tcod/console.py
Console._get_root
def _get_root(cls, order: Optional[str] = None) -> "Console": """Return a root console singleton with valid buffers. This function will also update an already active root console. """ global _root_console if _root_console is None: _root_console = object.__new__(cls) self = _root_console # type: Console if order is not None: self._order = order self.console_c = ffi.NULL self._init_setup_console_data(self._order) return self
python
def _get_root(cls, order: Optional[str] = None) -> "Console": """Return a root console singleton with valid buffers. This function will also update an already active root console. """ global _root_console if _root_console is None: _root_console = object.__new__(cls) self = _root_console # type: Console if order is not None: self._order = order self.console_c = ffi.NULL self._init_setup_console_data(self._order) return self
[ "def", "_get_root", "(", "cls", ",", "order", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"Console\"", ":", "global", "_root_console", "if", "_root_console", "is", "None", ":", "_root_console", "=", "object", ".", "__new__", "(", "cls", ")", "self", "=", "_root_console", "# type: Console", "if", "order", "is", "not", "None", ":", "self", ".", "_order", "=", "order", "self", ".", "console_c", "=", "ffi", ".", "NULL", "self", ".", "_init_setup_console_data", "(", "self", ".", "_order", ")", "return", "self" ]
Return a root console singleton with valid buffers. This function will also update an already active root console.
[ "Return", "a", "root", "console", "singleton", "with", "valid", "buffers", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L164-L177
train
libtcod/python-tcod
tcod/console.py
Console._init_setup_console_data
def _init_setup_console_data(self, order: str = "C") -> None: """Setup numpy arrays over libtcod data buffers.""" global _root_console self._key_color = None if self.console_c == ffi.NULL: _root_console = self self._console_data = lib.TCOD_ctx.root else: self._console_data = ffi.cast( "struct TCOD_Console*", self.console_c ) self._tiles = np.frombuffer( ffi.buffer(self._console_data.tiles[0 : self.width * self.height]), dtype=self.DTYPE, ).reshape((self.height, self.width)) self._order = tcod._internal.verify_order(order)
python
def _init_setup_console_data(self, order: str = "C") -> None: """Setup numpy arrays over libtcod data buffers.""" global _root_console self._key_color = None if self.console_c == ffi.NULL: _root_console = self self._console_data = lib.TCOD_ctx.root else: self._console_data = ffi.cast( "struct TCOD_Console*", self.console_c ) self._tiles = np.frombuffer( ffi.buffer(self._console_data.tiles[0 : self.width * self.height]), dtype=self.DTYPE, ).reshape((self.height, self.width)) self._order = tcod._internal.verify_order(order)
[ "def", "_init_setup_console_data", "(", "self", ",", "order", ":", "str", "=", "\"C\"", ")", "->", "None", ":", "global", "_root_console", "self", ".", "_key_color", "=", "None", "if", "self", ".", "console_c", "==", "ffi", ".", "NULL", ":", "_root_console", "=", "self", "self", ".", "_console_data", "=", "lib", ".", "TCOD_ctx", ".", "root", "else", ":", "self", ".", "_console_data", "=", "ffi", ".", "cast", "(", "\"struct TCOD_Console*\"", ",", "self", ".", "console_c", ")", "self", ".", "_tiles", "=", "np", ".", "frombuffer", "(", "ffi", ".", "buffer", "(", "self", ".", "_console_data", ".", "tiles", "[", "0", ":", "self", ".", "width", "*", "self", ".", "height", "]", ")", ",", "dtype", "=", "self", ".", "DTYPE", ",", ")", ".", "reshape", "(", "(", "self", ".", "height", ",", "self", ".", "width", ")", ")", "self", ".", "_order", "=", "tcod", ".", "_internal", ".", "verify_order", "(", "order", ")" ]
Setup numpy arrays over libtcod data buffers.
[ "Setup", "numpy", "arrays", "over", "libtcod", "data", "buffers", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L179-L196
train
libtcod/python-tcod
tcod/console.py
Console.tiles
def tiles(self) -> np.array: """An array of this consoles tile data. This acts as a combination of the `ch`, `fg`, and `bg` attributes. Colors include an alpha channel but how alpha works is currently undefined. Example:: >>> con = tcod.console.Console(10, 2, order="F") >>> con.tiles[0, 0] = ( ... ord("X"), ... (*tcod.white, 255), ... (*tcod.black, 255), ... ) >>> con.tiles[0, 0] (88, [255, 255, 255, 255], [ 0, 0, 0, 255]) .. versionadded:: 10.0 """ return self._tiles.T if self._order == "F" else self._tiles
python
def tiles(self) -> np.array: """An array of this consoles tile data. This acts as a combination of the `ch`, `fg`, and `bg` attributes. Colors include an alpha channel but how alpha works is currently undefined. Example:: >>> con = tcod.console.Console(10, 2, order="F") >>> con.tiles[0, 0] = ( ... ord("X"), ... (*tcod.white, 255), ... (*tcod.black, 255), ... ) >>> con.tiles[0, 0] (88, [255, 255, 255, 255], [ 0, 0, 0, 255]) .. versionadded:: 10.0 """ return self._tiles.T if self._order == "F" else self._tiles
[ "def", "tiles", "(", "self", ")", "->", "np", ".", "array", ":", "return", "self", ".", "_tiles", ".", "T", "if", "self", ".", "_order", "==", "\"F\"", "else", "self", ".", "_tiles" ]
An array of this consoles tile data. This acts as a combination of the `ch`, `fg`, and `bg` attributes. Colors include an alpha channel but how alpha works is currently undefined. Example:: >>> con = tcod.console.Console(10, 2, order="F") >>> con.tiles[0, 0] = ( ... ord("X"), ... (*tcod.white, 255), ... (*tcod.black, 255), ... ) >>> con.tiles[0, 0] (88, [255, 255, 255, 255], [ 0, 0, 0, 255]) .. versionadded:: 10.0
[ "An", "array", "of", "this", "consoles", "tile", "data", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L249-L268
train
libtcod/python-tcod
tcod/console.py
Console.__clear_warning
def __clear_warning(self, name: str, value: Tuple[int, int, int]) -> None: """Raise a warning for bad default values during calls to clear.""" warnings.warn( "Clearing with the console default values is deprecated.\n" "Add %s=%r to this call." % (name, value), DeprecationWarning, stacklevel=3, )
python
def __clear_warning(self, name: str, value: Tuple[int, int, int]) -> None: """Raise a warning for bad default values during calls to clear.""" warnings.warn( "Clearing with the console default values is deprecated.\n" "Add %s=%r to this call." % (name, value), DeprecationWarning, stacklevel=3, )
[ "def", "__clear_warning", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "warnings", ".", "warn", "(", "\"Clearing with the console default values is deprecated.\\n\"", "\"Add %s=%r to this call.\"", "%", "(", "name", ",", "value", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ",", ")" ]
Raise a warning for bad default values during calls to clear.
[ "Raise", "a", "warning", "for", "bad", "default", "values", "during", "calls", "to", "clear", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L312-L319
train
libtcod/python-tcod
tcod/console.py
Console.__deprecate_defaults
def __deprecate_defaults( self, new_func: str, bg_blend: Any, alignment: Any = ..., clear: Any = ..., ) -> None: """Return the parameters needed to recreate the current default state. """ if not __debug__: return fg = self.default_fg # type: Any bg = self.default_bg # type: Any if bg_blend == tcod.constants.BKGND_NONE: bg = None if bg_blend == tcod.constants.BKGND_DEFAULT: bg_blend = self.default_bg_blend else: bg_blend = None if bg_blend == tcod.constants.BKGND_NONE: bg = None bg_blend = None if bg_blend == tcod.constants.BKGND_SET: bg_blend = None if alignment is None: alignment = self.default_alignment if alignment == tcod.constants.LEFT: alignment = None else: alignment = None if clear is not ...: fg = None params = [] if clear is True: params.append('ch=ord(" ")') if clear is False: params.append("ch=0") if fg is not None: params.append("fg=%s" % (fg,)) if bg is not None: params.append("bg=%s" % (bg,)) if bg_blend is not None: params.append("bg_blend=%s" % (self.__BG_BLEND_LOOKUP[bg_blend],)) if alignment is not None: params.append( "alignment=%s" % (self.__ALIGNMENT_LOOKUP[alignment],) ) param_str = ", ".join(params) if not param_str: param_str = "." else: param_str = " and add the following parameters:\n%s" % (param_str,) warnings.warn( "Console functions using default values have been deprecated.\n" "Replace this method with `Console.%s`%s" % (new_func, param_str), DeprecationWarning, stacklevel=3, )
python
def __deprecate_defaults( self, new_func: str, bg_blend: Any, alignment: Any = ..., clear: Any = ..., ) -> None: """Return the parameters needed to recreate the current default state. """ if not __debug__: return fg = self.default_fg # type: Any bg = self.default_bg # type: Any if bg_blend == tcod.constants.BKGND_NONE: bg = None if bg_blend == tcod.constants.BKGND_DEFAULT: bg_blend = self.default_bg_blend else: bg_blend = None if bg_blend == tcod.constants.BKGND_NONE: bg = None bg_blend = None if bg_blend == tcod.constants.BKGND_SET: bg_blend = None if alignment is None: alignment = self.default_alignment if alignment == tcod.constants.LEFT: alignment = None else: alignment = None if clear is not ...: fg = None params = [] if clear is True: params.append('ch=ord(" ")') if clear is False: params.append("ch=0") if fg is not None: params.append("fg=%s" % (fg,)) if bg is not None: params.append("bg=%s" % (bg,)) if bg_blend is not None: params.append("bg_blend=%s" % (self.__BG_BLEND_LOOKUP[bg_blend],)) if alignment is not None: params.append( "alignment=%s" % (self.__ALIGNMENT_LOOKUP[alignment],) ) param_str = ", ".join(params) if not param_str: param_str = "." else: param_str = " and add the following parameters:\n%s" % (param_str,) warnings.warn( "Console functions using default values have been deprecated.\n" "Replace this method with `Console.%s`%s" % (new_func, param_str), DeprecationWarning, stacklevel=3, )
[ "def", "__deprecate_defaults", "(", "self", ",", "new_func", ":", "str", ",", "bg_blend", ":", "Any", ",", "alignment", ":", "Any", "=", "...", ",", "clear", ":", "Any", "=", "...", ",", ")", "->", "None", ":", "if", "not", "__debug__", ":", "return", "fg", "=", "self", ".", "default_fg", "# type: Any", "bg", "=", "self", ".", "default_bg", "# type: Any", "if", "bg_blend", "==", "tcod", ".", "constants", ".", "BKGND_NONE", ":", "bg", "=", "None", "if", "bg_blend", "==", "tcod", ".", "constants", ".", "BKGND_DEFAULT", ":", "bg_blend", "=", "self", ".", "default_bg_blend", "else", ":", "bg_blend", "=", "None", "if", "bg_blend", "==", "tcod", ".", "constants", ".", "BKGND_NONE", ":", "bg", "=", "None", "bg_blend", "=", "None", "if", "bg_blend", "==", "tcod", ".", "constants", ".", "BKGND_SET", ":", "bg_blend", "=", "None", "if", "alignment", "is", "None", ":", "alignment", "=", "self", ".", "default_alignment", "if", "alignment", "==", "tcod", ".", "constants", ".", "LEFT", ":", "alignment", "=", "None", "else", ":", "alignment", "=", "None", "if", "clear", "is", "not", "...", ":", "fg", "=", "None", "params", "=", "[", "]", "if", "clear", "is", "True", ":", "params", ".", "append", "(", "'ch=ord(\" \")'", ")", "if", "clear", "is", "False", ":", "params", ".", "append", "(", "\"ch=0\"", ")", "if", "fg", "is", "not", "None", ":", "params", ".", "append", "(", "\"fg=%s\"", "%", "(", "fg", ",", ")", ")", "if", "bg", "is", "not", "None", ":", "params", ".", "append", "(", "\"bg=%s\"", "%", "(", "bg", ",", ")", ")", "if", "bg_blend", "is", "not", "None", ":", "params", ".", "append", "(", "\"bg_blend=%s\"", "%", "(", "self", ".", "__BG_BLEND_LOOKUP", "[", "bg_blend", "]", ",", ")", ")", "if", "alignment", "is", "not", "None", ":", "params", ".", "append", "(", "\"alignment=%s\"", "%", "(", "self", ".", "__ALIGNMENT_LOOKUP", "[", "alignment", "]", ",", ")", ")", "param_str", "=", "\", \"", ".", "join", "(", "params", ")", "if", "not", "param_str", ":", "param_str", "=", "\".\"", "else", ":", "param_str", "=", "\" and add the following parameters:\\n%s\"", "%", "(", "param_str", ",", ")", "warnings", ".", "warn", "(", "\"Console functions using default values have been deprecated.\\n\"", "\"Replace this method with `Console.%s`%s\"", "%", "(", "new_func", ",", "param_str", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ",", ")" ]
Return the parameters needed to recreate the current default state.
[ "Return", "the", "parameters", "needed", "to", "recreate", "the", "current", "default", "state", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L390-L448
train
libtcod/python-tcod
tcod/console.py
Console.get_height_rect
def get_height_rect( self, x: int, y: int, width: int, height: int, string: str ) -> int: """Return the height of this text word-wrapped into this rectangle. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): Maximum width to render the text. height (int): Maximum lines to render the text. string (str): A Unicode string. Returns: int: The number of lines of text once word-wrapped. """ string_ = string.encode("utf-8") return int( lib.get_height_rect( self.console_c, x, y, width, height, string_, len(string_) ) )
python
def get_height_rect( self, x: int, y: int, width: int, height: int, string: str ) -> int: """Return the height of this text word-wrapped into this rectangle. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): Maximum width to render the text. height (int): Maximum lines to render the text. string (str): A Unicode string. Returns: int: The number of lines of text once word-wrapped. """ string_ = string.encode("utf-8") return int( lib.get_height_rect( self.console_c, x, y, width, height, string_, len(string_) ) )
[ "def", "get_height_rect", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "string", ":", "str", ")", "->", "int", ":", "string_", "=", "string", ".", "encode", "(", "\"utf-8\"", ")", "return", "int", "(", "lib", ".", "get_height_rect", "(", "self", ".", "console_c", ",", "x", ",", "y", ",", "width", ",", "height", ",", "string_", ",", "len", "(", "string_", ")", ")", ")" ]
Return the height of this text word-wrapped into this rectangle. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): Maximum width to render the text. height (int): Maximum lines to render the text. string (str): A Unicode string. Returns: int: The number of lines of text once word-wrapped.
[ "Return", "the", "height", "of", "this", "text", "word", "-", "wrapped", "into", "this", "rectangle", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L529-L549
train
libtcod/python-tcod
tcod/console.py
Console.print_frame
def print_frame( self, x: int, y: int, width: int, height: int, string: str = "", clear: bool = True, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a framed rectangle with optional text. This uses the default background color and blend mode to fill the rectangle and the default foreground to draw the outline. `string` will be printed on the inside of the rectangle, word-wrapped. If `string` is empty then no title will be drawn. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): The width if the frame. height (int): The height of the frame. string (str): A Unicode string to print. clear (bool): If True all text in the affected area will be removed. bg_blend (int): The background blending flag. .. versionchanged:: 8.2 Now supports Unicode strings. .. deprecated:: 8.5 Console methods which depend on console defaults have been deprecated. Use :any:`Console.draw_frame` instead, calling this function will print a warning detailing which default values need to be made explicit. """ self.__deprecate_defaults("draw_frame", bg_blend) string = _fmt(string) if string else ffi.NULL lib.TCOD_console_printf_frame( self.console_c, x, y, width, height, clear, bg_blend, string )
python
def print_frame( self, x: int, y: int, width: int, height: int, string: str = "", clear: bool = True, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a framed rectangle with optional text. This uses the default background color and blend mode to fill the rectangle and the default foreground to draw the outline. `string` will be printed on the inside of the rectangle, word-wrapped. If `string` is empty then no title will be drawn. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): The width if the frame. height (int): The height of the frame. string (str): A Unicode string to print. clear (bool): If True all text in the affected area will be removed. bg_blend (int): The background blending flag. .. versionchanged:: 8.2 Now supports Unicode strings. .. deprecated:: 8.5 Console methods which depend on console defaults have been deprecated. Use :any:`Console.draw_frame` instead, calling this function will print a warning detailing which default values need to be made explicit. """ self.__deprecate_defaults("draw_frame", bg_blend) string = _fmt(string) if string else ffi.NULL lib.TCOD_console_printf_frame( self.console_c, x, y, width, height, clear, bg_blend, string )
[ "def", "print_frame", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "string", ":", "str", "=", "\"\"", ",", "clear", ":", "bool", "=", "True", ",", "bg_blend", ":", "int", "=", "tcod", ".", "constants", ".", "BKGND_DEFAULT", ",", ")", "->", "None", ":", "self", ".", "__deprecate_defaults", "(", "\"draw_frame\"", ",", "bg_blend", ")", "string", "=", "_fmt", "(", "string", ")", "if", "string", "else", "ffi", ".", "NULL", "lib", ".", "TCOD_console_printf_frame", "(", "self", ".", "console_c", ",", "x", ",", "y", ",", "width", ",", "height", ",", "clear", ",", "bg_blend", ",", "string", ")" ]
Draw a framed rectangle with optional text. This uses the default background color and blend mode to fill the rectangle and the default foreground to draw the outline. `string` will be printed on the inside of the rectangle, word-wrapped. If `string` is empty then no title will be drawn. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): The width if the frame. height (int): The height of the frame. string (str): A Unicode string to print. clear (bool): If True all text in the affected area will be removed. bg_blend (int): The background blending flag. .. versionchanged:: 8.2 Now supports Unicode strings. .. deprecated:: 8.5 Console methods which depend on console defaults have been deprecated. Use :any:`Console.draw_frame` instead, calling this function will print a warning detailing which default values need to be made explicit.
[ "Draw", "a", "framed", "rectangle", "with", "optional", "text", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L639-L681
train
libtcod/python-tcod
tcod/console.py
Console.blit
def blit( self, dest: "Console", dest_x: int = 0, dest_y: int = 0, src_x: int = 0, src_y: int = 0, width: int = 0, height: int = 0, fg_alpha: float = 1.0, bg_alpha: float = 1.0, key_color: Optional[Tuple[int, int, int]] = None, ) -> None: """Blit from this console onto the ``dest`` console. Args: dest (Console): The destintaion console to blit onto. dest_x (int): Leftmost coordinate of the destintaion console. dest_y (int): Topmost coordinate of the destintaion console. src_x (int): X coordinate from this console to blit, from the left. src_y (int): Y coordinate from this console to blit, from the top. width (int): The width of the region to blit. If this is 0 the maximum possible width will be used. height (int): The height of the region to blit. If this is 0 the maximum possible height will be used. fg_alpha (float): Foreground color alpha vaule. bg_alpha (float): Background color alpha vaule. key_color (Optional[Tuple[int, int, int]]): None, or a (red, green, blue) tuple with values of 0-255. .. versionchanged:: 4.0 Parameters were rearraged and made optional. Previously they were: `(x, y, width, height, dest, dest_x, dest_y, *)` """ # The old syntax is easy to detect and correct. if hasattr(src_y, "console_c"): ( src_x, # type: ignore src_y, width, height, dest, # type: ignore dest_x, dest_y, ) = (dest, dest_x, dest_y, src_x, src_y, width, height) warnings.warn( "Parameter names have been moved around, see documentation.", DeprecationWarning, stacklevel=2, ) key_color = key_color or self._key_color if key_color: key_color = ffi.new("TCOD_color_t*", key_color) lib.TCOD_console_blit_key_color( self.console_c, src_x, src_y, width, height, dest.console_c, dest_x, dest_y, fg_alpha, bg_alpha, key_color, ) else: lib.TCOD_console_blit( self.console_c, src_x, src_y, width, height, dest.console_c, dest_x, dest_y, fg_alpha, bg_alpha, )
python
def blit( self, dest: "Console", dest_x: int = 0, dest_y: int = 0, src_x: int = 0, src_y: int = 0, width: int = 0, height: int = 0, fg_alpha: float = 1.0, bg_alpha: float = 1.0, key_color: Optional[Tuple[int, int, int]] = None, ) -> None: """Blit from this console onto the ``dest`` console. Args: dest (Console): The destintaion console to blit onto. dest_x (int): Leftmost coordinate of the destintaion console. dest_y (int): Topmost coordinate of the destintaion console. src_x (int): X coordinate from this console to blit, from the left. src_y (int): Y coordinate from this console to blit, from the top. width (int): The width of the region to blit. If this is 0 the maximum possible width will be used. height (int): The height of the region to blit. If this is 0 the maximum possible height will be used. fg_alpha (float): Foreground color alpha vaule. bg_alpha (float): Background color alpha vaule. key_color (Optional[Tuple[int, int, int]]): None, or a (red, green, blue) tuple with values of 0-255. .. versionchanged:: 4.0 Parameters were rearraged and made optional. Previously they were: `(x, y, width, height, dest, dest_x, dest_y, *)` """ # The old syntax is easy to detect and correct. if hasattr(src_y, "console_c"): ( src_x, # type: ignore src_y, width, height, dest, # type: ignore dest_x, dest_y, ) = (dest, dest_x, dest_y, src_x, src_y, width, height) warnings.warn( "Parameter names have been moved around, see documentation.", DeprecationWarning, stacklevel=2, ) key_color = key_color or self._key_color if key_color: key_color = ffi.new("TCOD_color_t*", key_color) lib.TCOD_console_blit_key_color( self.console_c, src_x, src_y, width, height, dest.console_c, dest_x, dest_y, fg_alpha, bg_alpha, key_color, ) else: lib.TCOD_console_blit( self.console_c, src_x, src_y, width, height, dest.console_c, dest_x, dest_y, fg_alpha, bg_alpha, )
[ "def", "blit", "(", "self", ",", "dest", ":", "\"Console\"", ",", "dest_x", ":", "int", "=", "0", ",", "dest_y", ":", "int", "=", "0", ",", "src_x", ":", "int", "=", "0", ",", "src_y", ":", "int", "=", "0", ",", "width", ":", "int", "=", "0", ",", "height", ":", "int", "=", "0", ",", "fg_alpha", ":", "float", "=", "1.0", ",", "bg_alpha", ":", "float", "=", "1.0", ",", "key_color", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", ")", "->", "None", ":", "# The old syntax is easy to detect and correct.", "if", "hasattr", "(", "src_y", ",", "\"console_c\"", ")", ":", "(", "src_x", ",", "# type: ignore", "src_y", ",", "width", ",", "height", ",", "dest", ",", "# type: ignore", "dest_x", ",", "dest_y", ",", ")", "=", "(", "dest", ",", "dest_x", ",", "dest_y", ",", "src_x", ",", "src_y", ",", "width", ",", "height", ")", "warnings", ".", "warn", "(", "\"Parameter names have been moved around, see documentation.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "key_color", "=", "key_color", "or", "self", ".", "_key_color", "if", "key_color", ":", "key_color", "=", "ffi", ".", "new", "(", "\"TCOD_color_t*\"", ",", "key_color", ")", "lib", ".", "TCOD_console_blit_key_color", "(", "self", ".", "console_c", ",", "src_x", ",", "src_y", ",", "width", ",", "height", ",", "dest", ".", "console_c", ",", "dest_x", ",", "dest_y", ",", "fg_alpha", ",", "bg_alpha", ",", "key_color", ",", ")", "else", ":", "lib", ".", "TCOD_console_blit", "(", "self", ".", "console_c", ",", "src_x", ",", "src_y", ",", "width", ",", "height", ",", "dest", ".", "console_c", ",", "dest_x", ",", "dest_y", ",", "fg_alpha", ",", "bg_alpha", ",", ")" ]
Blit from this console onto the ``dest`` console. Args: dest (Console): The destintaion console to blit onto. dest_x (int): Leftmost coordinate of the destintaion console. dest_y (int): Topmost coordinate of the destintaion console. src_x (int): X coordinate from this console to blit, from the left. src_y (int): Y coordinate from this console to blit, from the top. width (int): The width of the region to blit. If this is 0 the maximum possible width will be used. height (int): The height of the region to blit. If this is 0 the maximum possible height will be used. fg_alpha (float): Foreground color alpha vaule. bg_alpha (float): Background color alpha vaule. key_color (Optional[Tuple[int, int, int]]): None, or a (red, green, blue) tuple with values of 0-255. .. versionchanged:: 4.0 Parameters were rearraged and made optional. Previously they were: `(x, y, width, height, dest, dest_x, dest_y, *)`
[ "Blit", "from", "this", "console", "onto", "the", "dest", "console", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L683-L766
train
libtcod/python-tcod
tcod/console.py
Console.print
def print( self, x: int, y: int, string: str, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, alignment: int = tcod.constants.LEFT, ) -> None: """Print a string on a console with manual line breaks. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `string` is a Unicode string which may include color control characters. Strings which are too long will be truncated until the next newline character ``"\\n"``. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. `alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) string_ = string.encode("utf-8") # type: bytes lib.console_print( self.console_c, x, y, string_, len(string_), (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, alignment, )
python
def print( self, x: int, y: int, string: str, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, alignment: int = tcod.constants.LEFT, ) -> None: """Print a string on a console with manual line breaks. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `string` is a Unicode string which may include color control characters. Strings which are too long will be truncated until the next newline character ``"\\n"``. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. `alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) string_ = string.encode("utf-8") # type: bytes lib.console_print( self.console_c, x, y, string_, len(string_), (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, alignment, )
[ "def", "print", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "string", ":", "str", ",", "fg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg_blend", ":", "int", "=", "tcod", ".", "constants", ".", "BKGND_SET", ",", "alignment", ":", "int", "=", "tcod", ".", "constants", ".", "LEFT", ",", ")", "->", "None", ":", "x", ",", "y", "=", "self", ".", "_pythonic_index", "(", "x", ",", "y", ")", "string_", "=", "string", ".", "encode", "(", "\"utf-8\"", ")", "# type: bytes", "lib", ".", "console_print", "(", "self", ".", "console_c", ",", "x", ",", "y", ",", "string_", ",", "len", "(", "string_", ")", ",", "(", "fg", ",", ")", "if", "fg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "(", "bg", ",", ")", "if", "bg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "bg_blend", ",", "alignment", ",", ")" ]
Print a string on a console with manual line breaks. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `string` is a Unicode string which may include color control characters. Strings which are too long will be truncated until the next newline character ``"\\n"``. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. `alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black.
[ "Print", "a", "string", "on", "a", "console", "with", "manual", "line", "breaks", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L874-L921
train
libtcod/python-tcod
tcod/console.py
Console.draw_frame
def draw_frame( self, x: int, y: int, width: int, height: int, title: str = "", clear: bool = True, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, ) -> None: """Draw a framed rectangle with an optional title. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the frame. `title` is a Unicode string. If `clear` is True than the region inside of the frame will be cleared. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) title_ = title.encode("utf-8") # type: bytes lib.print_frame( self.console_c, x, y, width, height, title_, len(title_), (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, clear, )
python
def draw_frame( self, x: int, y: int, width: int, height: int, title: str = "", clear: bool = True, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, ) -> None: """Draw a framed rectangle with an optional title. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the frame. `title` is a Unicode string. If `clear` is True than the region inside of the frame will be cleared. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) title_ = title.encode("utf-8") # type: bytes lib.print_frame( self.console_c, x, y, width, height, title_, len(title_), (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, clear, )
[ "def", "draw_frame", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "title", ":", "str", "=", "\"\"", ",", "clear", ":", "bool", "=", "True", ",", "fg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg_blend", ":", "int", "=", "tcod", ".", "constants", ".", "BKGND_SET", ",", ")", "->", "None", ":", "x", ",", "y", "=", "self", ".", "_pythonic_index", "(", "x", ",", "y", ")", "title_", "=", "title", ".", "encode", "(", "\"utf-8\"", ")", "# type: bytes", "lib", ".", "print_frame", "(", "self", ".", "console_c", ",", "x", ",", "y", ",", "width", ",", "height", ",", "title_", ",", "len", "(", "title_", ")", ",", "(", "fg", ",", ")", "if", "fg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "(", "bg", ",", ")", "if", "bg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "bg_blend", ",", "clear", ",", ")" ]
Draw a framed rectangle with an optional title. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the frame. `title` is a Unicode string. If `clear` is True than the region inside of the frame will be cleared. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black.
[ "Draw", "a", "framed", "rectangle", "with", "an", "optional", "title", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L982-L1033
train
libtcod/python-tcod
tcod/console.py
Console.draw_rect
def draw_rect( self, x: int, y: int, width: int, height: int, ch: int, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, ) -> None: """Draw characters and colors over a rectangular region. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the rectangle. `ch` is a Unicode integer. You can use 0 to leave the current characters unchanged. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) lib.draw_rect( self.console_c, x, y, width, height, ch, (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, )
python
def draw_rect( self, x: int, y: int, width: int, height: int, ch: int, fg: Optional[Tuple[int, int, int]] = None, bg: Optional[Tuple[int, int, int]] = None, bg_blend: int = tcod.constants.BKGND_SET, ) -> None: """Draw characters and colors over a rectangular region. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the rectangle. `ch` is a Unicode integer. You can use 0 to leave the current characters unchanged. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black. """ x, y = self._pythonic_index(x, y) lib.draw_rect( self.console_c, x, y, width, height, ch, (fg,) if fg is not None else ffi.NULL, (bg,) if bg is not None else ffi.NULL, bg_blend, )
[ "def", "draw_rect", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "ch", ":", "int", ",", "fg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", ",", "int", "]", "]", "=", "None", ",", "bg_blend", ":", "int", "=", "tcod", ".", "constants", ".", "BKGND_SET", ",", ")", "->", "None", ":", "x", ",", "y", "=", "self", ".", "_pythonic_index", "(", "x", ",", "y", ")", "lib", ".", "draw_rect", "(", "self", ".", "console_c", ",", "x", ",", "y", ",", "width", ",", "height", ",", "ch", ",", "(", "fg", ",", ")", "if", "fg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "(", "bg", ",", ")", "if", "bg", "is", "not", "None", "else", "ffi", ".", "NULL", ",", "bg_blend", ",", ")" ]
Draw characters and colors over a rectangular region. `x` and `y` are the starting tile, with ``0,0`` as the upper-left corner of the console. You can use negative numbers if you want to start printing relative to the bottom-right corner, but this behavior may change in future versions. `width` and `height` determine the size of the rectangle. `ch` is a Unicode integer. You can use 0 to leave the current characters unchanged. `fg` and `bg` are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to `None` to leave the colors unchanged. `bg_blend` is the blend type used by libtcod. .. versionadded:: 8.5 .. versionchanged:: 9.0 `fg` and `bg` now default to `None` instead of white-on-black.
[ "Draw", "characters", "and", "colors", "over", "a", "rectangular", "region", "." ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L1035-L1081
train
libtcod/python-tcod
fonts/X11/bdf/bdf2png.py
Glyph.blit
def blit(self, image, x, y): """blit to the image array""" # adjust the position with the local bbox x += self.font_bbox[2] - self.bbox[2] y += self.font_bbox[3] - self.bbox[3] x += self.font_bbox[0] - self.bbox[0] y += self.font_bbox[1] - self.bbox[1] image[y:y+self.height, x:x+self.width] = self.bitmap * 255
python
def blit(self, image, x, y): """blit to the image array""" # adjust the position with the local bbox x += self.font_bbox[2] - self.bbox[2] y += self.font_bbox[3] - self.bbox[3] x += self.font_bbox[0] - self.bbox[0] y += self.font_bbox[1] - self.bbox[1] image[y:y+self.height, x:x+self.width] = self.bitmap * 255
[ "def", "blit", "(", "self", ",", "image", ",", "x", ",", "y", ")", ":", "# adjust the position with the local bbox", "x", "+=", "self", ".", "font_bbox", "[", "2", "]", "-", "self", ".", "bbox", "[", "2", "]", "y", "+=", "self", ".", "font_bbox", "[", "3", "]", "-", "self", ".", "bbox", "[", "3", "]", "x", "+=", "self", ".", "font_bbox", "[", "0", "]", "-", "self", ".", "bbox", "[", "0", "]", "y", "+=", "self", ".", "font_bbox", "[", "1", "]", "-", "self", ".", "bbox", "[", "1", "]", "image", "[", "y", ":", "y", "+", "self", ".", "height", ",", "x", ":", "x", "+", "self", ".", "width", "]", "=", "self", ".", "bitmap", "*", "255" ]
blit to the image array
[ "blit", "to", "the", "image", "array" ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/fonts/X11/bdf/bdf2png.py#L80-L87
train
libtcod/python-tcod
fonts/X11/bdf/bdf2png.py
Glyph.parseBits
def parseBits(self, hexcode, width): """enumerate over bits in a line of data""" bitarray = [] for byte in hexcode[::-1]: bits = int(byte, 16) for x in range(4): bitarray.append(bool((2 ** x) & bits)) bitarray = bitarray[::-1] return enumerate(bitarray[:width])
python
def parseBits(self, hexcode, width): """enumerate over bits in a line of data""" bitarray = [] for byte in hexcode[::-1]: bits = int(byte, 16) for x in range(4): bitarray.append(bool((2 ** x) & bits)) bitarray = bitarray[::-1] return enumerate(bitarray[:width])
[ "def", "parseBits", "(", "self", ",", "hexcode", ",", "width", ")", ":", "bitarray", "=", "[", "]", "for", "byte", "in", "hexcode", "[", ":", ":", "-", "1", "]", ":", "bits", "=", "int", "(", "byte", ",", "16", ")", "for", "x", "in", "range", "(", "4", ")", ":", "bitarray", ".", "append", "(", "bool", "(", "(", "2", "**", "x", ")", "&", "bits", ")", ")", "bitarray", "=", "bitarray", "[", ":", ":", "-", "1", "]", "return", "enumerate", "(", "bitarray", "[", ":", "width", "]", ")" ]
enumerate over bits in a line of data
[ "enumerate", "over", "bits", "in", "a", "line", "of", "data" ]
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/fonts/X11/bdf/bdf2png.py#L89-L97
train
Netflix-Skunkworks/raven-python-lambda
raven_python_lambda/__init__.py
memory_warning
def memory_warning(config, context): """Determines when memory usage is nearing it's max.""" used = psutil.Process(os.getpid()).memory_info().rss / 1048576 limit = float(context.memory_limit_in_mb) p = used / limit memory_threshold = config.get('memory_warning_threshold') if p >= memory_threshold: config['raven_client'].captureMessage( 'Memory Usage Warning', level='warning', extra={ 'MemoryLimitInMB': context.memory_limit_in_mb, 'MemoryUsedInMB': math.floor(used) } ) else: # nothing to do check back later Timer(.5, memory_warning, (config, context)).start()
python
def memory_warning(config, context): """Determines when memory usage is nearing it's max.""" used = psutil.Process(os.getpid()).memory_info().rss / 1048576 limit = float(context.memory_limit_in_mb) p = used / limit memory_threshold = config.get('memory_warning_threshold') if p >= memory_threshold: config['raven_client'].captureMessage( 'Memory Usage Warning', level='warning', extra={ 'MemoryLimitInMB': context.memory_limit_in_mb, 'MemoryUsedInMB': math.floor(used) } ) else: # nothing to do check back later Timer(.5, memory_warning, (config, context)).start()
[ "def", "memory_warning", "(", "config", ",", "context", ")", ":", "used", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", ".", "memory_info", "(", ")", ".", "rss", "/", "1048576", "limit", "=", "float", "(", "context", ".", "memory_limit_in_mb", ")", "p", "=", "used", "/", "limit", "memory_threshold", "=", "config", ".", "get", "(", "'memory_warning_threshold'", ")", "if", "p", ">=", "memory_threshold", ":", "config", "[", "'raven_client'", "]", ".", "captureMessage", "(", "'Memory Usage Warning'", ",", "level", "=", "'warning'", ",", "extra", "=", "{", "'MemoryLimitInMB'", ":", "context", ".", "memory_limit_in_mb", ",", "'MemoryUsedInMB'", ":", "math", ".", "floor", "(", "used", ")", "}", ")", "else", ":", "# nothing to do check back later", "Timer", "(", ".5", ",", "memory_warning", ",", "(", "config", ",", "context", ")", ")", ".", "start", "(", ")" ]
Determines when memory usage is nearing it's max.
[ "Determines", "when", "memory", "usage", "is", "nearing", "it", "s", "max", "." ]
640d5cfcef6e69ea685ca13469cfca71adf0e78c
https://github.com/Netflix-Skunkworks/raven-python-lambda/blob/640d5cfcef6e69ea685ca13469cfca71adf0e78c/raven_python_lambda/__init__.py#L233-L252
train
Netflix-Skunkworks/raven-python-lambda
raven_python_lambda/__init__.py
install_timers
def install_timers(config, context): """Create the timers as specified by the plugin configuration.""" timers = [] if config.get('capture_timeout_warnings'): timeout_threshold = config.get('timeout_warning_threshold') # Schedule the warning at the user specified threshold given in percent. # ie: 0.50 of 30000 ms = 15000ms # Schedule the error a few milliseconds before the actual timeout happens. time_remaining = context.get_remaining_time_in_millis() / 1000 timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context))) timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config])) if config.get('capture_memory_warnings'): # Schedule the memory watch dog interval. Warning will re-schedule itself if necessary. timers.append(Timer(.5, memory_warning, (config, context))) for t in timers: t.start() return timers
python
def install_timers(config, context): """Create the timers as specified by the plugin configuration.""" timers = [] if config.get('capture_timeout_warnings'): timeout_threshold = config.get('timeout_warning_threshold') # Schedule the warning at the user specified threshold given in percent. # ie: 0.50 of 30000 ms = 15000ms # Schedule the error a few milliseconds before the actual timeout happens. time_remaining = context.get_remaining_time_in_millis() / 1000 timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context))) timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config])) if config.get('capture_memory_warnings'): # Schedule the memory watch dog interval. Warning will re-schedule itself if necessary. timers.append(Timer(.5, memory_warning, (config, context))) for t in timers: t.start() return timers
[ "def", "install_timers", "(", "config", ",", "context", ")", ":", "timers", "=", "[", "]", "if", "config", ".", "get", "(", "'capture_timeout_warnings'", ")", ":", "timeout_threshold", "=", "config", ".", "get", "(", "'timeout_warning_threshold'", ")", "# Schedule the warning at the user specified threshold given in percent.", "# ie: 0.50 of 30000 ms = 15000ms", "# Schedule the error a few milliseconds before the actual timeout happens.", "time_remaining", "=", "context", ".", "get_remaining_time_in_millis", "(", ")", "/", "1000", "timers", ".", "append", "(", "Timer", "(", "time_remaining", "*", "timeout_threshold", ",", "timeout_warning", ",", "(", "config", ",", "context", ")", ")", ")", "timers", ".", "append", "(", "Timer", "(", "max", "(", "time_remaining", "-", ".5", ",", "0", ")", ",", "timeout_error", ",", "[", "config", "]", ")", ")", "if", "config", ".", "get", "(", "'capture_memory_warnings'", ")", ":", "# Schedule the memory watch dog interval. Warning will re-schedule itself if necessary.", "timers", ".", "append", "(", "Timer", "(", ".5", ",", "memory_warning", ",", "(", "config", ",", "context", ")", ")", ")", "for", "t", "in", "timers", ":", "t", ".", "start", "(", ")", "return", "timers" ]
Create the timers as specified by the plugin configuration.
[ "Create", "the", "timers", "as", "specified", "by", "the", "plugin", "configuration", "." ]
640d5cfcef6e69ea685ca13469cfca71adf0e78c
https://github.com/Netflix-Skunkworks/raven-python-lambda/blob/640d5cfcef6e69ea685ca13469cfca71adf0e78c/raven_python_lambda/__init__.py#L255-L274
train
ellmetha/django-machina
machina/templatetags/forum_tags.py
recurseforumcontents
def recurseforumcontents(parser, token): """ Iterates over the content nodes and renders the contained forum block for each node. """ bits = token.contents.split() forums_contents_var = template.Variable(bits[1]) template_nodes = parser.parse(('endrecurseforumcontents',)) parser.delete_first_token() return RecurseTreeForumVisibilityContentNode(template_nodes, forums_contents_var)
python
def recurseforumcontents(parser, token): """ Iterates over the content nodes and renders the contained forum block for each node. """ bits = token.contents.split() forums_contents_var = template.Variable(bits[1]) template_nodes = parser.parse(('endrecurseforumcontents',)) parser.delete_first_token() return RecurseTreeForumVisibilityContentNode(template_nodes, forums_contents_var)
[ "def", "recurseforumcontents", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "forums_contents_var", "=", "template", ".", "Variable", "(", "bits", "[", "1", "]", ")", "template_nodes", "=", "parser", ".", "parse", "(", "(", "'endrecurseforumcontents'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "RecurseTreeForumVisibilityContentNode", "(", "template_nodes", ",", "forums_contents_var", ")" ]
Iterates over the content nodes and renders the contained forum block for each node.
[ "Iterates", "over", "the", "content", "nodes", "and", "renders", "the", "contained", "forum", "block", "for", "each", "node", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tags.py#L40-L48
train
ellmetha/django-machina
machina/templatetags/forum_tags.py
forum_list
def forum_list(context, forum_visibility_contents): """ Renders the considered forum list. This will render the given list of forums by respecting the order and the depth of each forum in the forums tree. Usage:: {% forum_list my_forums %} """ request = context.get('request') tracking_handler = TrackingHandler(request=request) data_dict = { 'forum_contents': forum_visibility_contents, 'unread_forums': tracking_handler.get_unread_forums_from_list( request.user, forum_visibility_contents.forums), 'user': request.user, 'request': request, } root_level = forum_visibility_contents.root_level if root_level is not None: data_dict['root_level'] = root_level data_dict['root_level_middle'] = root_level + 1 data_dict['root_level_sub'] = root_level + 2 return data_dict
python
def forum_list(context, forum_visibility_contents): """ Renders the considered forum list. This will render the given list of forums by respecting the order and the depth of each forum in the forums tree. Usage:: {% forum_list my_forums %} """ request = context.get('request') tracking_handler = TrackingHandler(request=request) data_dict = { 'forum_contents': forum_visibility_contents, 'unread_forums': tracking_handler.get_unread_forums_from_list( request.user, forum_visibility_contents.forums), 'user': request.user, 'request': request, } root_level = forum_visibility_contents.root_level if root_level is not None: data_dict['root_level'] = root_level data_dict['root_level_middle'] = root_level + 1 data_dict['root_level_sub'] = root_level + 2 return data_dict
[ "def", "forum_list", "(", "context", ",", "forum_visibility_contents", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ")", "tracking_handler", "=", "TrackingHandler", "(", "request", "=", "request", ")", "data_dict", "=", "{", "'forum_contents'", ":", "forum_visibility_contents", ",", "'unread_forums'", ":", "tracking_handler", ".", "get_unread_forums_from_list", "(", "request", ".", "user", ",", "forum_visibility_contents", ".", "forums", ")", ",", "'user'", ":", "request", ".", "user", ",", "'request'", ":", "request", ",", "}", "root_level", "=", "forum_visibility_contents", ".", "root_level", "if", "root_level", "is", "not", "None", ":", "data_dict", "[", "'root_level'", "]", "=", "root_level", "data_dict", "[", "'root_level_middle'", "]", "=", "root_level", "+", "1", "data_dict", "[", "'root_level_sub'", "]", "=", "root_level", "+", "2", "return", "data_dict" ]
Renders the considered forum list. This will render the given list of forums by respecting the order and the depth of each forum in the forums tree. Usage:: {% forum_list my_forums %}
[ "Renders", "the", "considered", "forum", "list", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tags.py#L52-L80
train
ellmetha/django-machina
machina/apps/forum_feeds/feeds.py
LastTopicsFeed.get_object
def get_object(self, request, *args, **kwargs): """ Handles the considered object. """ forum_pk = kwargs.get('forum_pk', None) descendants = kwargs.get('descendants', None) self.user = request.user if forum_pk: forum = get_object_or_404(Forum, pk=forum_pk) forums_qs = ( forum.get_descendants(include_self=True) if descendants else Forum.objects.filter(pk=forum_pk) ) self.forums = request.forum_permission_handler.get_readable_forums( forums_qs, request.user, ) else: self.forums = request.forum_permission_handler.get_readable_forums( Forum.objects.all(), request.user, )
python
def get_object(self, request, *args, **kwargs): """ Handles the considered object. """ forum_pk = kwargs.get('forum_pk', None) descendants = kwargs.get('descendants', None) self.user = request.user if forum_pk: forum = get_object_or_404(Forum, pk=forum_pk) forums_qs = ( forum.get_descendants(include_self=True) if descendants else Forum.objects.filter(pk=forum_pk) ) self.forums = request.forum_permission_handler.get_readable_forums( forums_qs, request.user, ) else: self.forums = request.forum_permission_handler.get_readable_forums( Forum.objects.all(), request.user, )
[ "def", "get_object", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "forum_pk", "=", "kwargs", ".", "get", "(", "'forum_pk'", ",", "None", ")", "descendants", "=", "kwargs", ".", "get", "(", "'descendants'", ",", "None", ")", "self", ".", "user", "=", "request", ".", "user", "if", "forum_pk", ":", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_pk", ")", "forums_qs", "=", "(", "forum", ".", "get_descendants", "(", "include_self", "=", "True", ")", "if", "descendants", "else", "Forum", ".", "objects", ".", "filter", "(", "pk", "=", "forum_pk", ")", ")", "self", ".", "forums", "=", "request", ".", "forum_permission_handler", ".", "get_readable_forums", "(", "forums_qs", ",", "request", ".", "user", ",", ")", "else", ":", "self", ".", "forums", "=", "request", ".", "forum_permission_handler", ".", "get_readable_forums", "(", "Forum", ".", "objects", ".", "all", "(", ")", ",", "request", ".", "user", ",", ")" ]
Handles the considered object.
[ "Handles", "the", "considered", "object", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L34-L52
train
ellmetha/django-machina
machina/apps/forum_feeds/feeds.py
LastTopicsFeed.items
def items(self): """ Returns the items to include into the feed. """ return Topic.objects.filter(forum__in=self.forums, approved=True).order_by('-last_post_on')
python
def items(self): """ Returns the items to include into the feed. """ return Topic.objects.filter(forum__in=self.forums, approved=True).order_by('-last_post_on')
[ "def", "items", "(", "self", ")", ":", "return", "Topic", ".", "objects", ".", "filter", "(", "forum__in", "=", "self", ".", "forums", ",", "approved", "=", "True", ")", ".", "order_by", "(", "'-last_post_on'", ")" ]
Returns the items to include into the feed.
[ "Returns", "the", "items", "to", "include", "into", "the", "feed", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L54-L56
train
ellmetha/django-machina
machina/apps/forum_feeds/feeds.py
LastTopicsFeed.item_link
def item_link(self, item): """ Generates a link for a specific item of the feed. """ return reverse_lazy( 'forum_conversation:topic', kwargs={ 'forum_slug': item.forum.slug, 'forum_pk': item.forum.pk, 'slug': item.slug, 'pk': item.id, }, )
python
def item_link(self, item): """ Generates a link for a specific item of the feed. """ return reverse_lazy( 'forum_conversation:topic', kwargs={ 'forum_slug': item.forum.slug, 'forum_pk': item.forum.pk, 'slug': item.slug, 'pk': item.id, }, )
[ "def", "item_link", "(", "self", ",", "item", ")", ":", "return", "reverse_lazy", "(", "'forum_conversation:topic'", ",", "kwargs", "=", "{", "'forum_slug'", ":", "item", ".", "forum", ".", "slug", ",", "'forum_pk'", ":", "item", ".", "forum", ".", "pk", ",", "'slug'", ":", "item", ".", "slug", ",", "'pk'", ":", "item", ".", "id", ",", "}", ",", ")" ]
Generates a link for a specific item of the feed.
[ "Generates", "a", "link", "for", "a", "specific", "item", "of", "the", "feed", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L58-L68
train
ellmetha/django-machina
machina/templatetags/forum_conversation_tags.py
topic_pages_inline_list
def topic_pages_inline_list(topic): """ This will render an inline pagination for the posts related to the given topic. Usage:: {% topic_pages_inline_list my_topic %} """ data_dict = { 'topic': topic, } pages_number = ((topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE) + 1 if pages_number > 5: data_dict['first_pages'] = range(1, 5) data_dict['last_page'] = pages_number elif pages_number > 1: data_dict['first_pages'] = range(1, pages_number + 1) return data_dict
python
def topic_pages_inline_list(topic): """ This will render an inline pagination for the posts related to the given topic. Usage:: {% topic_pages_inline_list my_topic %} """ data_dict = { 'topic': topic, } pages_number = ((topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE) + 1 if pages_number > 5: data_dict['first_pages'] = range(1, 5) data_dict['last_page'] = pages_number elif pages_number > 1: data_dict['first_pages'] = range(1, pages_number + 1) return data_dict
[ "def", "topic_pages_inline_list", "(", "topic", ")", ":", "data_dict", "=", "{", "'topic'", ":", "topic", ",", "}", "pages_number", "=", "(", "(", "topic", ".", "posts_count", "-", "1", ")", "//", "machina_settings", ".", "TOPIC_POSTS_NUMBER_PER_PAGE", ")", "+", "1", "if", "pages_number", ">", "5", ":", "data_dict", "[", "'first_pages'", "]", "=", "range", "(", "1", ",", "5", ")", "data_dict", "[", "'last_page'", "]", "=", "pages_number", "elif", "pages_number", ">", "1", ":", "data_dict", "[", "'first_pages'", "]", "=", "range", "(", "1", ",", "pages_number", "+", "1", ")", "return", "data_dict" ]
This will render an inline pagination for the posts related to the given topic. Usage:: {% topic_pages_inline_list my_topic %}
[ "This", "will", "render", "an", "inline", "pagination", "for", "the", "posts", "related", "to", "the", "given", "topic", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_conversation_tags.py#L22-L41
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.get_urls
def get_urls(self): """ Returns the URLs associated with the admin abstraction. """ urls = super().get_urls() forum_admin_urls = [ url( r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$', self.admin_site.admin_view(self.moveforum_view), name='forum_forum_move', ), url( r'^edit-global-permissions/$', self.admin_site.admin_view(self.editpermissions_index_view), name='forum_forum_editpermission_index', ), url( r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_user_view), name='forum_forum_editpermission_user', ), url( r'^edit-global-permissions/user/anonymous/$', self.admin_site.admin_view(self.editpermissions_anonymous_user_view), name='forum_forum_editpermission_anonymous_user', ), url( r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_group_view), name='forum_forum_editpermission_group', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/$', self.admin_site.admin_view(self.editpermissions_index_view), name='forum_forum_editpermission_index', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_user_view), name='forum_forum_editpermission_user', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$', self.admin_site.admin_view(self.editpermissions_anonymous_user_view), name='forum_forum_editpermission_anonymous_user', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_group_view), name='forum_forum_editpermission_group', ), ] return forum_admin_urls + urls
python
def get_urls(self): """ Returns the URLs associated with the admin abstraction. """ urls = super().get_urls() forum_admin_urls = [ url( r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$', self.admin_site.admin_view(self.moveforum_view), name='forum_forum_move', ), url( r'^edit-global-permissions/$', self.admin_site.admin_view(self.editpermissions_index_view), name='forum_forum_editpermission_index', ), url( r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_user_view), name='forum_forum_editpermission_user', ), url( r'^edit-global-permissions/user/anonymous/$', self.admin_site.admin_view(self.editpermissions_anonymous_user_view), name='forum_forum_editpermission_anonymous_user', ), url( r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_group_view), name='forum_forum_editpermission_group', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/$', self.admin_site.admin_view(self.editpermissions_index_view), name='forum_forum_editpermission_index', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_user_view), name='forum_forum_editpermission_user', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$', self.admin_site.admin_view(self.editpermissions_anonymous_user_view), name='forum_forum_editpermission_anonymous_user', ), url( r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$', self.admin_site.admin_view(self.editpermissions_group_view), name='forum_forum_editpermission_group', ), ] return forum_admin_urls + urls
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", ")", ".", "get_urls", "(", ")", "forum_admin_urls", "=", "[", "url", "(", "r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "moveforum_view", ")", ",", "name", "=", "'forum_forum_move'", ",", ")", ",", "url", "(", "r'^edit-global-permissions/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_index_view", ")", ",", "name", "=", "'forum_forum_editpermission_index'", ",", ")", ",", "url", "(", "r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_user_view", ")", ",", "name", "=", "'forum_forum_editpermission_user'", ",", ")", ",", "url", "(", "r'^edit-global-permissions/user/anonymous/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_anonymous_user_view", ")", ",", "name", "=", "'forum_forum_editpermission_anonymous_user'", ",", ")", ",", "url", "(", "r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_group_view", ")", ",", "name", "=", "'forum_forum_editpermission_group'", ",", ")", ",", "url", "(", "r'^(?P<forum_id>[0-9]+)/edit-permissions/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_index_view", ")", ",", "name", "=", "'forum_forum_editpermission_index'", ",", ")", ",", "url", "(", "r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_user_view", ")", ",", "name", "=", "'forum_forum_editpermission_user'", ",", ")", ",", "url", "(", "r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_anonymous_user_view", ")", ",", "name", "=", "'forum_forum_editpermission_anonymous_user'", ",", ")", ",", "url", "(", "r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "editpermissions_group_view", ")", ",", "name", "=", "'forum_forum_editpermission_group'", ",", ")", ",", "]", "return", "forum_admin_urls", "+", "urls" ]
Returns the URLs associated with the admin abstraction.
[ "Returns", "the", "URLs", "associated", "with", "the", "admin", "abstraction", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L66-L116
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.get_forum_perms_base_context
def get_forum_perms_base_context(self, request, obj=None): """ Returns the context to provide to the template for permissions contents. """ context = { 'adminform': {'model_admin': self}, 'media': self.media, 'object': obj, 'app_label': self.model._meta.app_label, 'opts': self.model._meta, 'has_change_permission': self.has_change_permission(request, obj), } try: context.update(self.admin_site.each_context(request)) except TypeError: # pragma: no cover # Django 1.7 compatibility context.update(self.admin_site.each_context()) except AttributeError: # pragma: no cover pass return context
python
def get_forum_perms_base_context(self, request, obj=None): """ Returns the context to provide to the template for permissions contents. """ context = { 'adminform': {'model_admin': self}, 'media': self.media, 'object': obj, 'app_label': self.model._meta.app_label, 'opts': self.model._meta, 'has_change_permission': self.has_change_permission(request, obj), } try: context.update(self.admin_site.each_context(request)) except TypeError: # pragma: no cover # Django 1.7 compatibility context.update(self.admin_site.each_context()) except AttributeError: # pragma: no cover pass return context
[ "def", "get_forum_perms_base_context", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "context", "=", "{", "'adminform'", ":", "{", "'model_admin'", ":", "self", "}", ",", "'media'", ":", "self", ".", "media", ",", "'object'", ":", "obj", ",", "'app_label'", ":", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "'opts'", ":", "self", ".", "model", ".", "_meta", ",", "'has_change_permission'", ":", "self", ".", "has_change_permission", "(", "request", ",", "obj", ")", ",", "}", "try", ":", "context", ".", "update", "(", "self", ".", "admin_site", ".", "each_context", "(", "request", ")", ")", "except", "TypeError", ":", "# pragma: no cover", "# Django 1.7 compatibility", "context", ".", "update", "(", "self", ".", "admin_site", ".", "each_context", "(", ")", ")", "except", "AttributeError", ":", "# pragma: no cover", "pass", "return", "context" ]
Returns the context to provide to the template for permissions contents.
[ "Returns", "the", "context", "to", "provide", "to", "the", "template", "for", "permissions", "contents", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L118-L135
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.moveforum_view
def moveforum_view(self, request, forum_id, direction): """ Moves the given forum toward the requested direction. """ forum = get_object_or_404(Forum, pk=forum_id) # Fetch the target target, position = None, None if direction == 'up': target, position = forum.get_previous_sibling(), 'left' elif direction == 'down': target, position = forum.get_next_sibling(), 'right' # Do the move try: assert target is not None forum.move_to(target, position) except (InvalidMove, AssertionError): pass self.message_user(request, _("'{}' forum successfully moved").format(forum.name)) return HttpResponseRedirect(reverse('admin:forum_forum_changelist'))
python
def moveforum_view(self, request, forum_id, direction): """ Moves the given forum toward the requested direction. """ forum = get_object_or_404(Forum, pk=forum_id) # Fetch the target target, position = None, None if direction == 'up': target, position = forum.get_previous_sibling(), 'left' elif direction == 'down': target, position = forum.get_next_sibling(), 'right' # Do the move try: assert target is not None forum.move_to(target, position) except (InvalidMove, AssertionError): pass self.message_user(request, _("'{}' forum successfully moved").format(forum.name)) return HttpResponseRedirect(reverse('admin:forum_forum_changelist'))
[ "def", "moveforum_view", "(", "self", ",", "request", ",", "forum_id", ",", "direction", ")", ":", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_id", ")", "# Fetch the target", "target", ",", "position", "=", "None", ",", "None", "if", "direction", "==", "'up'", ":", "target", ",", "position", "=", "forum", ".", "get_previous_sibling", "(", ")", ",", "'left'", "elif", "direction", "==", "'down'", ":", "target", ",", "position", "=", "forum", ".", "get_next_sibling", "(", ")", ",", "'right'", "# Do the move", "try", ":", "assert", "target", "is", "not", "None", "forum", ".", "move_to", "(", "target", ",", "position", ")", "except", "(", "InvalidMove", ",", "AssertionError", ")", ":", "pass", "self", ".", "message_user", "(", "request", ",", "_", "(", "\"'{}' forum successfully moved\"", ")", ".", "format", "(", "forum", ".", "name", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'admin:forum_forum_changelist'", ")", ")" ]
Moves the given forum toward the requested direction.
[ "Moves", "the", "given", "forum", "toward", "the", "requested", "direction", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L137-L155
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.editpermissions_index_view
def editpermissions_index_view(self, request, forum_id=None): """ Allows to select how to edit forum permissions. The view displays a form to select a user or a group in order to edit its permissions for the considered forum. """ forum = get_object_or_404(Forum, pk=forum_id) if forum_id \ else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = _('Forum permissions') if forum else _('Global forum permissions') # Handles "copy permission from" form permissions_copied = False if forum and request.method == 'POST': forum_form = PickForumForm(request.POST) if forum_form.is_valid() and forum_form.cleaned_data['forum']: self._copy_forum_permissions(forum_form.cleaned_data['forum'], forum) self.message_user(request, _('Permissions successfully copied')) permissions_copied = True context['forum_form'] = forum_form elif forum: context['forum_form'] = PickForumForm() # Handles user or group selection if request.method == 'POST' and not permissions_copied: user_form = PickUserForm(request.POST, admin_site=self.admin_site) group_form = PickGroupForm(request.POST, admin_site=self.admin_site) if user_form.is_valid() and group_form.is_valid(): user = user_form.cleaned_data.get('user', None) if user_form.cleaned_data else None anonymous_user = ( user_form.cleaned_data.get('anonymous_user', None) if user_form.cleaned_data else None ) group = ( group_form.cleaned_data.get('group', None) if group_form.cleaned_data else None ) if not user and not anonymous_user and not group: user_form._errors[NON_FIELD_ERRORS] = user_form.error_class( [_('Choose either a user ID, a group ID or the anonymous user'), ]) elif user: # Redirect to user url_kwargs = ( {'forum_id': forum.id, 'user_id': user.id} if forum else {'user_id': user.id} ) return redirect( reverse('admin:forum_forum_editpermission_user', kwargs=url_kwargs), ) elif anonymous_user: # Redirect to anonymous user url_kwargs = {'forum_id': forum.id} if forum else {} return redirect( reverse( 'admin:forum_forum_editpermission_anonymous_user', kwargs=url_kwargs, ), ) elif group: # Redirect to group url_kwargs = ( {'forum_id': forum.id, 'group_id': group.id} if forum else {'group_id': group.id} ) return redirect( reverse('admin:forum_forum_editpermission_group', kwargs=url_kwargs), ) context['user_errors'] = helpers.AdminErrorList(user_form, []) context['group_errors'] = helpers.AdminErrorList(group_form, []) else: user_form = PickUserForm(admin_site=self.admin_site) group_form = PickGroupForm(admin_site=self.admin_site) context['user_form'] = user_form context['group_form'] = group_form return render(request, self.editpermissions_index_view_template_name, context)
python
def editpermissions_index_view(self, request, forum_id=None): """ Allows to select how to edit forum permissions. The view displays a form to select a user or a group in order to edit its permissions for the considered forum. """ forum = get_object_or_404(Forum, pk=forum_id) if forum_id \ else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = _('Forum permissions') if forum else _('Global forum permissions') # Handles "copy permission from" form permissions_copied = False if forum and request.method == 'POST': forum_form = PickForumForm(request.POST) if forum_form.is_valid() and forum_form.cleaned_data['forum']: self._copy_forum_permissions(forum_form.cleaned_data['forum'], forum) self.message_user(request, _('Permissions successfully copied')) permissions_copied = True context['forum_form'] = forum_form elif forum: context['forum_form'] = PickForumForm() # Handles user or group selection if request.method == 'POST' and not permissions_copied: user_form = PickUserForm(request.POST, admin_site=self.admin_site) group_form = PickGroupForm(request.POST, admin_site=self.admin_site) if user_form.is_valid() and group_form.is_valid(): user = user_form.cleaned_data.get('user', None) if user_form.cleaned_data else None anonymous_user = ( user_form.cleaned_data.get('anonymous_user', None) if user_form.cleaned_data else None ) group = ( group_form.cleaned_data.get('group', None) if group_form.cleaned_data else None ) if not user and not anonymous_user and not group: user_form._errors[NON_FIELD_ERRORS] = user_form.error_class( [_('Choose either a user ID, a group ID or the anonymous user'), ]) elif user: # Redirect to user url_kwargs = ( {'forum_id': forum.id, 'user_id': user.id} if forum else {'user_id': user.id} ) return redirect( reverse('admin:forum_forum_editpermission_user', kwargs=url_kwargs), ) elif anonymous_user: # Redirect to anonymous user url_kwargs = {'forum_id': forum.id} if forum else {} return redirect( reverse( 'admin:forum_forum_editpermission_anonymous_user', kwargs=url_kwargs, ), ) elif group: # Redirect to group url_kwargs = ( {'forum_id': forum.id, 'group_id': group.id} if forum else {'group_id': group.id} ) return redirect( reverse('admin:forum_forum_editpermission_group', kwargs=url_kwargs), ) context['user_errors'] = helpers.AdminErrorList(user_form, []) context['group_errors'] = helpers.AdminErrorList(group_form, []) else: user_form = PickUserForm(admin_site=self.admin_site) group_form = PickGroupForm(admin_site=self.admin_site) context['user_form'] = user_form context['group_form'] = group_form return render(request, self.editpermissions_index_view_template_name, context)
[ "def", "editpermissions_index_view", "(", "self", ",", "request", ",", "forum_id", "=", "None", ")", ":", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_id", ")", "if", "forum_id", "else", "None", "# Set up the context", "context", "=", "self", ".", "get_forum_perms_base_context", "(", "request", ",", "forum", ")", "context", "[", "'forum'", "]", "=", "forum", "context", "[", "'title'", "]", "=", "_", "(", "'Forum permissions'", ")", "if", "forum", "else", "_", "(", "'Global forum permissions'", ")", "# Handles \"copy permission from\" form", "permissions_copied", "=", "False", "if", "forum", "and", "request", ".", "method", "==", "'POST'", ":", "forum_form", "=", "PickForumForm", "(", "request", ".", "POST", ")", "if", "forum_form", ".", "is_valid", "(", ")", "and", "forum_form", ".", "cleaned_data", "[", "'forum'", "]", ":", "self", ".", "_copy_forum_permissions", "(", "forum_form", ".", "cleaned_data", "[", "'forum'", "]", ",", "forum", ")", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Permissions successfully copied'", ")", ")", "permissions_copied", "=", "True", "context", "[", "'forum_form'", "]", "=", "forum_form", "elif", "forum", ":", "context", "[", "'forum_form'", "]", "=", "PickForumForm", "(", ")", "# Handles user or group selection", "if", "request", ".", "method", "==", "'POST'", "and", "not", "permissions_copied", ":", "user_form", "=", "PickUserForm", "(", "request", ".", "POST", ",", "admin_site", "=", "self", ".", "admin_site", ")", "group_form", "=", "PickGroupForm", "(", "request", ".", "POST", ",", "admin_site", "=", "self", ".", "admin_site", ")", "if", "user_form", ".", "is_valid", "(", ")", "and", "group_form", ".", "is_valid", "(", ")", ":", "user", "=", "user_form", ".", "cleaned_data", ".", "get", "(", "'user'", ",", "None", ")", "if", "user_form", ".", "cleaned_data", "else", "None", "anonymous_user", "=", "(", "user_form", ".", "cleaned_data", ".", "get", "(", "'anonymous_user'", ",", "None", ")", "if", "user_form", ".", "cleaned_data", "else", "None", ")", "group", "=", "(", "group_form", ".", "cleaned_data", ".", "get", "(", "'group'", ",", "None", ")", "if", "group_form", ".", "cleaned_data", "else", "None", ")", "if", "not", "user", "and", "not", "anonymous_user", "and", "not", "group", ":", "user_form", ".", "_errors", "[", "NON_FIELD_ERRORS", "]", "=", "user_form", ".", "error_class", "(", "[", "_", "(", "'Choose either a user ID, a group ID or the anonymous user'", ")", ",", "]", ")", "elif", "user", ":", "# Redirect to user", "url_kwargs", "=", "(", "{", "'forum_id'", ":", "forum", ".", "id", ",", "'user_id'", ":", "user", ".", "id", "}", "if", "forum", "else", "{", "'user_id'", ":", "user", ".", "id", "}", ")", "return", "redirect", "(", "reverse", "(", "'admin:forum_forum_editpermission_user'", ",", "kwargs", "=", "url_kwargs", ")", ",", ")", "elif", "anonymous_user", ":", "# Redirect to anonymous user", "url_kwargs", "=", "{", "'forum_id'", ":", "forum", ".", "id", "}", "if", "forum", "else", "{", "}", "return", "redirect", "(", "reverse", "(", "'admin:forum_forum_editpermission_anonymous_user'", ",", "kwargs", "=", "url_kwargs", ",", ")", ",", ")", "elif", "group", ":", "# Redirect to group", "url_kwargs", "=", "(", "{", "'forum_id'", ":", "forum", ".", "id", ",", "'group_id'", ":", "group", ".", "id", "}", "if", "forum", "else", "{", "'group_id'", ":", "group", ".", "id", "}", ")", "return", "redirect", "(", "reverse", "(", "'admin:forum_forum_editpermission_group'", ",", "kwargs", "=", "url_kwargs", ")", ",", ")", "context", "[", "'user_errors'", "]", "=", "helpers", ".", "AdminErrorList", "(", "user_form", ",", "[", "]", ")", "context", "[", "'group_errors'", "]", "=", "helpers", ".", "AdminErrorList", "(", "group_form", ",", "[", "]", ")", "else", ":", "user_form", "=", "PickUserForm", "(", "admin_site", "=", "self", ".", "admin_site", ")", "group_form", "=", "PickGroupForm", "(", "admin_site", "=", "self", ".", "admin_site", ")", "context", "[", "'user_form'", "]", "=", "user_form", "context", "[", "'group_form'", "]", "=", "group_form", "return", "render", "(", "request", ",", "self", ".", "editpermissions_index_view_template_name", ",", "context", ")" ]
Allows to select how to edit forum permissions. The view displays a form to select a user or a group in order to edit its permissions for the considered forum.
[ "Allows", "to", "select", "how", "to", "edit", "forum", "permissions", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L157-L240
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.editpermissions_user_view
def editpermissions_user_view(self, request, user_id, forum_id=None): """ Allows to edit user permissions for the considered forum. The view displays a form to define which permissions are granted for the given user for the considered forum. """ user_model = get_user_model() user = get_object_or_404(user_model, pk=user_id) forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), user) context['form'] = self._get_permissions_form( request, UserForumPermission, {'forum': forum, 'user': user}, ) return render(request, self.editpermissions_user_view_template_name, context)
python
def editpermissions_user_view(self, request, user_id, forum_id=None): """ Allows to edit user permissions for the considered forum. The view displays a form to define which permissions are granted for the given user for the considered forum. """ user_model = get_user_model() user = get_object_or_404(user_model, pk=user_id) forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), user) context['form'] = self._get_permissions_form( request, UserForumPermission, {'forum': forum, 'user': user}, ) return render(request, self.editpermissions_user_view_template_name, context)
[ "def", "editpermissions_user_view", "(", "self", ",", "request", ",", "user_id", ",", "forum_id", "=", "None", ")", ":", "user_model", "=", "get_user_model", "(", ")", "user", "=", "get_object_or_404", "(", "user_model", ",", "pk", "=", "user_id", ")", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_id", ")", "if", "forum_id", "else", "None", "# Set up the context", "context", "=", "self", ".", "get_forum_perms_base_context", "(", "request", ",", "forum", ")", "context", "[", "'forum'", "]", "=", "forum", "context", "[", "'title'", "]", "=", "'{} - {}'", ".", "format", "(", "_", "(", "'Forum permissions'", ")", ",", "user", ")", "context", "[", "'form'", "]", "=", "self", ".", "_get_permissions_form", "(", "request", ",", "UserForumPermission", ",", "{", "'forum'", ":", "forum", ",", "'user'", ":", "user", "}", ",", ")", "return", "render", "(", "request", ",", "self", ".", "editpermissions_user_view_template_name", ",", "context", ")" ]
Allows to edit user permissions for the considered forum. The view displays a form to define which permissions are granted for the given user for the considered forum.
[ "Allows", "to", "edit", "user", "permissions", "for", "the", "considered", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L242-L261
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.editpermissions_anonymous_user_view
def editpermissions_anonymous_user_view(self, request, forum_id=None): """ Allows to edit anonymous user permissions for the considered forum. The view displays a form to define which permissions are granted for the anonymous user for the considered forum. """ forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user')) context['form'] = self._get_permissions_form( request, UserForumPermission, {'forum': forum, 'anonymous_user': True}, ) return render(request, self.editpermissions_anonymous_user_view_template_name, context)
python
def editpermissions_anonymous_user_view(self, request, forum_id=None): """ Allows to edit anonymous user permissions for the considered forum. The view displays a form to define which permissions are granted for the anonymous user for the considered forum. """ forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user')) context['form'] = self._get_permissions_form( request, UserForumPermission, {'forum': forum, 'anonymous_user': True}, ) return render(request, self.editpermissions_anonymous_user_view_template_name, context)
[ "def", "editpermissions_anonymous_user_view", "(", "self", ",", "request", ",", "forum_id", "=", "None", ")", ":", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_id", ")", "if", "forum_id", "else", "None", "# Set up the context", "context", "=", "self", ".", "get_forum_perms_base_context", "(", "request", ",", "forum", ")", "context", "[", "'forum'", "]", "=", "forum", "context", "[", "'title'", "]", "=", "'{} - {}'", ".", "format", "(", "_", "(", "'Forum permissions'", ")", ",", "_", "(", "'Anonymous user'", ")", ")", "context", "[", "'form'", "]", "=", "self", ".", "_get_permissions_form", "(", "request", ",", "UserForumPermission", ",", "{", "'forum'", ":", "forum", ",", "'anonymous_user'", ":", "True", "}", ",", ")", "return", "render", "(", "request", ",", "self", ".", "editpermissions_anonymous_user_view_template_name", ",", "context", ")" ]
Allows to edit anonymous user permissions for the considered forum. The view displays a form to define which permissions are granted for the anonymous user for the considered forum.
[ "Allows", "to", "edit", "anonymous", "user", "permissions", "for", "the", "considered", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L263-L280
train
ellmetha/django-machina
machina/apps/forum/admin.py
ForumAdmin.editpermissions_group_view
def editpermissions_group_view(self, request, group_id, forum_id=None): """ Allows to edit group permissions for the considered forum. The view displays a form to define which permissions are granted for the given group for the considered forum. """ group = get_object_or_404(Group, pk=group_id) forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), group) context['form'] = self._get_permissions_form( request, GroupForumPermission, {'forum': forum, 'group': group}, ) return render(request, self.editpermissions_group_view_template_name, context)
python
def editpermissions_group_view(self, request, group_id, forum_id=None): """ Allows to edit group permissions for the considered forum. The view displays a form to define which permissions are granted for the given group for the considered forum. """ group = get_object_or_404(Group, pk=group_id) forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None # Set up the context context = self.get_forum_perms_base_context(request, forum) context['forum'] = forum context['title'] = '{} - {}'.format(_('Forum permissions'), group) context['form'] = self._get_permissions_form( request, GroupForumPermission, {'forum': forum, 'group': group}, ) return render(request, self.editpermissions_group_view_template_name, context)
[ "def", "editpermissions_group_view", "(", "self", ",", "request", ",", "group_id", ",", "forum_id", "=", "None", ")", ":", "group", "=", "get_object_or_404", "(", "Group", ",", "pk", "=", "group_id", ")", "forum", "=", "get_object_or_404", "(", "Forum", ",", "pk", "=", "forum_id", ")", "if", "forum_id", "else", "None", "# Set up the context", "context", "=", "self", ".", "get_forum_perms_base_context", "(", "request", ",", "forum", ")", "context", "[", "'forum'", "]", "=", "forum", "context", "[", "'title'", "]", "=", "'{} - {}'", ".", "format", "(", "_", "(", "'Forum permissions'", ")", ",", "group", ")", "context", "[", "'form'", "]", "=", "self", ".", "_get_permissions_form", "(", "request", ",", "GroupForumPermission", ",", "{", "'forum'", ":", "forum", ",", "'group'", ":", "group", "}", ",", ")", "return", "render", "(", "request", ",", "self", ".", "editpermissions_group_view_template_name", ",", "context", ")" ]
Allows to edit group permissions for the considered forum. The view displays a form to define which permissions are granted for the given group for the considered forum.
[ "Allows", "to", "edit", "group", "permissions", "for", "the", "considered", "forum", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L282-L300
train
ellmetha/django-machina
machina/templatetags/forum_permission_tags.py
get_permission
def get_permission(context, method, *args, **kwargs): """ This will return a boolean indicating if the considered permission is granted for the passed user. Usage:: {% get_permission 'can_access_moderation_panel' request.user as var %} """ request = context.get('request', None) perm_handler = request.forum_permission_handler if request else PermissionHandler() allowed_methods = inspect.getmembers(perm_handler, predicate=inspect.ismethod) allowed_method_names = [a[0] for a in allowed_methods if not a[0].startswith('_')] if method not in allowed_method_names: raise template.TemplateSyntaxError( 'Only the following methods are allowed through ' 'this templatetag: {}'.format(allowed_method_names)) perm_method = getattr(perm_handler, method) return perm_method(*args, **kwargs)
python
def get_permission(context, method, *args, **kwargs): """ This will return a boolean indicating if the considered permission is granted for the passed user. Usage:: {% get_permission 'can_access_moderation_panel' request.user as var %} """ request = context.get('request', None) perm_handler = request.forum_permission_handler if request else PermissionHandler() allowed_methods = inspect.getmembers(perm_handler, predicate=inspect.ismethod) allowed_method_names = [a[0] for a in allowed_methods if not a[0].startswith('_')] if method not in allowed_method_names: raise template.TemplateSyntaxError( 'Only the following methods are allowed through ' 'this templatetag: {}'.format(allowed_method_names)) perm_method = getattr(perm_handler, method) return perm_method(*args, **kwargs)
[ "def", "get_permission", "(", "context", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ",", "None", ")", "perm_handler", "=", "request", ".", "forum_permission_handler", "if", "request", "else", "PermissionHandler", "(", ")", "allowed_methods", "=", "inspect", ".", "getmembers", "(", "perm_handler", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "allowed_method_names", "=", "[", "a", "[", "0", "]", "for", "a", "in", "allowed_methods", "if", "not", "a", "[", "0", "]", ".", "startswith", "(", "'_'", ")", "]", "if", "method", "not", "in", "allowed_method_names", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'Only the following methods are allowed through '", "'this templatetag: {}'", ".", "format", "(", "allowed_method_names", ")", ")", "perm_method", "=", "getattr", "(", "perm_handler", ",", "method", ")", "return", "perm_method", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
This will return a boolean indicating if the considered permission is granted for the passed user. Usage:: {% get_permission 'can_access_moderation_panel' request.user as var %}
[ "This", "will", "return", "a", "boolean", "indicating", "if", "the", "considered", "permission", "is", "granted", "for", "the", "passed", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_permission_tags.py#L14-L35
train
ellmetha/django-machina
machina/apps/forum_conversation/forum_polls/forms.py
BaseTopicPollOptionFormset.total_form_count
def total_form_count(self): """ This rewrite of total_form_count allows to add an empty form to the formset only when no initial data is provided. """ total_forms = super().total_form_count() if not self.data and not self.files and self.initial_form_count() > 0: total_forms -= self.extra return total_forms
python
def total_form_count(self): """ This rewrite of total_form_count allows to add an empty form to the formset only when no initial data is provided. """ total_forms = super().total_form_count() if not self.data and not self.files and self.initial_form_count() > 0: total_forms -= self.extra return total_forms
[ "def", "total_form_count", "(", "self", ")", ":", "total_forms", "=", "super", "(", ")", ".", "total_form_count", "(", ")", "if", "not", "self", ".", "data", "and", "not", "self", ".", "files", "and", "self", ".", "initial_form_count", "(", ")", ">", "0", ":", "total_forms", "-=", "self", ".", "extra", "return", "total_forms" ]
This rewrite of total_form_count allows to add an empty form to the formset only when no initial data is provided.
[ "This", "rewrite", "of", "total_form_count", "allows", "to", "add", "an", "empty", "form", "to", "the", "formset", "only", "when", "no", "initial", "data", "is", "provided", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/forms.py#L52-L60
train
ellmetha/django-machina
machina/core/loading.py
get_classes
def get_classes(module_label, classnames): """ Imports a set of classes from a given module. Usage:: get_classes('forum.models', ['Forum', 'ForumReadTrack', ]) """ app_label = module_label.split('.')[0] app_module_path = _get_app_module_path(module_label) if not app_module_path: raise AppNotFoundError('No app found matching \'{}\''.format(module_label)) # Determines the full module path by appending the module label # to the base package path of the considered application. module_path = app_module_path if '.' in app_module_path: base_package = app_module_path.rsplit('.' + app_label, 1)[0] module_path = '{}.{}'.format(base_package, module_label) # Try to import this module from the related app that is specified # in the Django settings. local_imported_module = _import_module(module_path, classnames) # If the module we tried to import is not located inside the machina # vanilla apps, try to import it from the corresponding machina app. machina_imported_module = None if not app_module_path.startswith('machina.apps'): machina_imported_module = _import_module( '{}.{}'.format('machina.apps', module_label), classnames, ) if local_imported_module is None and machina_imported_module is None: raise AppNotFoundError('Error importing \'{}\''.format(module_path)) # Any local module is prioritized over the corresponding machina module imported_modules = [ m for m in (local_imported_module, machina_imported_module) if m is not None ] return _pick_up_classes(imported_modules, classnames)
python
def get_classes(module_label, classnames): """ Imports a set of classes from a given module. Usage:: get_classes('forum.models', ['Forum', 'ForumReadTrack', ]) """ app_label = module_label.split('.')[0] app_module_path = _get_app_module_path(module_label) if not app_module_path: raise AppNotFoundError('No app found matching \'{}\''.format(module_label)) # Determines the full module path by appending the module label # to the base package path of the considered application. module_path = app_module_path if '.' in app_module_path: base_package = app_module_path.rsplit('.' + app_label, 1)[0] module_path = '{}.{}'.format(base_package, module_label) # Try to import this module from the related app that is specified # in the Django settings. local_imported_module = _import_module(module_path, classnames) # If the module we tried to import is not located inside the machina # vanilla apps, try to import it from the corresponding machina app. machina_imported_module = None if not app_module_path.startswith('machina.apps'): machina_imported_module = _import_module( '{}.{}'.format('machina.apps', module_label), classnames, ) if local_imported_module is None and machina_imported_module is None: raise AppNotFoundError('Error importing \'{}\''.format(module_path)) # Any local module is prioritized over the corresponding machina module imported_modules = [ m for m in (local_imported_module, machina_imported_module) if m is not None ] return _pick_up_classes(imported_modules, classnames)
[ "def", "get_classes", "(", "module_label", ",", "classnames", ")", ":", "app_label", "=", "module_label", ".", "split", "(", "'.'", ")", "[", "0", "]", "app_module_path", "=", "_get_app_module_path", "(", "module_label", ")", "if", "not", "app_module_path", ":", "raise", "AppNotFoundError", "(", "'No app found matching \\'{}\\''", ".", "format", "(", "module_label", ")", ")", "# Determines the full module path by appending the module label", "# to the base package path of the considered application.", "module_path", "=", "app_module_path", "if", "'.'", "in", "app_module_path", ":", "base_package", "=", "app_module_path", ".", "rsplit", "(", "'.'", "+", "app_label", ",", "1", ")", "[", "0", "]", "module_path", "=", "'{}.{}'", ".", "format", "(", "base_package", ",", "module_label", ")", "# Try to import this module from the related app that is specified", "# in the Django settings.", "local_imported_module", "=", "_import_module", "(", "module_path", ",", "classnames", ")", "# If the module we tried to import is not located inside the machina", "# vanilla apps, try to import it from the corresponding machina app.", "machina_imported_module", "=", "None", "if", "not", "app_module_path", ".", "startswith", "(", "'machina.apps'", ")", ":", "machina_imported_module", "=", "_import_module", "(", "'{}.{}'", ".", "format", "(", "'machina.apps'", ",", "module_label", ")", ",", "classnames", ",", ")", "if", "local_imported_module", "is", "None", "and", "machina_imported_module", "is", "None", ":", "raise", "AppNotFoundError", "(", "'Error importing \\'{}\\''", ".", "format", "(", "module_path", ")", ")", "# Any local module is prioritized over the corresponding machina module", "imported_modules", "=", "[", "m", "for", "m", "in", "(", "local_imported_module", ",", "machina_imported_module", ")", "if", "m", "is", "not", "None", "]", "return", "_pick_up_classes", "(", "imported_modules", ",", "classnames", ")" ]
Imports a set of classes from a given module. Usage:: get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
[ "Imports", "a", "set", "of", "classes", "from", "a", "given", "module", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L19-L59
train
ellmetha/django-machina
machina/core/loading.py
_import_module
def _import_module(module_path, classnames): """ Tries to import the given Python module path. """ try: imported_module = __import__(module_path, fromlist=classnames) return imported_module except ImportError: # In case of an ImportError, the module being loaded generally does not exist. But an # ImportError can occur if the module being loaded exists and another import located inside # it failed. # # In order to provide a meaningfull traceback, the execution information can be inspected in # order to determine which case to consider. If the execution information provides more than # a certain amount of frames, this means that an ImportError occured while loading the # initial Python module. __, __, exc_traceback = sys.exc_info() frames = traceback.extract_tb(exc_traceback) if len(frames) > 1: raise
python
def _import_module(module_path, classnames): """ Tries to import the given Python module path. """ try: imported_module = __import__(module_path, fromlist=classnames) return imported_module except ImportError: # In case of an ImportError, the module being loaded generally does not exist. But an # ImportError can occur if the module being loaded exists and another import located inside # it failed. # # In order to provide a meaningfull traceback, the execution information can be inspected in # order to determine which case to consider. If the execution information provides more than # a certain amount of frames, this means that an ImportError occured while loading the # initial Python module. __, __, exc_traceback = sys.exc_info() frames = traceback.extract_tb(exc_traceback) if len(frames) > 1: raise
[ "def", "_import_module", "(", "module_path", ",", "classnames", ")", ":", "try", ":", "imported_module", "=", "__import__", "(", "module_path", ",", "fromlist", "=", "classnames", ")", "return", "imported_module", "except", "ImportError", ":", "# In case of an ImportError, the module being loaded generally does not exist. But an", "# ImportError can occur if the module being loaded exists and another import located inside", "# it failed.", "#", "# In order to provide a meaningfull traceback, the execution information can be inspected in", "# order to determine which case to consider. If the execution information provides more than", "# a certain amount of frames, this means that an ImportError occured while loading the", "# initial Python module.", "__", ",", "__", ",", "exc_traceback", "=", "sys", ".", "exc_info", "(", ")", "frames", "=", "traceback", ".", "extract_tb", "(", "exc_traceback", ")", "if", "len", "(", "frames", ")", ">", "1", ":", "raise" ]
Tries to import the given Python module path.
[ "Tries", "to", "import", "the", "given", "Python", "module", "path", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L62-L79
train
ellmetha/django-machina
machina/core/loading.py
_pick_up_classes
def _pick_up_classes(modules, classnames): """ Given a list of class names to retrieve, try to fetch them from the specified list of modules and returns the list of the fetched classes. """ klasses = [] for classname in classnames: klass = None for module in modules: if hasattr(module, classname): klass = getattr(module, classname) break if not klass: raise ClassNotFoundError('Error fetching \'{}\' in {}'.format( classname, str([module.__name__ for module in modules])) ) klasses.append(klass) return klasses
python
def _pick_up_classes(modules, classnames): """ Given a list of class names to retrieve, try to fetch them from the specified list of modules and returns the list of the fetched classes. """ klasses = [] for classname in classnames: klass = None for module in modules: if hasattr(module, classname): klass = getattr(module, classname) break if not klass: raise ClassNotFoundError('Error fetching \'{}\' in {}'.format( classname, str([module.__name__ for module in modules])) ) klasses.append(klass) return klasses
[ "def", "_pick_up_classes", "(", "modules", ",", "classnames", ")", ":", "klasses", "=", "[", "]", "for", "classname", "in", "classnames", ":", "klass", "=", "None", "for", "module", "in", "modules", ":", "if", "hasattr", "(", "module", ",", "classname", ")", ":", "klass", "=", "getattr", "(", "module", ",", "classname", ")", "break", "if", "not", "klass", ":", "raise", "ClassNotFoundError", "(", "'Error fetching \\'{}\\' in {}'", ".", "format", "(", "classname", ",", "str", "(", "[", "module", ".", "__name__", "for", "module", "in", "modules", "]", ")", ")", ")", "klasses", ".", "append", "(", "klass", ")", "return", "klasses" ]
Given a list of class names to retrieve, try to fetch them from the specified list of modules and returns the list of the fetched classes.
[ "Given", "a", "list", "of", "class", "names", "to", "retrieve", "try", "to", "fetch", "them", "from", "the", "specified", "list", "of", "modules", "and", "returns", "the", "list", "of", "the", "fetched", "classes", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L82-L98
train
ellmetha/django-machina
machina/core/loading.py
_get_app_module_path
def _get_app_module_path(module_label): """ Given a module label, loop over the apps specified in the INSTALLED_APPS to find the corresponding application module path. """ app_name = module_label.rsplit('.', 1)[0] for app in settings.INSTALLED_APPS: if app.endswith('.' + app_name) or app == app_name: return app return None
python
def _get_app_module_path(module_label): """ Given a module label, loop over the apps specified in the INSTALLED_APPS to find the corresponding application module path. """ app_name = module_label.rsplit('.', 1)[0] for app in settings.INSTALLED_APPS: if app.endswith('.' + app_name) or app == app_name: return app return None
[ "def", "_get_app_module_path", "(", "module_label", ")", ":", "app_name", "=", "module_label", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "if", "app", ".", "endswith", "(", "'.'", "+", "app_name", ")", "or", "app", "==", "app_name", ":", "return", "app", "return", "None" ]
Given a module label, loop over the apps specified in the INSTALLED_APPS to find the corresponding application module path.
[ "Given", "a", "module", "label", "loop", "over", "the", "apps", "specified", "in", "the", "INSTALLED_APPS", "to", "find", "the", "corresponding", "application", "module", "path", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L101-L109
train
ellmetha/django-machina
machina/apps/forum_tracking/handler.py
TrackingHandler.get_unread_forums
def get_unread_forums(self, user): """ Returns the list of unread forums for the given user. """ return self.get_unread_forums_from_list( user, self.perm_handler.get_readable_forums(Forum.objects.all(), user))
python
def get_unread_forums(self, user): """ Returns the list of unread forums for the given user. """ return self.get_unread_forums_from_list( user, self.perm_handler.get_readable_forums(Forum.objects.all(), user))
[ "def", "get_unread_forums", "(", "self", ",", "user", ")", ":", "return", "self", ".", "get_unread_forums_from_list", "(", "user", ",", "self", ".", "perm_handler", ".", "get_readable_forums", "(", "Forum", ".", "objects", ".", "all", "(", ")", ",", "user", ")", ")" ]
Returns the list of unread forums for the given user.
[ "Returns", "the", "list", "of", "unread", "forums", "for", "the", "given", "user", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L36-L39
train
ellmetha/django-machina
machina/apps/forum_tracking/handler.py
TrackingHandler.get_unread_forums_from_list
def get_unread_forums_from_list(self, user, forums): """ Returns the list of unread forums for the given user from a given list of forums. """ unread_forums = [] # A user which is not authenticated will never see a forum as unread if not user.is_authenticated: return unread_forums unread = ForumReadTrack.objects.get_unread_forums_from_list(forums, user) unread_forums.extend(unread) return unread_forums
python
def get_unread_forums_from_list(self, user, forums): """ Returns the list of unread forums for the given user from a given list of forums. """ unread_forums = [] # A user which is not authenticated will never see a forum as unread if not user.is_authenticated: return unread_forums unread = ForumReadTrack.objects.get_unread_forums_from_list(forums, user) unread_forums.extend(unread) return unread_forums
[ "def", "get_unread_forums_from_list", "(", "self", ",", "user", ",", "forums", ")", ":", "unread_forums", "=", "[", "]", "# A user which is not authenticated will never see a forum as unread", "if", "not", "user", ".", "is_authenticated", ":", "return", "unread_forums", "unread", "=", "ForumReadTrack", ".", "objects", ".", "get_unread_forums_from_list", "(", "forums", ",", "user", ")", "unread_forums", ".", "extend", "(", "unread", ")", "return", "unread_forums" ]
Returns the list of unread forums for the given user from a given list of forums.
[ "Returns", "the", "list", "of", "unread", "forums", "for", "the", "given", "user", "from", "a", "given", "list", "of", "forums", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L41-L52
train
ellmetha/django-machina
machina/apps/forum_tracking/handler.py
TrackingHandler.get_unread_topics
def get_unread_topics(self, topics, user): """ Returns a list of unread topics for the given user from a given set of topics. """ unread_topics = [] # A user which is not authenticated will never see a topic as unread. # If there are no topics to consider, we stop here. if not user.is_authenticated or topics is None or not len(topics): return unread_topics # A topic can be unread if a track for itself exists with a mark time that # is less important than its update date. topic_ids = [topic.id for topic in topics] topic_tracks = TopicReadTrack.objects.filter(topic__in=topic_ids, user=user) tracked_topics = dict(topic_tracks.values_list('topic__pk', 'mark_time')) if tracked_topics: for topic in topics: topic_last_modification_date = topic.last_post_on or topic.created if ( topic.id in tracked_topics.keys() and topic_last_modification_date > tracked_topics[topic.id] ): unread_topics.append(topic) # A topic can be unread if a track for its associated forum exists with # a mark time that is less important than its creation or update date. forum_ids = [topic.forum_id for topic in topics] forum_tracks = ForumReadTrack.objects.filter(forum_id__in=forum_ids, user=user) tracked_forums = dict(forum_tracks.values_list('forum__pk', 'mark_time')) if tracked_forums: for topic in topics: topic_last_modification_date = topic.last_post_on or topic.created if ( (topic.forum_id in tracked_forums.keys() and topic.id not in tracked_topics) and topic_last_modification_date > tracked_forums[topic.forum_id] ): unread_topics.append(topic) # A topic can be unread if no tracks exists for it for topic in topics: if topic.forum_id not in tracked_forums and topic.id not in tracked_topics: unread_topics.append(topic) return list(set(unread_topics))
python
def get_unread_topics(self, topics, user): """ Returns a list of unread topics for the given user from a given set of topics. """ unread_topics = [] # A user which is not authenticated will never see a topic as unread. # If there are no topics to consider, we stop here. if not user.is_authenticated or topics is None or not len(topics): return unread_topics # A topic can be unread if a track for itself exists with a mark time that # is less important than its update date. topic_ids = [topic.id for topic in topics] topic_tracks = TopicReadTrack.objects.filter(topic__in=topic_ids, user=user) tracked_topics = dict(topic_tracks.values_list('topic__pk', 'mark_time')) if tracked_topics: for topic in topics: topic_last_modification_date = topic.last_post_on or topic.created if ( topic.id in tracked_topics.keys() and topic_last_modification_date > tracked_topics[topic.id] ): unread_topics.append(topic) # A topic can be unread if a track for its associated forum exists with # a mark time that is less important than its creation or update date. forum_ids = [topic.forum_id for topic in topics] forum_tracks = ForumReadTrack.objects.filter(forum_id__in=forum_ids, user=user) tracked_forums = dict(forum_tracks.values_list('forum__pk', 'mark_time')) if tracked_forums: for topic in topics: topic_last_modification_date = topic.last_post_on or topic.created if ( (topic.forum_id in tracked_forums.keys() and topic.id not in tracked_topics) and topic_last_modification_date > tracked_forums[topic.forum_id] ): unread_topics.append(topic) # A topic can be unread if no tracks exists for it for topic in topics: if topic.forum_id not in tracked_forums and topic.id not in tracked_topics: unread_topics.append(topic) return list(set(unread_topics))
[ "def", "get_unread_topics", "(", "self", ",", "topics", ",", "user", ")", ":", "unread_topics", "=", "[", "]", "# A user which is not authenticated will never see a topic as unread.", "# If there are no topics to consider, we stop here.", "if", "not", "user", ".", "is_authenticated", "or", "topics", "is", "None", "or", "not", "len", "(", "topics", ")", ":", "return", "unread_topics", "# A topic can be unread if a track for itself exists with a mark time that", "# is less important than its update date.", "topic_ids", "=", "[", "topic", ".", "id", "for", "topic", "in", "topics", "]", "topic_tracks", "=", "TopicReadTrack", ".", "objects", ".", "filter", "(", "topic__in", "=", "topic_ids", ",", "user", "=", "user", ")", "tracked_topics", "=", "dict", "(", "topic_tracks", ".", "values_list", "(", "'topic__pk'", ",", "'mark_time'", ")", ")", "if", "tracked_topics", ":", "for", "topic", "in", "topics", ":", "topic_last_modification_date", "=", "topic", ".", "last_post_on", "or", "topic", ".", "created", "if", "(", "topic", ".", "id", "in", "tracked_topics", ".", "keys", "(", ")", "and", "topic_last_modification_date", ">", "tracked_topics", "[", "topic", ".", "id", "]", ")", ":", "unread_topics", ".", "append", "(", "topic", ")", "# A topic can be unread if a track for its associated forum exists with", "# a mark time that is less important than its creation or update date.", "forum_ids", "=", "[", "topic", ".", "forum_id", "for", "topic", "in", "topics", "]", "forum_tracks", "=", "ForumReadTrack", ".", "objects", ".", "filter", "(", "forum_id__in", "=", "forum_ids", ",", "user", "=", "user", ")", "tracked_forums", "=", "dict", "(", "forum_tracks", ".", "values_list", "(", "'forum__pk'", ",", "'mark_time'", ")", ")", "if", "tracked_forums", ":", "for", "topic", "in", "topics", ":", "topic_last_modification_date", "=", "topic", ".", "last_post_on", "or", "topic", ".", "created", "if", "(", "(", "topic", ".", "forum_id", "in", "tracked_forums", ".", "keys", "(", ")", "and", "topic", ".", "id", "not", "in", "tracked_topics", ")", "and", "topic_last_modification_date", ">", "tracked_forums", "[", "topic", ".", "forum_id", "]", ")", ":", "unread_topics", ".", "append", "(", "topic", ")", "# A topic can be unread if no tracks exists for it", "for", "topic", "in", "topics", ":", "if", "topic", ".", "forum_id", "not", "in", "tracked_forums", "and", "topic", ".", "id", "not", "in", "tracked_topics", ":", "unread_topics", ".", "append", "(", "topic", ")", "return", "list", "(", "set", "(", "unread_topics", ")", ")" ]
Returns a list of unread topics for the given user from a given set of topics.
[ "Returns", "a", "list", "of", "unread", "topics", "for", "the", "given", "user", "from", "a", "given", "set", "of", "topics", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L54-L98
train
ellmetha/django-machina
machina/apps/forum_tracking/handler.py
TrackingHandler.mark_forums_read
def mark_forums_read(self, forums, user): """ Marks a list of forums as read. """ if not forums or not user.is_authenticated: return forums = sorted(forums, key=lambda f: f.level) # Update all forum tracks to the current date for the considered forums for forum in forums: forum_track = ForumReadTrack.objects.get_or_create(forum=forum, user=user)[0] forum_track.save() # Delete all the unnecessary topic tracks TopicReadTrack.objects.filter(topic__forum__in=forums, user=user).delete() # Update parent forum tracks self._update_parent_forum_tracks(forums[0], user)
python
def mark_forums_read(self, forums, user): """ Marks a list of forums as read. """ if not forums or not user.is_authenticated: return forums = sorted(forums, key=lambda f: f.level) # Update all forum tracks to the current date for the considered forums for forum in forums: forum_track = ForumReadTrack.objects.get_or_create(forum=forum, user=user)[0] forum_track.save() # Delete all the unnecessary topic tracks TopicReadTrack.objects.filter(topic__forum__in=forums, user=user).delete() # Update parent forum tracks self._update_parent_forum_tracks(forums[0], user)
[ "def", "mark_forums_read", "(", "self", ",", "forums", ",", "user", ")", ":", "if", "not", "forums", "or", "not", "user", ".", "is_authenticated", ":", "return", "forums", "=", "sorted", "(", "forums", ",", "key", "=", "lambda", "f", ":", "f", ".", "level", ")", "# Update all forum tracks to the current date for the considered forums", "for", "forum", "in", "forums", ":", "forum_track", "=", "ForumReadTrack", ".", "objects", ".", "get_or_create", "(", "forum", "=", "forum", ",", "user", "=", "user", ")", "[", "0", "]", "forum_track", ".", "save", "(", ")", "# Delete all the unnecessary topic tracks", "TopicReadTrack", ".", "objects", ".", "filter", "(", "topic__forum__in", "=", "forums", ",", "user", "=", "user", ")", ".", "delete", "(", ")", "# Update parent forum tracks", "self", ".", "_update_parent_forum_tracks", "(", "forums", "[", "0", "]", ",", "user", ")" ]
Marks a list of forums as read.
[ "Marks", "a", "list", "of", "forums", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L100-L114
train
ellmetha/django-machina
machina/apps/forum_tracking/handler.py
TrackingHandler.mark_topic_read
def mark_topic_read(self, topic, user): """ Marks a topic as read. """ if not user.is_authenticated: return forum = topic.forum try: forum_track = ForumReadTrack.objects.get(forum=forum, user=user) except ForumReadTrack.DoesNotExist: forum_track = None if ( forum_track is None or (topic.last_post_on and forum_track.mark_time < topic.last_post_on) ): topic_track, created = TopicReadTrack.objects.get_or_create(topic=topic, user=user) if not created: topic_track.save() # mark_time filled # If no other topic is unread inside the considered forum, the latter should also be # marked as read. unread_topics = ( forum.topics .filter( Q(tracks__user=user, tracks__mark_time__lt=F('last_post_on')) | Q( forum__tracks__user=user, forum__tracks__mark_time__lt=F('last_post_on'), tracks__isnull=True, ) ) .exclude(id=topic.id) ) forum_topic_tracks = TopicReadTrack.objects.filter(topic__forum=forum, user=user) if ( not unread_topics.exists() and ( forum_track is not None or forum_topic_tracks.count() == forum.topics.filter(approved=True).count() ) ): # The topics that are marked as read inside the forum for the given user will be # deleted while the forum track associated with the user must be created or updated. # This is done only if there are as many topic tracks as approved topics in case # the related forum has not beem previously marked as read. TopicReadTrack.objects.filter(topic__forum=forum, user=user).delete() forum_track, _ = ForumReadTrack.objects.get_or_create(forum=forum, user=user) forum_track.save() # Update parent forum tracks self._update_parent_forum_tracks(forum, user)
python
def mark_topic_read(self, topic, user): """ Marks a topic as read. """ if not user.is_authenticated: return forum = topic.forum try: forum_track = ForumReadTrack.objects.get(forum=forum, user=user) except ForumReadTrack.DoesNotExist: forum_track = None if ( forum_track is None or (topic.last_post_on and forum_track.mark_time < topic.last_post_on) ): topic_track, created = TopicReadTrack.objects.get_or_create(topic=topic, user=user) if not created: topic_track.save() # mark_time filled # If no other topic is unread inside the considered forum, the latter should also be # marked as read. unread_topics = ( forum.topics .filter( Q(tracks__user=user, tracks__mark_time__lt=F('last_post_on')) | Q( forum__tracks__user=user, forum__tracks__mark_time__lt=F('last_post_on'), tracks__isnull=True, ) ) .exclude(id=topic.id) ) forum_topic_tracks = TopicReadTrack.objects.filter(topic__forum=forum, user=user) if ( not unread_topics.exists() and ( forum_track is not None or forum_topic_tracks.count() == forum.topics.filter(approved=True).count() ) ): # The topics that are marked as read inside the forum for the given user will be # deleted while the forum track associated with the user must be created or updated. # This is done only if there are as many topic tracks as approved topics in case # the related forum has not beem previously marked as read. TopicReadTrack.objects.filter(topic__forum=forum, user=user).delete() forum_track, _ = ForumReadTrack.objects.get_or_create(forum=forum, user=user) forum_track.save() # Update parent forum tracks self._update_parent_forum_tracks(forum, user)
[ "def", "mark_topic_read", "(", "self", ",", "topic", ",", "user", ")", ":", "if", "not", "user", ".", "is_authenticated", ":", "return", "forum", "=", "topic", ".", "forum", "try", ":", "forum_track", "=", "ForumReadTrack", ".", "objects", ".", "get", "(", "forum", "=", "forum", ",", "user", "=", "user", ")", "except", "ForumReadTrack", ".", "DoesNotExist", ":", "forum_track", "=", "None", "if", "(", "forum_track", "is", "None", "or", "(", "topic", ".", "last_post_on", "and", "forum_track", ".", "mark_time", "<", "topic", ".", "last_post_on", ")", ")", ":", "topic_track", ",", "created", "=", "TopicReadTrack", ".", "objects", ".", "get_or_create", "(", "topic", "=", "topic", ",", "user", "=", "user", ")", "if", "not", "created", ":", "topic_track", ".", "save", "(", ")", "# mark_time filled", "# If no other topic is unread inside the considered forum, the latter should also be", "# marked as read.", "unread_topics", "=", "(", "forum", ".", "topics", ".", "filter", "(", "Q", "(", "tracks__user", "=", "user", ",", "tracks__mark_time__lt", "=", "F", "(", "'last_post_on'", ")", ")", "|", "Q", "(", "forum__tracks__user", "=", "user", ",", "forum__tracks__mark_time__lt", "=", "F", "(", "'last_post_on'", ")", ",", "tracks__isnull", "=", "True", ",", ")", ")", ".", "exclude", "(", "id", "=", "topic", ".", "id", ")", ")", "forum_topic_tracks", "=", "TopicReadTrack", ".", "objects", ".", "filter", "(", "topic__forum", "=", "forum", ",", "user", "=", "user", ")", "if", "(", "not", "unread_topics", ".", "exists", "(", ")", "and", "(", "forum_track", "is", "not", "None", "or", "forum_topic_tracks", ".", "count", "(", ")", "==", "forum", ".", "topics", ".", "filter", "(", "approved", "=", "True", ")", ".", "count", "(", ")", ")", ")", ":", "# The topics that are marked as read inside the forum for the given user will be", "# deleted while the forum track associated with the user must be created or updated.", "# This is done only if there are as many topic tracks as approved topics in case", "# the related forum has not beem previously marked as read.", "TopicReadTrack", ".", "objects", ".", "filter", "(", "topic__forum", "=", "forum", ",", "user", "=", "user", ")", ".", "delete", "(", ")", "forum_track", ",", "_", "=", "ForumReadTrack", ".", "objects", ".", "get_or_create", "(", "forum", "=", "forum", ",", "user", "=", "user", ")", "forum_track", ".", "save", "(", ")", "# Update parent forum tracks", "self", ".", "_update_parent_forum_tracks", "(", "forum", ",", "user", ")" ]
Marks a topic as read.
[ "Marks", "a", "topic", "as", "read", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L116-L166
train
ellmetha/django-machina
machina/apps/forum/abstract_models.py
AbstractForum.clean
def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum as parent')) if self.is_category and self.parent and self.parent.is_category: raise ValidationError(_('A category can not have another category as parent')) if self.is_link and not self.link: raise ValidationError(_('A link forum must have a link associated with it'))
python
def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum as parent')) if self.is_category and self.parent and self.parent.is_category: raise ValidationError(_('A category can not have another category as parent')) if self.is_link and not self.link: raise ValidationError(_('A link forum must have a link associated with it'))
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "parent", "and", "self", ".", "parent", ".", "is_link", ":", "raise", "ValidationError", "(", "_", "(", "'A forum can not have a link forum as parent'", ")", ")", "if", "self", ".", "is_category", "and", "self", ".", "parent", "and", "self", ".", "parent", ".", "is_category", ":", "raise", "ValidationError", "(", "_", "(", "'A category can not have another category as parent'", ")", ")", "if", "self", ".", "is_link", "and", "not", "self", ".", "link", ":", "raise", "ValidationError", "(", "_", "(", "'A link forum must have a link associated with it'", ")", ")" ]
Validates the forum instance.
[ "Validates", "the", "forum", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L134-L145
train
ellmetha/django-machina
machina/apps/forum/abstract_models.py
AbstractForum.get_image_upload_to
def get_image_upload_to(self, filename): """ Returns the path to upload a new associated image to. """ dummy, ext = os.path.splitext(filename) return os.path.join( machina_settings.FORUM_IMAGE_UPLOAD_TO, '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext), )
python
def get_image_upload_to(self, filename): """ Returns the path to upload a new associated image to. """ dummy, ext = os.path.splitext(filename) return os.path.join( machina_settings.FORUM_IMAGE_UPLOAD_TO, '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext), )
[ "def", "get_image_upload_to", "(", "self", ",", "filename", ")", ":", "dummy", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "os", ".", "path", ".", "join", "(", "machina_settings", ".", "FORUM_IMAGE_UPLOAD_TO", ",", "'{id}{ext}'", ".", "format", "(", "id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "'-'", ",", "''", ")", ",", "ext", "=", "ext", ")", ",", ")" ]
Returns the path to upload a new associated image to.
[ "Returns", "the", "path", "to", "upload", "a", "new", "associated", "image", "to", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L147-L153
train
ellmetha/django-machina
machina/apps/forum/abstract_models.py
AbstractForum.save
def save(self, *args, **kwargs): """ Saves the forum instance. """ # It is vital to track the changes of the parent associated with a forum in order to # maintain counters up-to-date and to trigger other operations such as permissions updates. old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) # Update the slug field self.slug = slugify(force_text(self.name), allow_unicode=True) # Do the save super().save(*args, **kwargs) # If any change has been made to the forum parent, trigger the update of the counters if old_instance and old_instance.parent != self.parent: self.update_trackers() # Trigger the 'forum_moved' signal signals.forum_moved.send(sender=self, previous_parent=old_instance.parent)
python
def save(self, *args, **kwargs): """ Saves the forum instance. """ # It is vital to track the changes of the parent associated with a forum in order to # maintain counters up-to-date and to trigger other operations such as permissions updates. old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) # Update the slug field self.slug = slugify(force_text(self.name), allow_unicode=True) # Do the save super().save(*args, **kwargs) # If any change has been made to the forum parent, trigger the update of the counters if old_instance and old_instance.parent != self.parent: self.update_trackers() # Trigger the 'forum_moved' signal signals.forum_moved.send(sender=self, previous_parent=old_instance.parent)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# It is vital to track the changes of the parent associated with a forum in order to", "# maintain counters up-to-date and to trigger other operations such as permissions updates.", "old_instance", "=", "None", "if", "self", ".", "pk", ":", "old_instance", "=", "self", ".", "__class__", ".", "_default_manager", ".", "get", "(", "pk", "=", "self", ".", "pk", ")", "# Update the slug field", "self", ".", "slug", "=", "slugify", "(", "force_text", "(", "self", ".", "name", ")", ",", "allow_unicode", "=", "True", ")", "# Do the save", "super", "(", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# If any change has been made to the forum parent, trigger the update of the counters", "if", "old_instance", "and", "old_instance", ".", "parent", "!=", "self", ".", "parent", ":", "self", ".", "update_trackers", "(", ")", "# Trigger the 'forum_moved' signal", "signals", ".", "forum_moved", ".", "send", "(", "sender", "=", "self", ",", "previous_parent", "=", "old_instance", ".", "parent", ")" ]
Saves the forum instance.
[ "Saves", "the", "forum", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L155-L173
train
ellmetha/django-machina
machina/apps/forum/abstract_models.py
AbstractForum.update_trackers
def update_trackers(self): """ Updates the denormalized trackers associated with the forum instance. """ direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on') # Compute the direct topics count and the direct posts count. self.direct_topics_count = direct_approved_topics.count() self.direct_posts_count = direct_approved_topics.aggregate( total_posts_count=Sum('posts_count'))['total_posts_count'] or 0 # Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values # associated with the topic with the latest post. if direct_approved_topics.exists(): self.last_post_id = direct_approved_topics[0].last_post_id self.last_post_on = direct_approved_topics[0].last_post_on else: self.last_post_id = None self.last_post_on = None # Any save of a forum triggered from the update_tracker process will not result in checking # for a change of the forum's parent. self._simple_save()
python
def update_trackers(self): """ Updates the denormalized trackers associated with the forum instance. """ direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on') # Compute the direct topics count and the direct posts count. self.direct_topics_count = direct_approved_topics.count() self.direct_posts_count = direct_approved_topics.aggregate( total_posts_count=Sum('posts_count'))['total_posts_count'] or 0 # Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values # associated with the topic with the latest post. if direct_approved_topics.exists(): self.last_post_id = direct_approved_topics[0].last_post_id self.last_post_on = direct_approved_topics[0].last_post_on else: self.last_post_id = None self.last_post_on = None # Any save of a forum triggered from the update_tracker process will not result in checking # for a change of the forum's parent. self._simple_save()
[ "def", "update_trackers", "(", "self", ")", ":", "direct_approved_topics", "=", "self", ".", "topics", ".", "filter", "(", "approved", "=", "True", ")", ".", "order_by", "(", "'-last_post_on'", ")", "# Compute the direct topics count and the direct posts count.", "self", ".", "direct_topics_count", "=", "direct_approved_topics", ".", "count", "(", ")", "self", ".", "direct_posts_count", "=", "direct_approved_topics", ".", "aggregate", "(", "total_posts_count", "=", "Sum", "(", "'posts_count'", ")", ")", "[", "'total_posts_count'", "]", "or", "0", "# Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values", "# associated with the topic with the latest post.", "if", "direct_approved_topics", ".", "exists", "(", ")", ":", "self", ".", "last_post_id", "=", "direct_approved_topics", "[", "0", "]", ".", "last_post_id", "self", ".", "last_post_on", "=", "direct_approved_topics", "[", "0", "]", ".", "last_post_on", "else", ":", "self", ".", "last_post_id", "=", "None", "self", ".", "last_post_on", "=", "None", "# Any save of a forum triggered from the update_tracker process will not result in checking", "# for a change of the forum's parent.", "self", ".", "_simple_save", "(", ")" ]
Updates the denormalized trackers associated with the forum instance.
[ "Updates", "the", "denormalized", "trackers", "associated", "with", "the", "forum", "instance", "." ]
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L175-L195
train