docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Fill the foregound of a console with r,g,b. Args: con (Console): Any Console instance. r (Sequence[int]): An array of integers with a length of width*height. g (Sequence[int]): An array of integers with a length of width*height. b (Sequence[int]): An array of integers with a length ...
def console_fill_foreground( con: tcod.console.Console, r: Sequence[int], g: Sequence[int], b: Sequence[int], ) -> None: if len(r) != len(g) or len(r) != len(b): raise TypeError("R, G and B must all have the same size.") if ( isinstance(r, np.ndarray) and isinstance(...
456,260
Return a new AStar using the given Map. Args: m (Map): A Map instance. dcost (float): The path-finding cost of diagonal movement. Can be set to 0 to disable diagonal movement. Returns: AStar: A new AStar instance.
def path_new_using_map( m: tcod.map.Map, dcost: float = 1.41 ) -> tcod.path.AStar: return tcod.path.AStar(m, dcost)
456,271
Return a new AStar using the given callable function. Args: w (int): Clipping width. h (int): Clipping height. func (Callable[[int, int, int, int, Any], float]): userData (Any): dcost (float): A multiplier for the cost of diagonal movement. Can be set ...
def path_new_using_function( w: int, h: int, func: Callable[[int, int, int, int, Any], float], userData: Any = 0, dcost: float = 1.41, ) -> tcod.path.AStar: return tcod.path.AStar( tcod.path._EdgeCostFunc((func, userData), (w, h)), dcost )
456,272
Find a path from (ox, oy) to (dx, dy). Return True if path is found. Args: p (AStar): An AStar instance. ox (int): Starting x position. oy (int): Starting y position. dx (int): Destination x position. dy (int): Destination y position. Returns: bool: True if a va...
def path_compute( p: tcod.path.AStar, ox: int, oy: int, dx: int, dy: int ) -> bool: return bool(lib.TCOD_path_compute(p._path_c, ox, oy, dx, dy))
456,273
Get the current origin position. This point moves when :any:`path_walk` returns the next x,y step. Args: p (AStar): An AStar instance. Returns: Tuple[int, int]: An (x, y) point.
def path_get_origin(p: tcod.path.AStar) -> Tuple[int, int]: x = ffi.new("int *") y = ffi.new("int *") lib.TCOD_path_get_origin(p._path_c, x, y) return x[0], y[0]
456,274
Get the current destination position. Args: p (AStar): An AStar instance. Returns: Tuple[int, int]: An (x, y) point.
def path_get_destination(p: tcod.path.AStar) -> Tuple[int, int]: x = ffi.new("int *") y = ffi.new("int *") lib.TCOD_path_get_destination(p._path_c, x, y) return x[0], y[0]
456,275
Return the current length of the computed path. Args: p (AStar): An AStar instance. Returns: int: Length of the path.
def path_size(p: tcod.path.AStar) -> int: return int(lib.TCOD_path_size(p._path_c))
456,276
Get a point on a path. Args: p (AStar): An AStar instance. idx (int): Should be in range: 0 <= inx < :any:`path_size`
def path_get(p: tcod.path.AStar, idx: int) -> Tuple[int, int]: x = ffi.new("int *") y = ffi.new("int *") lib.TCOD_path_get(p._path_c, idx, x, y) return x[0], y[0]
456,277
Return True if a path is empty. Args: p (AStar): An AStar instance. Returns: bool: True if a path is empty. Otherwise False.
def path_is_empty(p: tcod.path.AStar) -> bool: return bool(lib.TCOD_path_is_empty(p._path_c))
456,278
Return the next (x, y) point in a path, or (None, None) if it's empty. When ``recompute`` is True and a previously valid path reaches a point where it is now blocked, a new path will automatically be found. Args: p (AStar): An AStar instance. recompute (bool): Recompute the path automatica...
def path_walk( p: tcod.path.AStar, recompute: bool ) -> Union[Tuple[int, int], Tuple[None, None]]: x = ffi.new("int *") y = ffi.new("int *") if lib.TCOD_path_walk(p._path_c, x, y, recompute): return x[0], y[0] return None, None
456,279
Clamp all values on this heightmap between ``mi`` and ``ma`` Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. mi (float): The lower bound to clamp to. ma (float): The upper bound to clamp to. .. deprecated:: 2.0 Do ``hm.clip(mi, ma)`` instead.
def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None: hm.clip(mi, ma)
456,292
Normalize heightmap values between ``mi`` and ``ma``. Args: mi (float): The lowest value after normalization. ma (float): The highest value after normalization.
def heightmap_normalize( hm: np.ndarray, mi: float = 0.0, ma: float = 1.0 ) -> None: lib.TCOD_heightmap_normalize(_heightmap_cdata(hm), mi, ma)
456,293
Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to add to the first. hm3 (numpy.ndar...
def heightmap_lerp_hm( hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float ) -> None: lib.TCOD_heightmap_lerp_hm( _heightmap_cdata(hm1), _heightmap_cdata(hm2), _heightmap_cdata(hm3), coef, )
456,294
Add two heightmaps together and stores the result in ``hm3``. Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to add to the first. hm3 (numpy.ndarray): A destination heightmap to store the result. .. deprecated:: 2.0 Do ``hm3[:] = hm1[:...
def heightmap_add_hm( hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray ) -> None: hm3[:] = hm1[:] + hm2[:]
456,295
Multiplies two heightmap's together and stores the result in ``hm3``. Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to multiply with the first. hm3 (numpy.ndarray): A destination heightmap to store the result. .. deprecated:: 2.0 Do `...
def heightmap_multiply_hm( hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray ) -> None: hm3[:] = hm1[:] * hm2[:]
456,296
Add a hill (a half spheroid) at given position. If height == radius or -radius, the hill is a half-sphere. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): The x position at the center of the new hill. y (float): The y position at the center of th...
def heightmap_add_hill( hm: np.ndarray, x: float, y: float, radius: float, height: float ) -> None: lib.TCOD_heightmap_add_hill(_heightmap_cdata(hm), x, y, radius, height)
456,297
Return the interpolated height at non integer coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): A floating point x coordinate. y (float): A floating point y coordinate. Returns: float: The value at ``x``, ``y``.
def heightmap_get_interpolated_value( hm: np.ndarray, x: float, y: float ) -> float: return float( lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm), x, y) )
456,304
Return the slope between 0 and (pi / 2) at given coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (int): The x coordinate. y (int): The y coordinate. Returns: float: The steepness at ``x``, ``y``. From 0 to (pi / 2)
def heightmap_get_slope(hm: np.ndarray, x: int, y: int) -> float: return float(lib.TCOD_heightmap_get_slope(_heightmap_cdata(hm), x, y))
456,305
Return the map normal at given coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): The x coordinate. y (float): The y coordinate. waterLevel (float): The heightmap is considered flat below this value. Returns: Tuple[float...
def heightmap_get_normal( hm: np.ndarray, x: float, y: float, waterLevel: float ) -> Tuple[float, float, float]: cn = ffi.new("float[3]") lib.TCOD_heightmap_get_normal(_heightmap_cdata(hm), x, y, cn, waterLevel) return tuple(cn)
456,306
Return the number of map cells which value is between ``mi`` and ``ma``. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. mi (float): The lower bound. ma (float): The upper bound. Returns: int: The count of values which fall between ``mi`` and ``ma``...
def heightmap_count_cells(hm: np.ndarray, mi: float, ma: float) -> int: return int(lib.TCOD_heightmap_count_cells(_heightmap_cdata(hm), mi, ma))
456,307
Returns True if the map edges are below ``waterlevel``, otherwise False. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. waterLevel (float): The water level to use. Returns: bool: True if the map edges are below ``waterlevel``, otherwise False.
def heightmap_has_land_on_border(hm: np.ndarray, waterlevel: float) -> bool: return bool( lib.TCOD_heightmap_has_land_on_border(_heightmap_cdata(hm), waterlevel) )
456,308
Return the min and max values of this heightmap. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. Returns: Tuple[float, float]: The (min, max) values. .. deprecated:: 2.0 Use ``hm.min()`` or ``hm.max()`` instead.
def heightmap_get_minmax(hm: np.ndarray) -> Tuple[float, float]: mi = ffi.new("float *") ma = ffi.new("float *") lib.TCOD_heightmap_get_minmax(_heightmap_cdata(hm), mi, ma) return mi[0], ma[0]
456,309
Load an image file into an Image instance and return it. Args: filename (AnyStr): Path to a .bmp or .png image file.
def image_load(filename: str) -> tcod.image.Image: return tcod.image.Image._from_cdata( ffi.gc(lib.TCOD_image_load(_bytes(filename)), lib.TCOD_image_delete) )
456,317
Return an Image with a Consoles pixel data. This effectively takes a screen-shot of the Console. Args: console (Console): Any Console instance.
def image_from_console(console: tcod.console.Console) -> tcod.image.Image: return tcod.image.Image._from_cdata( ffi.gc( lib.TCOD_image_from_console(_console(console)), lib.TCOD_image_delete, ) )
456,318
Initilize a line whose points will be returned by `line_step`. This function does not return anything on its own. Does not include the origin point. Args: xo (int): X starting point. yo (int): Y starting point. xd (int): X destination point. yd (int): Y destination point. ...
def line_init(xo: int, yo: int, xd: int, yd: int) -> None: lib.TCOD_line_init(xo, yo, xd, yd)
456,328
returns an Iterable This Iterable does not include the origin point. Args: xo (int): X starting point. yo (int): Y starting point. xd (int): X destination point. yd (int): Y destination point. Returns: Iterable[Tuple[int,int]]: An Iterable of (x,y) points.
def line_iter(xo: int, yo: int, xd: int, yd: int) -> Iterator[Tuple[int, int]]: data = ffi.new("TCOD_bresenham_data_t *") lib.TCOD_line_init_mt(xo, yo, xd, yd, data) x = ffi.new("int *") y = ffi.new("int *") yield xo, yo while not lib.TCOD_line_step_mt(x, y, data): yield (x[0], y[0]...
456,331
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 instan...
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)
456,345
Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant.
def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: n.algorithm = typ
456,346
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 (Seque...
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))
456,347
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: ...
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) )
456,348
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:...
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 ) )
456,349
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.
def random_new(algo: int = RNG_CMWC) -> tcod.random.Random: return tcod.random.Random(algo)
456,366
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 u...
def random_new_from_seed( seed: Hashable, algo: int = RNG_CMWC ) -> tcod.random.Random: return tcod.random.Random(algo, seed)
456,367
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_*.
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)
456,368
Return a random integer in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. low (int): The lower bound of the random range, inclusive. high (int): The upper ...
def random_get_int(rnd: Optional[tcod.random.Random], mi: int, ma: int) -> int: return int( lib.TCOD_random_get_int(rnd.random_c if rnd else ffi.NULL, mi, ma) )
456,369
Return a random float in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. low (float): The lower bound of the random range, inclusive. high (float): The uppe...
def random_get_float( rnd: Optional[tcod.random.Random], mi: float, ma: float ) -> float: return float( lib.TCOD_random_get_double(rnd.random_c if rnd else ffi.NULL, mi, ma) )
456,370
Return a random weighted integer in the range: ``mi`` <= n <= ``ma``. The result is affacted by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. low (int): The lower bound of the random range, inclusive. high (int): T...
def random_get_int_mean( rnd: Optional[tcod.random.Random], mi: int, ma: int, mean: int ) -> int: return int( lib.TCOD_random_get_int_mean( rnd.random_c if rnd else ffi.NULL, mi, ma, mean ) )
456,371
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 ...
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)
456,374
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...
def sys_save_screenshot(name: Optional[str] = None) -> None: lib.TCOD_sys_save_screenshot( _bytes(name) if name is not None else ffi.NULL )
456,379
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 C...
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....
456,383
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 ...
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 ) )
456,384
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 ...
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)
456,390
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.
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
456,391
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.
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 Valu...
456,393
Fill this entire Image with color. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
def clear(self, color: Tuple[int, int, int]) -> None: lib.TCOD_image_clear(self.image_c, color)
456,408
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.
def scale(self, width: int, height: int) -> None: lib.TCOD_image_scale(self.image_c, width, height) self.width, self.height = width, height
456,409
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.
def set_key_color(self, color: Tuple[int, int, int]) -> None: lib.TCOD_image_set_key_color(self.image_c, color)
456,410
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 be...
def get_alpha(self, x: int, y: int) -> int: return lib.TCOD_image_get_alpha(self.image_c, x, y)
456,411
Update an Image created with :any:`tcod.image_from_console`. The console used with this function should have the same width and height as the Console given to :any:`tcod.image_from_console`. The font width and height must also be the same as when :any:`tcod.image_from_console` was calle...
def refresh_console(self, console: tcod.console.Console) -> None: lib.TCOD_image_refresh_console(self.image_c, _console(console))
456,412
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...
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
456,414
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.
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)
456,416
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. ...
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 )
456,418
Save the Image to a 32-bit .bmp or .png file. Args: filename (Text): File path to same this Image.
def save_as(self, filename: str) -> None: lib.TCOD_image_save(self.image_c, filename.encode("utf-8"))
456,420
Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int):
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)
456,487
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.
def contains(self, x: int, y: int) -> bool: return ( self.x <= x < self.x + self.width and self.y <= y < self.y + self.height )
456,492
Draw the character c at x,y using the default colors and a blend mode. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. ch (int): Character code to draw. Must be in integer form. bg_blend (int): Blending mode to use, default...
def put_char( self, x: int, y: int, ch: int, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: lib.TCOD_console_put_char(self.console_c, x, y, ch, bg_blend)
456,543
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. stri...
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_) ) )
456,547
Collect all symbols from a list of modules. Args: module_to_name: Dictionary mapping modules to short names. Returns: Dictionary mapping name to (fullname, member) pairs.
def collect_members(module_to_name): members = {} for module, module_name in module_to_name.items(): all_names = getattr(module, "__all__", None) for name, member in inspect.getmembers(module): if ((inspect.isfunction(member) or inspect.isclass(member)) and not _always_drop_symbol_re.matc...
456,881
Turn a full member name into an anchor. Args: module_to_name: Dictionary mapping modules to short names. fullname: Fully qualified name of symbol. Returns: HTML anchor string. The longest module name prefix of fullname is removed to make the anchor. Raises: ValueError: If fullname uses cha...
def _get_anchor(module_to_name, fullname): if not _anchor_re.match(fullname): raise ValueError("'%s' is not a valid anchor" % fullname) anchor = fullname for module_name in module_to_name.values(): if fullname.startswith(module_name + "."): rest = fullname[len(module_name)+1:] # Use this pr...
456,882
Write a list of libraries to disk. Args: dir: Output directory. libraries: List of (filename, library) pairs.
def write_libraries(dir, libraries): files = [open(os.path.join(dir, k), "w") for k, _ in libraries] # Document mentioned symbols for all libraries for f, (_, v) in zip(files, libraries): v.write_markdown_to_file(f) # Document symbols that no library mentioned. We do this after writing # out all libra...
456,883
Creates a new Index. Args: module_to_name: Dictionary mapping modules to short names. members: Dictionary mapping member name to (fullname, member). filename_to_library_map: A list of (filename, Library) pairs. The order corresponds to the order in which the libraries appear in the index....
def __init__(self, module_to_name, members, filename_to_library_map, path_prefix): self._module_to_name = module_to_name self._members = members self._filename_to_library_map = filename_to_library_map self._path_prefix = path_prefix
456,884
Writes this index to file `f`. The output is formatted as an unordered list. Each list element contains the title of the library, followed by a list of symbols in that library hyperlinked to the corresponding anchor in that library. Args: f: The output file.
def write_markdown_to_file(self, f): print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) print("# TensorFlow Python reference documentation", file=f) print("", file=f) fullname_f = lambda name: self._members[...
456,885
Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'class'. Yields: name, member tuples.
def get_class_members(self, cls_name, cls): for name, member in inspect.getmembers(cls): # Only show methods and properties presently. In Python 3, # methods register as isfunction. is_method = inspect.ismethod(member) or inspect.isfunction(member) if not (is_method or isinstance(membe...
456,889
Remove indenting. We follow Python's convention and remove the minimum indent of the lines after the first, see: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation preserving relative indentation. Args: docstring: A docstring. Returns: A list of strings, one ...
def _remove_docstring_indent(self, docstring): docstring = docstring or "" lines = docstring.strip().split("\n") min_indent = len(docstring) for l in lines[1:]: l = l.rstrip() if l: i = 0 while i < len(l) and l[i] == " ": i += 1 if i < min_indent: min_...
456,891
Write the class doc to `f`. Args: f: File to write to. prefix: Prefix for names. cls: class object. name: name to use.
def _write_class_markdown_to_file(self, f, name, cls): # Build the list of class methods to document. methods = dict(self.get_class_members(name, cls)) # Used later to check if any methods were called out in the class # docstring. num_methods = len(methods) try: self._write_docstring_...
456,896
Prints this library to file `f`. Args: f: File to write to. Returns: Dictionary of documented members.
def write_markdown_to_file(self, f): print("---", file=f) print("---", file=f) print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f) print("", file=f) # TODO(touts): Do not insert these. Let the doc writer put them in # the module docstring explicitly. print("#", self....
456,898
Writes the leftover members to `f`. Args: f: File to write to. catch_all: If true, document all missing symbols from any module. Otherwise, document missing symbols from just this module.
def write_other_members(self, f, catch_all=False): if catch_all: names = self._members.items() else: names = inspect.getmembers(self._module) leftovers = [] for name, _ in names: if name in self._members and name not in self._documented: leftovers.append(name) if lefto...
456,899
config: values for command line options config_file: -c output_dag: -d args: command line argument passed to workflow. However, if a dictionary is passed, then it is assumed to be a nested workflow where parameters are made immediately av...
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs) -> None: # the worker process knows configuration file, command line argument etc super(SoS_Worker, self).__init__(**kwargs) # self.config = config # there can be multiple jobs for th...
456,996
Takes input that must be parsed Note: Attach all your listeners before calling this method Args: data (str): input json string
def consume(self, data): if not self._started: self.fire(JSONStreamer.DOC_START_EVENT) self._started = True self._file_like.write(data) try: self._parser.parse(self._file_like) except YajlError as ye: raise JSONStreamerException(ye...
457,734
Takes input that must be parsed Note: Attach all your listeners before calling this method Args: data (str): input json string
def consume(self, data): try: self._streamer.consume(data) except YajlError as ye: print(ye.value) raise JSONStreamerException(ye.value)
457,744
Checks if specified glyph has any ink. That is, that it has at least one defined contour associated. Composites are considered to have ink if any of their components have ink. Args: font: the font glyph_name: The name of the glyph to check for ink. Returns: True if the font has at least...
def glyph_has_ink(font: TTFont, name: Text) -> bool: if 'glyf' in font: return ttf_glyph_has_ink(font, name) elif ('CFF ' in font) or ('CFF2' in font): return cff_glyph_has_ink(font, name) else: raise Exception("Could not find 'glyf', 'CFF ', or 'CFF2' table.")
458,385
Get device temperature reading. Params: - sensors: optional list of sensors to get a reading for, examples: [0,] - get reading for sensor 0 [0, 1,] - get reading for sensors 0 and 1 None - get readings for all sensors
def get_temperatures(self, sensors=None): _sensors = sensors if _sensors is None: _sensors = list(range(0, self._sensor_count)) if not set(_sensors).issubset(list(range(0, self._sensor_count))): raise ValueError( 'Some or all of the sensors in th...
459,260
Get device humidity reading. Params: - sensors: optional list of sensors to get a reading for, examples: [0,] - get reading for sensor 0 [0, 1,] - get reading for sensors 0 and 1 None - get readings for all sensors
def get_humidity(self, sensors=None): _sensors = sensors if _sensors is None: _sensors = list(range(0, self._sensor_count)) if not set(_sensors).issubset(list(range(0, self._sensor_count))): raise ValueError( 'Some or all of the sensors in the li...
459,261
Constructs a server instance. Args: listener (EventListener): the object that listens and keeps celery events dispatcher (StreamingDispatcher): the mechanism to dispatch data to clients
def __init__(self, listener, dispatcher): logger.info('Creating %s', ClearlyServer.__name__) self.listener = listener self.dispatcher = dispatcher
459,784
Supports converting internal TaskData and WorkerData, as well as celery Task and Worker to proto buffers messages. Args: event (Union[TaskData|Task|WorkerData|Worker]): Returns: ProtoBuf object
def _event_to_pb(event): if isinstance(event, (TaskData, Task)): key, klass = 'task', clearly_pb2.TaskMessage elif isinstance(event, (WorkerData, Worker)): key, klass = 'worker', clearly_pb2.WorkerMessage else: raise ValueError('unknown event') ...
459,786
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.capture_realtime = channel.unary_stream( '/ClearlyServer/capture_realtime', request_serializer=protos_dot_clearly__pb2.CaptureRequest.SerializeToString, response_deserializer=protos_dot_clearly__pb2.RealtimeEventMessage.FromString, ) self.fi...
459,796
Given a compiled regex and a negate, find if any of the values match. Args: regex (Pattern): negate (bool): *values (str): Returns:
def accepts(regex, negate, *values): return any(v and regex.search(v) for v in values) != negate
459,798
Returns a copy of the PB object, with some fields updated. Args: pb_message: **kwds: Returns:
def copy_update(pb_message, **kwds): result = pb_message.__class__() result.CopyFrom(pb_message) for k, v in kwds.items(): setattr(result, k, v) return result
459,799
Constructs a client dispatcher instance. Args: queue_input (Queue): to receive from event listener
def __init__(self, queue_input): logger.info('Creating %s', StreamingDispatcher.__name__) self.queue_input = queue_input self.observers = [] # should not need any lock, thanks to GIL self.task_states = setup_task_states() # type: ExpectedStateHandler self.worker_state...
459,800
Constructs an event listener instance. Args: broker (str): the broker being used by the celery system. queue_output (Queue): to send to streaming dispatcher. backend (str): the result backend being used by the celery system. max_tasks_in_memory (int): max tasks s...
def __init__(self, broker, queue_output, backend=None, max_tasks_in_memory=None, max_workers_in_memory=None): self._app = Celery(broker=broker, backend=backend) self._queue_output = queue_output from celery.backends.base import DisabledBackend self._use_result_...
459,809
Constructs a client instance. Args: host (str): the hostname of the server port (int): the port of the server
def __init__(self, host='localhost', port=12223): channel = grpc.insecure_channel('{}:{}'.format(host, port)) self._stub = clearly_pb2_grpc.ClearlyServerStub(channel)
459,817
Finds one specific task. Args: task_uuid (str): the task id
def task(self, task_uuid): request = clearly_pb2.FindTaskRequest(task_uuid=task_uuid) task = self._stub.find_task(request) if task.uuid: ClearlyClient._display_task(task, True, True, True) else: print(EMPTY)
459,823
Linear operator _vec() from Wiktorsson2001 p478 Args: A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each interval of time j in 0..N-1 Returns: array of shape N x mn x 1, made by stacking the columns of matrix A[j] on top of each other, for each j in 0..N-1
def _vec(A): N, m, n = A.shape return A.reshape((N, m*n, 1), order='F')
459,846
Shows logs of nodes in this cluster, by default, with multitail. If you need to alter the command or options, change CCM_MULTITAIL_CMD . Params: @selected_nodes_names : a list-like object that contains names of nodes to be shown. If empty, this will show all nodes in the cluster.
def show_logs(self, selected_nodes_names=None): if selected_nodes_names is None: selected_nodes_names = [] if len(self.nodes) == 0: print_("There are no nodes in this cluster yet.") return nodes = sorted(list(self.nodes.values()), key=lambda node: ...
459,900
Get DDO of a particular asset. --- tags: - ddo parameters: - name: did in: path description: DID of the asset. required: true type: string responses: 200: description: successful operation 404: description: This asset DID is not in ...
def get_ddo(did): try: asset_record = dao.get(did) return Response(_sanitize_record(asset_record), 200, content_type='application/json') except Exception as e: logger.error(e) return f'{did} asset DID is not in OceanDB', 404
461,036
Get metadata of a particular asset --- tags: - metadata parameters: - name: did in: path description: DID of the asset. required: true type: string responses: 200: description: successful operation. 404: description: This asset DID ...
def get_metadata(did): try: asset_record = dao.get(did) metadata = _get_metadata(asset_record['service']) return Response(_sanitize_record(metadata), 200, content_type='application/json') except Exception as e: logger.error(e) return f'{did} asset DID is not in Ocean...
461,037
Retire metadata of an asset --- tags: - ddo parameters: - name: did in: path description: DID of the asset. required: true type: string responses: 200: description: successfully deleted 404: description: This asset DID is not in Oce...
def retire(did): try: if dao.get(did) is None: return 'This asset DID is not in OceanDB', 404 else: dao.delete(did) return 'Succesfully deleted', 200 except Exception as err: return f'Some error: {str(err)}', 500
461,040
Validate metadata content. --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: Asset metadata. schema: type: object responses: 200: description: successfully request. ...
def validate(): assert isinstance(request.json, dict), 'invalid payload format.' data = request.json assert isinstance(data, dict), 'invalid `body` type, should be formatted as a dict.' if is_valid_dict(data): return jsonify(True) else: error_list = list() for err in lis...
461,045
open()-replacement that automatically handles zip files. This assumes there is at most one .zip in the file path. Args: filepath: the path to the file to open. Returns: An open file-like object.
def OpenFile(self, filepath): archive = False if '.zip/' in filepath: archive = True archive_type = '.zip' if '.par/' in filepath: archive = True archive_type = '.par' if archive: path, archived_file = filepath.split(archive_type) path += archive_type zip_f...
462,106
Handles sanitizing of unserializable objects for Json. For instances of heap types, we take the class dict, augment it with the instance's __dict__, tag it and transmit it over to the RPC client to be reconstructed there. (Works with both old and new style classes) Args: obj: The object to Json-s...
def _UnserializableObjectFallback(self, obj): if isinstance(obj, libpython.PyInstanceObjectPtr): # old-style classes use 'classobj'/'instance' # get class attribute dictionary in_class = obj.pyop_field('in_class') result_dict = in_class.pyop_field('cl_dict').proxyval(set()) # let...
462,110
Make sure our position matches the request. Args: pid: The process ID of the target process tid: The python thread ident of the target thread frame_depth: The 'depth' of the requested frame in the frame stack Raises: PositionUnavailableException: If the requested process, thread or fram...
def EnsureGdbPosition(self, pid, tid, frame_depth): position = [pid, tid, frame_depth] if not pid: return if not self.IsAttached(): try: self.Attach(position) except gdb.error as exc: raise PositionUnavailableException(exc.message) if gdb.selected_inferior().pid !=...
462,116
Handles transparent proxying to gdb subprocess. This returns a lambda which, when called, sends an RPC request to gdb Args: name: The method to call within GdbService Returns: The result of the RPC.
def __getattr__(self, name): return lambda *args, **kwargs: self._Execute(name, *args, **kwargs)
462,141
Send an RPC request to the gdb-internal python. Blocks for 3 seconds by default and returns any results. Args: funcname: the name of the function to call. *args: the function's arguments. **kwargs: Only the key 'wait_for_completion' is inspected, which decides whether to wait forever ...
def _Execute(self, funcname, *args, **kwargs): wait_for_completion = kwargs.get('wait_for_completion', False) rpc_dict = {'func': funcname, 'args': args} self._Send(json.dumps(rpc_dict)) timeout = TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT result_string = self._Recv(timeout) ...
462,146
Reinitializes the object with a new pid. Since all modes might need access to this object at any time, this object needs to be long-lived. To make this clear in the API, this shorthand is supplied. Args: pid: the pid of the target process auto_symfile_loading: whether the symbol file should...
def Reinit(self, pid, auto_symfile_loading=True): self.ShutDownGdb() self.__init__(pid, auto_symfile_loading, architecture=self.arch)
462,150
Try to inject python code into current thread. Args: codestring: Python snippet to execute in inferior. (may contain newlines) wait_for_completion: Block until execution of snippet has completed.
def InjectString(self, codestring, wait_for_completion=True): if self.inferior.is_running and self.inferior.gdb.IsAttached(): try: self.inferior.gdb.InjectString( self.inferior.position, codestring, wait_for_completion=wait_for_completion) except RuntimeE...
462,163
Closely emulate the interactive Python console. This method overwrites its superclass' method to specify a different help text and to enable proper handling of the debugger status line. Args: banner: Text to be displayed on interpreter startup.
def interact(self, banner=None): sys.ps1 = getattr(sys, 'ps1', '>>> ') sys.ps2 = getattr(sys, 'ps2', '... ') if banner is None: print ('Pyringe (Python %s.%s.%s) on %s\n%s' % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro, sys.platform, _WELCOME...
462,228
Sends push notifications to the Apple APNS server. Multiple notifications can be sent by sending pairing the token/notification arguments in lists [token1, token2], [notification1, notification2]. Arguments: app_id provisioned app_id to send to token_or_token_list ...
def xmlrpc_notify(self, app_id, token_or_token_list, aps_dict_or_list): d = self.apns_service(app_id).write( encode_notifications( [t.replace(' ', '') for t in token_or_token_list] if (type(token_or_token_list) is list) else token_or_token_list.replace(' ', ''), aps_d...
463,877
Queries the Apple APNS feedback server for inactive app tokens. Returns a list of tuples as (datetime_went_dark, token_str). Arguments: app_id the app_id to query Returns: Feedback tuples like (datetime_expired, token_str)
def xmlrpc_feedback(self, app_id): return self.apns_service(app_id).read().addCallback( lambda r: decode_feedback(r))
463,878
Parse the command line arguments. Args: argv: If not ``None``, use the provided command line arguments for parsing. Otherwise, extract them automatically. Returns: The argparse object representing the parsed arguments.
def parse_arguments( argv: Optional[Sequence[str]] = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description='Git credential helper using pass as the data source.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-m', '--mappi...
463,933
Parse the file containing the mappings from hosts to pass entries. Args: mapping_file: Name of the file to parse. If ``None``, the default file from the XDG location is used.
def parse_mapping(mapping_file: Optional[str]) -> configparser.ConfigParser: LOGGER.debug('Parsing mapping file. Command line: %s', mapping_file) def parse(mapping_file): config = configparser.ConfigParser() config.read_file(mapping_file) return config # give precedence to the...
463,934