repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ergoithz/browsepy
browsepy/compat.py
re_escape
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): ''' Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str ''' escape = '\\{}'.format return ''.join( escape(c) if c in chars or c.isspace() else '\\000' if c == '\x00' else c for c in pattern )
python
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): ''' Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str ''' escape = '\\{}'.format return ''.join( escape(c) if c in chars or c.isspace() else '\\000' if c == '\x00' else c for c in pattern )
[ "def", "re_escape", "(", "pattern", ",", "chars", "=", "frozenset", "(", "\"()[]{}?*+|^$\\\\.-#\"", ")", ")", ":", "escape", "=", "'\\\\{}'", ".", "format", "return", "''", ".", "join", "(", "escape", "(", "c", ")", "if", "c", "in", "chars", "or", "c", ".", "isspace", "(", ")", "else", "'\\\\000'", "if", "c", "==", "'\\x00'", "else", "c", "for", "c", "in", "pattern", ")" ]
Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str
[ "Escape", "all", "special", "regex", "characters", "in", "pattern", ".", "Logic", "taken", "from", "regex", "module", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L297-L312
ergoithz/browsepy
browsepy/plugin/player/__init__.py
register_plugin
def register_plugin(manager): ''' Register blueprints and actions using given plugin manager. :param manager: plugin manager :type manager: browsepy.manager.PluginManager ''' manager.register_blueprint(player) manager.register_mimetype_function(detect_playable_mimetype) # add style tag manager.register_widget( place='styles', type='stylesheet', endpoint='player.static', filename='css/browse.css' ) # register link actions manager.register_widget( place='entry-link', type='link', endpoint='player.audio', filter=PlayableFile.detect ) manager.register_widget( place='entry-link', icon='playlist', type='link', endpoint='player.playlist', filter=PlayListFile.detect ) # register action buttons manager.register_widget( place='entry-actions', css='play', type='button', endpoint='player.audio', filter=PlayableFile.detect ) manager.register_widget( place='entry-actions', css='play', type='button', endpoint='player.playlist', filter=PlayListFile.detect ) # check argument (see `register_arguments`) before registering if manager.get_argument('player_directory_play'): # register header button manager.register_widget( place='header', type='button', endpoint='player.directory', text='Play directory', filter=PlayableDirectory.detect )
python
def register_plugin(manager): ''' Register blueprints and actions using given plugin manager. :param manager: plugin manager :type manager: browsepy.manager.PluginManager ''' manager.register_blueprint(player) manager.register_mimetype_function(detect_playable_mimetype) # add style tag manager.register_widget( place='styles', type='stylesheet', endpoint='player.static', filename='css/browse.css' ) # register link actions manager.register_widget( place='entry-link', type='link', endpoint='player.audio', filter=PlayableFile.detect ) manager.register_widget( place='entry-link', icon='playlist', type='link', endpoint='player.playlist', filter=PlayListFile.detect ) # register action buttons manager.register_widget( place='entry-actions', css='play', type='button', endpoint='player.audio', filter=PlayableFile.detect ) manager.register_widget( place='entry-actions', css='play', type='button', endpoint='player.playlist', filter=PlayListFile.detect ) # check argument (see `register_arguments`) before registering if manager.get_argument('player_directory_play'): # register header button manager.register_widget( place='header', type='button', endpoint='player.directory', text='Play directory', filter=PlayableDirectory.detect )
[ "def", "register_plugin", "(", "manager", ")", ":", "manager", ".", "register_blueprint", "(", "player", ")", "manager", ".", "register_mimetype_function", "(", "detect_playable_mimetype", ")", "# add style tag", "manager", ".", "register_widget", "(", "place", "=", "'styles'", ",", "type", "=", "'stylesheet'", ",", "endpoint", "=", "'player.static'", ",", "filename", "=", "'css/browse.css'", ")", "# register link actions", "manager", ".", "register_widget", "(", "place", "=", "'entry-link'", ",", "type", "=", "'link'", ",", "endpoint", "=", "'player.audio'", ",", "filter", "=", "PlayableFile", ".", "detect", ")", "manager", ".", "register_widget", "(", "place", "=", "'entry-link'", ",", "icon", "=", "'playlist'", ",", "type", "=", "'link'", ",", "endpoint", "=", "'player.playlist'", ",", "filter", "=", "PlayListFile", ".", "detect", ")", "# register action buttons", "manager", ".", "register_widget", "(", "place", "=", "'entry-actions'", ",", "css", "=", "'play'", ",", "type", "=", "'button'", ",", "endpoint", "=", "'player.audio'", ",", "filter", "=", "PlayableFile", ".", "detect", ")", "manager", ".", "register_widget", "(", "place", "=", "'entry-actions'", ",", "css", "=", "'play'", ",", "type", "=", "'button'", ",", "endpoint", "=", "'player.playlist'", ",", "filter", "=", "PlayListFile", ".", "detect", ")", "# check argument (see `register_arguments`) before registering", "if", "manager", ".", "get_argument", "(", "'player_directory_play'", ")", ":", "# register header button", "manager", ".", "register_widget", "(", "place", "=", "'header'", ",", "type", "=", "'button'", ",", "endpoint", "=", "'player.directory'", ",", "text", "=", "'Play directory'", ",", "filter", "=", "PlayableDirectory", ".", "detect", ")" ]
Register blueprints and actions using given plugin manager. :param manager: plugin manager :type manager: browsepy.manager.PluginManager
[ "Register", "blueprints", "and", "actions", "using", "given", "plugin", "manager", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/plugin/player/__init__.py#L93-L151
ergoithz/browsepy
browsepy/file.py
fmt_size
def fmt_size(size, binary=True): ''' Get size and unit. :param size: size in bytes :type size: int :param binary: whether use binary or standard units, defaults to True :type binary: bool :return: size and unit :rtype: tuple of int and unit as str ''' if binary: fmt_sizes = binary_units fmt_divider = 1024. else: fmt_sizes = standard_units fmt_divider = 1000. for fmt in fmt_sizes[:-1]: if size < 1000: return (size, fmt) size /= fmt_divider return size, fmt_sizes[-1]
python
def fmt_size(size, binary=True): ''' Get size and unit. :param size: size in bytes :type size: int :param binary: whether use binary or standard units, defaults to True :type binary: bool :return: size and unit :rtype: tuple of int and unit as str ''' if binary: fmt_sizes = binary_units fmt_divider = 1024. else: fmt_sizes = standard_units fmt_divider = 1000. for fmt in fmt_sizes[:-1]: if size < 1000: return (size, fmt) size /= fmt_divider return size, fmt_sizes[-1]
[ "def", "fmt_size", "(", "size", ",", "binary", "=", "True", ")", ":", "if", "binary", ":", "fmt_sizes", "=", "binary_units", "fmt_divider", "=", "1024.", "else", ":", "fmt_sizes", "=", "standard_units", "fmt_divider", "=", "1000.", "for", "fmt", "in", "fmt_sizes", "[", ":", "-", "1", "]", ":", "if", "size", "<", "1000", ":", "return", "(", "size", ",", "fmt", ")", "size", "/=", "fmt_divider", "return", "size", ",", "fmt_sizes", "[", "-", "1", "]" ]
Get size and unit. :param size: size in bytes :type size: int :param binary: whether use binary or standard units, defaults to True :type binary: bool :return: size and unit :rtype: tuple of int and unit as str
[ "Get", "size", "and", "unit", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L721-L742
ergoithz/browsepy
browsepy/file.py
relativize_path
def relativize_path(path, base, os_sep=os.sep): ''' Make absolute path relative to an absolute base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path component separator, defaults to current OS separator :type os_sep: str :return: relative path :rtype: str or unicode :raises OutsideDirectoryBase: if path is not below base ''' if not check_base(path, base, os_sep): raise OutsideDirectoryBase("%r is not under %r" % (path, base)) prefix_len = len(base) if not base.endswith(os_sep): prefix_len += len(os_sep) return path[prefix_len:]
python
def relativize_path(path, base, os_sep=os.sep): ''' Make absolute path relative to an absolute base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path component separator, defaults to current OS separator :type os_sep: str :return: relative path :rtype: str or unicode :raises OutsideDirectoryBase: if path is not below base ''' if not check_base(path, base, os_sep): raise OutsideDirectoryBase("%r is not under %r" % (path, base)) prefix_len = len(base) if not base.endswith(os_sep): prefix_len += len(os_sep) return path[prefix_len:]
[ "def", "relativize_path", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "if", "not", "check_base", "(", "path", ",", "base", ",", "os_sep", ")", ":", "raise", "OutsideDirectoryBase", "(", "\"%r is not under %r\"", "%", "(", "path", ",", "base", ")", ")", "prefix_len", "=", "len", "(", "base", ")", "if", "not", "base", ".", "endswith", "(", "os_sep", ")", ":", "prefix_len", "+=", "len", "(", "os_sep", ")", "return", "path", "[", "prefix_len", ":", "]" ]
Make absolute path relative to an absolute base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path component separator, defaults to current OS separator :type os_sep: str :return: relative path :rtype: str or unicode :raises OutsideDirectoryBase: if path is not below base
[ "Make", "absolute", "path", "relative", "to", "an", "absolute", "base", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L745-L764
ergoithz/browsepy
browsepy/file.py
abspath_to_urlpath
def abspath_to_urlpath(path, base, os_sep=os.sep): ''' Make filesystem absolute path uri relative using given absolute base path. :param path: absolute path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: relative uri :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base ''' return relativize_path(path, base, os_sep).replace(os_sep, '/')
python
def abspath_to_urlpath(path, base, os_sep=os.sep): ''' Make filesystem absolute path uri relative using given absolute base path. :param path: absolute path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: relative uri :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base ''' return relativize_path(path, base, os_sep).replace(os_sep, '/')
[ "def", "abspath_to_urlpath", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "return", "relativize_path", "(", "path", ",", "base", ",", "os_sep", ")", ".", "replace", "(", "os_sep", ",", "'/'", ")" ]
Make filesystem absolute path uri relative using given absolute base path. :param path: absolute path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: relative uri :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base
[ "Make", "filesystem", "absolute", "path", "uri", "relative", "using", "given", "absolute", "base", "path", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L767-L778
ergoithz/browsepy
browsepy/file.py
urlpath_to_abspath
def urlpath_to_abspath(path, base, os_sep=os.sep): ''' Make uri relative path fs absolute using a given absolute base path. :param path: relative path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: absolute path :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base ''' prefix = base if base.endswith(os_sep) else base + os_sep realpath = os.path.abspath(prefix + path.replace('/', os_sep)) if check_path(base, realpath) or check_under_base(realpath, base): return realpath raise OutsideDirectoryBase("%r is not under %r" % (realpath, base))
python
def urlpath_to_abspath(path, base, os_sep=os.sep): ''' Make uri relative path fs absolute using a given absolute base path. :param path: relative path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: absolute path :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base ''' prefix = base if base.endswith(os_sep) else base + os_sep realpath = os.path.abspath(prefix + path.replace('/', os_sep)) if check_path(base, realpath) or check_under_base(realpath, base): return realpath raise OutsideDirectoryBase("%r is not under %r" % (realpath, base))
[ "def", "urlpath_to_abspath", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "prefix", "=", "base", "if", "base", ".", "endswith", "(", "os_sep", ")", "else", "base", "+", "os_sep", "realpath", "=", "os", ".", "path", ".", "abspath", "(", "prefix", "+", "path", ".", "replace", "(", "'/'", ",", "os_sep", ")", ")", "if", "check_path", "(", "base", ",", "realpath", ")", "or", "check_under_base", "(", "realpath", ",", "base", ")", ":", "return", "realpath", "raise", "OutsideDirectoryBase", "(", "\"%r is not under %r\"", "%", "(", "realpath", ",", "base", ")", ")" ]
Make uri relative path fs absolute using a given absolute base path. :param path: relative path :param base: absolute base path :param os_sep: path component separator, defaults to current OS separator :return: absolute path :rtype: str or unicode :raises OutsideDirectoryBase: if resulting path is not below base
[ "Make", "uri", "relative", "path", "fs", "absolute", "using", "a", "given", "absolute", "base", "path", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L781-L796
ergoithz/browsepy
browsepy/file.py
generic_filename
def generic_filename(path): ''' Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path) ''' for sep in common_path_separators: if sep in path: _, path = path.rsplit(sep, 1) return path
python
def generic_filename(path): ''' Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path) ''' for sep in common_path_separators: if sep in path: _, path = path.rsplit(sep, 1) return path
[ "def", "generic_filename", "(", "path", ")", ":", "for", "sep", "in", "common_path_separators", ":", "if", "sep", "in", "path", ":", "_", ",", "path", "=", "path", ".", "rsplit", "(", "sep", ",", "1", ")", "return", "path" ]
Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path)
[ "Extract", "filename", "of", "given", "path", "os", "-", "indepently", "taking", "care", "of", "known", "path", "separators", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L799-L812
ergoithz/browsepy
browsepy/file.py
clean_restricted_chars
def clean_restricted_chars(path, restricted_chars=restricted_chars): ''' Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path) ''' for character in restricted_chars: path = path.replace(character, '_') return path
python
def clean_restricted_chars(path, restricted_chars=restricted_chars): ''' Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path) ''' for character in restricted_chars: path = path.replace(character, '_') return path
[ "def", "clean_restricted_chars", "(", "path", ",", "restricted_chars", "=", "restricted_chars", ")", ":", "for", "character", "in", "restricted_chars", ":", "path", "=", "path", ".", "replace", "(", "character", ",", "'_'", ")", "return", "path" ]
Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path)
[ "Get", "path", "without", "restricted", "characters", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L815-L825
ergoithz/browsepy
browsepy/file.py
check_forbidden_filename
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool ''' return ( filename in restricted_names or destiny_os == 'nt' and filename.split('.', 1)[0].upper() in nt_device_names )
python
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool ''' return ( filename in restricted_names or destiny_os == 'nt' and filename.split('.', 1)[0].upper() in nt_device_names )
[ "def", "check_forbidden_filename", "(", "filename", ",", "destiny_os", "=", "os", ".", "name", ",", "restricted_names", "=", "restricted_names", ")", ":", "return", "(", "filename", "in", "restricted_names", "or", "destiny_os", "==", "'nt'", "and", "filename", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", ".", "upper", "(", ")", "in", "nt_device_names", ")" ]
Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool
[ "Get", "if", "given", "filename", "is", "forbidden", "for", "current", "OS", "or", "filesystem", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L828-L844
ergoithz/browsepy
browsepy/file.py
check_path
def check_path(path, base, os_sep=os.sep): ''' Check if both given paths are equal. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :type base: str :return: wether two path are equal or not :rtype: bool ''' base = base[:-len(os_sep)] if base.endswith(os_sep) else base return os.path.normcase(path) == os.path.normcase(base)
python
def check_path(path, base, os_sep=os.sep): ''' Check if both given paths are equal. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :type base: str :return: wether two path are equal or not :rtype: bool ''' base = base[:-len(os_sep)] if base.endswith(os_sep) else base return os.path.normcase(path) == os.path.normcase(base)
[ "def", "check_path", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "base", "=", "base", "[", ":", "-", "len", "(", "os_sep", ")", "]", "if", "base", ".", "endswith", "(", "os_sep", ")", "else", "base", "return", "os", ".", "path", ".", "normcase", "(", "path", ")", "==", "os", ".", "path", ".", "normcase", "(", "base", ")" ]
Check if both given paths are equal. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :type base: str :return: wether two path are equal or not :rtype: bool
[ "Check", "if", "both", "given", "paths", "are", "equal", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L847-L861
ergoithz/browsepy
browsepy/file.py
check_base
def check_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under or given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether path is under given base or not :rtype: bool ''' return ( check_path(path, base, os_sep) or check_under_base(path, base, os_sep) )
python
def check_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under or given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether path is under given base or not :rtype: bool ''' return ( check_path(path, base, os_sep) or check_under_base(path, base, os_sep) )
[ "def", "check_base", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "return", "(", "check_path", "(", "path", ",", "base", ",", "os_sep", ")", "or", "check_under_base", "(", "path", ",", "base", ",", "os_sep", ")", ")" ]
Check if given absolute path is under or given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether path is under given base or not :rtype: bool
[ "Check", "if", "given", "absolute", "path", "is", "under", "or", "given", "base", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L864-L879
ergoithz/browsepy
browsepy/file.py
check_under_base
def check_under_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether file is under given base or not :rtype: bool ''' prefix = base if base.endswith(os_sep) else base + os_sep return os.path.normcase(path).startswith(os.path.normcase(prefix))
python
def check_under_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether file is under given base or not :rtype: bool ''' prefix = base if base.endswith(os_sep) else base + os_sep return os.path.normcase(path).startswith(os.path.normcase(prefix))
[ "def", "check_under_base", "(", "path", ",", "base", ",", "os_sep", "=", "os", ".", "sep", ")", ":", "prefix", "=", "base", "if", "base", ".", "endswith", "(", "os_sep", ")", "else", "base", "+", "os_sep", "return", "os", ".", "path", ".", "normcase", "(", "path", ")", ".", "startswith", "(", "os", ".", "path", ".", "normcase", "(", "prefix", ")", ")" ]
Check if given absolute path is under given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether file is under given base or not :rtype: bool
[ "Check", "if", "given", "absolute", "path", "is", "under", "given", "base", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L882-L895
ergoithz/browsepy
browsepy/file.py
secure_filename
def secure_filename(path, destiny_os=os.name, fs_encoding=compat.FS_ENCODING): ''' Get rid of parent path components and special filenames. If path is invalid or protected, return empty string. :param path: unsafe path, only basename will be used :type: str :param destiny_os: destination operative system (defaults to os.name) :type destiny_os: str :param fs_encoding: fs path encoding (defaults to detected) :type fs_encoding: str :return: filename or empty string :rtype: str ''' path = generic_filename(path) path = clean_restricted_chars( path, restricted_chars=( nt_restricted_chars if destiny_os == 'nt' else restricted_chars )) path = path.strip(' .') # required by nt, recommended for others if check_forbidden_filename(path, destiny_os=destiny_os): return '' if isinstance(path, bytes): path = path.decode('latin-1', errors=underscore_replace) # Decode and recover from filesystem encoding in order to strip unwanted # characters out kwargs = { 'os_name': destiny_os, 'fs_encoding': fs_encoding, 'errors': underscore_replace, } fs_encoded_path = compat.fsencode(path, **kwargs) fs_decoded_path = compat.fsdecode(fs_encoded_path, **kwargs) return fs_decoded_path
python
def secure_filename(path, destiny_os=os.name, fs_encoding=compat.FS_ENCODING): ''' Get rid of parent path components and special filenames. If path is invalid or protected, return empty string. :param path: unsafe path, only basename will be used :type: str :param destiny_os: destination operative system (defaults to os.name) :type destiny_os: str :param fs_encoding: fs path encoding (defaults to detected) :type fs_encoding: str :return: filename or empty string :rtype: str ''' path = generic_filename(path) path = clean_restricted_chars( path, restricted_chars=( nt_restricted_chars if destiny_os == 'nt' else restricted_chars )) path = path.strip(' .') # required by nt, recommended for others if check_forbidden_filename(path, destiny_os=destiny_os): return '' if isinstance(path, bytes): path = path.decode('latin-1', errors=underscore_replace) # Decode and recover from filesystem encoding in order to strip unwanted # characters out kwargs = { 'os_name': destiny_os, 'fs_encoding': fs_encoding, 'errors': underscore_replace, } fs_encoded_path = compat.fsencode(path, **kwargs) fs_decoded_path = compat.fsdecode(fs_encoded_path, **kwargs) return fs_decoded_path
[ "def", "secure_filename", "(", "path", ",", "destiny_os", "=", "os", ".", "name", ",", "fs_encoding", "=", "compat", ".", "FS_ENCODING", ")", ":", "path", "=", "generic_filename", "(", "path", ")", "path", "=", "clean_restricted_chars", "(", "path", ",", "restricted_chars", "=", "(", "nt_restricted_chars", "if", "destiny_os", "==", "'nt'", "else", "restricted_chars", ")", ")", "path", "=", "path", ".", "strip", "(", "' .'", ")", "# required by nt, recommended for others", "if", "check_forbidden_filename", "(", "path", ",", "destiny_os", "=", "destiny_os", ")", ":", "return", "''", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "path", "=", "path", ".", "decode", "(", "'latin-1'", ",", "errors", "=", "underscore_replace", ")", "# Decode and recover from filesystem encoding in order to strip unwanted", "# characters out", "kwargs", "=", "{", "'os_name'", ":", "destiny_os", ",", "'fs_encoding'", ":", "fs_encoding", ",", "'errors'", ":", "underscore_replace", ",", "}", "fs_encoded_path", "=", "compat", ".", "fsencode", "(", "path", ",", "*", "*", "kwargs", ")", "fs_decoded_path", "=", "compat", ".", "fsdecode", "(", "fs_encoded_path", ",", "*", "*", "kwargs", ")", "return", "fs_decoded_path" ]
Get rid of parent path components and special filenames. If path is invalid or protected, return empty string. :param path: unsafe path, only basename will be used :type: str :param destiny_os: destination operative system (defaults to os.name) :type destiny_os: str :param fs_encoding: fs path encoding (defaults to detected) :type fs_encoding: str :return: filename or empty string :rtype: str
[ "Get", "rid", "of", "parent", "path", "components", "and", "special", "filenames", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L898-L938
ergoithz/browsepy
browsepy/file.py
alternative_filename
def alternative_filename(filename, attempt=None): ''' Generates an alternative version of given filename. If an number attempt parameter is given, will be used on the alternative name, a random value will be used otherwise. :param filename: original filename :param attempt: optional attempt number, defaults to null :return: new filename :rtype: str or unicode ''' filename_parts = filename.rsplit(u'.', 2) name = filename_parts[0] ext = ''.join(u'.%s' % ext for ext in filename_parts[1:]) if attempt is None: choose = random.choice extra = u' %s' % ''.join(choose(fs_safe_characters) for i in range(8)) else: extra = u' (%d)' % attempt return u'%s%s%s' % (name, extra, ext)
python
def alternative_filename(filename, attempt=None): ''' Generates an alternative version of given filename. If an number attempt parameter is given, will be used on the alternative name, a random value will be used otherwise. :param filename: original filename :param attempt: optional attempt number, defaults to null :return: new filename :rtype: str or unicode ''' filename_parts = filename.rsplit(u'.', 2) name = filename_parts[0] ext = ''.join(u'.%s' % ext for ext in filename_parts[1:]) if attempt is None: choose = random.choice extra = u' %s' % ''.join(choose(fs_safe_characters) for i in range(8)) else: extra = u' (%d)' % attempt return u'%s%s%s' % (name, extra, ext)
[ "def", "alternative_filename", "(", "filename", ",", "attempt", "=", "None", ")", ":", "filename_parts", "=", "filename", ".", "rsplit", "(", "u'.'", ",", "2", ")", "name", "=", "filename_parts", "[", "0", "]", "ext", "=", "''", ".", "join", "(", "u'.%s'", "%", "ext", "for", "ext", "in", "filename_parts", "[", "1", ":", "]", ")", "if", "attempt", "is", "None", ":", "choose", "=", "random", ".", "choice", "extra", "=", "u' %s'", "%", "''", ".", "join", "(", "choose", "(", "fs_safe_characters", ")", "for", "i", "in", "range", "(", "8", ")", ")", "else", ":", "extra", "=", "u' (%d)'", "%", "attempt", "return", "u'%s%s%s'", "%", "(", "name", ",", "extra", ",", "ext", ")" ]
Generates an alternative version of given filename. If an number attempt parameter is given, will be used on the alternative name, a random value will be used otherwise. :param filename: original filename :param attempt: optional attempt number, defaults to null :return: new filename :rtype: str or unicode
[ "Generates", "an", "alternative", "version", "of", "given", "filename", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L941-L961
ergoithz/browsepy
browsepy/file.py
scandir
def scandir(path, app=None): ''' Config-aware scandir. Currently, only aware of ``exclude_fnc``. :param path: absolute path :type path: str :param app: flask application :type app: flask.Flask or None :returns: filtered scandir entries :rtype: iterator ''' exclude = app and app.config.get('exclude_fnc') if exclude: return ( item for item in compat.scandir(path) if not exclude(item.path) ) return compat.scandir(path)
python
def scandir(path, app=None): ''' Config-aware scandir. Currently, only aware of ``exclude_fnc``. :param path: absolute path :type path: str :param app: flask application :type app: flask.Flask or None :returns: filtered scandir entries :rtype: iterator ''' exclude = app and app.config.get('exclude_fnc') if exclude: return ( item for item in compat.scandir(path) if not exclude(item.path) ) return compat.scandir(path)
[ "def", "scandir", "(", "path", ",", "app", "=", "None", ")", ":", "exclude", "=", "app", "and", "app", ".", "config", ".", "get", "(", "'exclude_fnc'", ")", "if", "exclude", ":", "return", "(", "item", "for", "item", "in", "compat", ".", "scandir", "(", "path", ")", "if", "not", "exclude", "(", "item", ".", "path", ")", ")", "return", "compat", ".", "scandir", "(", "path", ")" ]
Config-aware scandir. Currently, only aware of ``exclude_fnc``. :param path: absolute path :type path: str :param app: flask application :type app: flask.Flask or None :returns: filtered scandir entries :rtype: iterator
[ "Config", "-", "aware", "scandir", ".", "Currently", "only", "aware", "of", "exclude_fnc", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L964-L982
ergoithz/browsepy
browsepy/file.py
Node.is_excluded
def is_excluded(self): ''' Get if current node shouldn't be shown, using :attt:`app` config's exclude_fnc. :returns: True if excluded, False otherwise ''' exclude = self.app and self.app.config['exclude_fnc'] return exclude and exclude(self.path)
python
def is_excluded(self): ''' Get if current node shouldn't be shown, using :attt:`app` config's exclude_fnc. :returns: True if excluded, False otherwise ''' exclude = self.app and self.app.config['exclude_fnc'] return exclude and exclude(self.path)
[ "def", "is_excluded", "(", "self", ")", ":", "exclude", "=", "self", ".", "app", "and", "self", ".", "app", ".", "config", "[", "'exclude_fnc'", "]", "return", "exclude", "and", "exclude", "(", "self", ".", "path", ")" ]
Get if current node shouldn't be shown, using :attt:`app` config's exclude_fnc. :returns: True if excluded, False otherwise
[ "Get", "if", "current", "node", "shouldn", "t", "be", "shown", "using", ":", "attt", ":", "app", "config", "s", "exclude_fnc", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L68-L76
ergoithz/browsepy
browsepy/file.py
Node.widgets
def widgets(self): ''' List widgets with filter return True for this node (or without filter). Remove button is prepended if :property:can_remove returns true. :returns: list of widgets :rtype: list of namedtuple instances ''' widgets = [] if self.can_remove: widgets.append( self.plugin_manager.create_widget( 'entry-actions', 'button', file=self, css='remove', endpoint='remove' ) ) return widgets + self.plugin_manager.get_widgets(file=self)
python
def widgets(self): ''' List widgets with filter return True for this node (or without filter). Remove button is prepended if :property:can_remove returns true. :returns: list of widgets :rtype: list of namedtuple instances ''' widgets = [] if self.can_remove: widgets.append( self.plugin_manager.create_widget( 'entry-actions', 'button', file=self, css='remove', endpoint='remove' ) ) return widgets + self.plugin_manager.get_widgets(file=self)
[ "def", "widgets", "(", "self", ")", ":", "widgets", "=", "[", "]", "if", "self", ".", "can_remove", ":", "widgets", ".", "append", "(", "self", ".", "plugin_manager", ".", "create_widget", "(", "'entry-actions'", ",", "'button'", ",", "file", "=", "self", ",", "css", "=", "'remove'", ",", "endpoint", "=", "'remove'", ")", ")", "return", "widgets", "+", "self", ".", "plugin_manager", ".", "get_widgets", "(", "file", "=", "self", ")" ]
List widgets with filter return True for this node (or without filter). Remove button is prepended if :property:can_remove returns true. :returns: list of widgets :rtype: list of namedtuple instances
[ "List", "widgets", "with", "filter", "return", "True", "for", "this", "node", "(", "or", "without", "filter", ")", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L88-L108
ergoithz/browsepy
browsepy/file.py
Node.link
def link(self): ''' Get last widget with place "entry-link". :returns: widget on entry-link (ideally a link one) :rtype: namedtuple instance ''' link = None for widget in self.widgets: if widget.place == 'entry-link': link = widget return link
python
def link(self): ''' Get last widget with place "entry-link". :returns: widget on entry-link (ideally a link one) :rtype: namedtuple instance ''' link = None for widget in self.widgets: if widget.place == 'entry-link': link = widget return link
[ "def", "link", "(", "self", ")", ":", "link", "=", "None", "for", "widget", "in", "self", ".", "widgets", ":", "if", "widget", ".", "place", "==", "'entry-link'", ":", "link", "=", "widget", "return", "link" ]
Get last widget with place "entry-link". :returns: widget on entry-link (ideally a link one) :rtype: namedtuple instance
[ "Get", "last", "widget", "with", "place", "entry", "-", "link", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L111-L122
ergoithz/browsepy
browsepy/file.py
Node.can_remove
def can_remove(self): ''' Get if current node can be removed based on app config's directory_remove. :returns: True if current node can be removed, False otherwise. :rtype: bool ''' dirbase = self.app.config["directory_remove"] return bool(dirbase and check_under_base(self.path, dirbase))
python
def can_remove(self): ''' Get if current node can be removed based on app config's directory_remove. :returns: True if current node can be removed, False otherwise. :rtype: bool ''' dirbase = self.app.config["directory_remove"] return bool(dirbase and check_under_base(self.path, dirbase))
[ "def", "can_remove", "(", "self", ")", ":", "dirbase", "=", "self", ".", "app", ".", "config", "[", "\"directory_remove\"", "]", "return", "bool", "(", "dirbase", "and", "check_under_base", "(", "self", ".", "path", ",", "dirbase", ")", ")" ]
Get if current node can be removed based on app config's directory_remove. :returns: True if current node can be removed, False otherwise. :rtype: bool
[ "Get", "if", "current", "node", "can", "be", "removed", "based", "on", "app", "config", "s", "directory_remove", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L125-L134
ergoithz/browsepy
browsepy/file.py
Node.parent
def parent(self): ''' Get parent node if available based on app config's directory_base. :returns: parent object if available :rtype: Node instance or None ''' if check_path(self.path, self.app.config['directory_base']): return None parent = os.path.dirname(self.path) if self.path else None return self.directory_class(parent, self.app) if parent else None
python
def parent(self): ''' Get parent node if available based on app config's directory_base. :returns: parent object if available :rtype: Node instance or None ''' if check_path(self.path, self.app.config['directory_base']): return None parent = os.path.dirname(self.path) if self.path else None return self.directory_class(parent, self.app) if parent else None
[ "def", "parent", "(", "self", ")", ":", "if", "check_path", "(", "self", ".", "path", ",", "self", ".", "app", ".", "config", "[", "'directory_base'", "]", ")", ":", "return", "None", "parent", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "if", "self", ".", "path", "else", "None", "return", "self", ".", "directory_class", "(", "parent", ",", "self", ".", "app", ")", "if", "parent", "else", "None" ]
Get parent node if available based on app config's directory_base. :returns: parent object if available :rtype: Node instance or None
[ "Get", "parent", "node", "if", "available", "based", "on", "app", "config", "s", "directory_base", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L158-L168
ergoithz/browsepy
browsepy/file.py
Node.ancestors
def ancestors(self): ''' Get list of ancestors until app config's directory_base is reached. :returns: list of ancestors starting from nearest. :rtype: list of Node objects ''' ancestors = [] parent = self.parent while parent: ancestors.append(parent) parent = parent.parent return ancestors
python
def ancestors(self): ''' Get list of ancestors until app config's directory_base is reached. :returns: list of ancestors starting from nearest. :rtype: list of Node objects ''' ancestors = [] parent = self.parent while parent: ancestors.append(parent) parent = parent.parent return ancestors
[ "def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "[", "]", "parent", "=", "self", ".", "parent", "while", "parent", ":", "ancestors", ".", "append", "(", "parent", ")", "parent", "=", "parent", ".", "parent", "return", "ancestors" ]
Get list of ancestors until app config's directory_base is reached. :returns: list of ancestors starting from nearest. :rtype: list of Node objects
[ "Get", "list", "of", "ancestors", "until", "app", "config", "s", "directory_base", "is", "reached", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L171-L183
ergoithz/browsepy
browsepy/file.py
Node.modified
def modified(self): ''' Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str ''' try: dt = datetime.datetime.fromtimestamp(self.stats.st_mtime) return dt.strftime('%Y.%m.%d %H:%M:%S') except OSError: return None
python
def modified(self): ''' Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str ''' try: dt = datetime.datetime.fromtimestamp(self.stats.st_mtime) return dt.strftime('%Y.%m.%d %H:%M:%S') except OSError: return None
[ "def", "modified", "(", "self", ")", ":", "try", ":", "dt", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "self", ".", "stats", ".", "st_mtime", ")", "return", "dt", ".", "strftime", "(", "'%Y.%m.%d %H:%M:%S'", ")", "except", "OSError", ":", "return", "None" ]
Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str
[ "Get", "human", "-", "readable", "last", "modification", "date", "-", "time", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L186-L197
ergoithz/browsepy
browsepy/file.py
Node.from_urlpath
def from_urlpath(cls, path, app=None): ''' Alternative constructor which accepts a path as taken from URL and uses the given app or the current app config to get the real path. If class has attribute `generic` set to True, `directory_class` or `file_class` will be used as type. :param path: relative path as from URL :param app: optional, flask application :return: file object pointing to path :rtype: File ''' app = app or current_app base = app.config['directory_base'] path = urlpath_to_abspath(path, base) if not cls.generic: kls = cls elif os.path.isdir(path): kls = cls.directory_class else: kls = cls.file_class return kls(path=path, app=app)
python
def from_urlpath(cls, path, app=None): ''' Alternative constructor which accepts a path as taken from URL and uses the given app or the current app config to get the real path. If class has attribute `generic` set to True, `directory_class` or `file_class` will be used as type. :param path: relative path as from URL :param app: optional, flask application :return: file object pointing to path :rtype: File ''' app = app or current_app base = app.config['directory_base'] path = urlpath_to_abspath(path, base) if not cls.generic: kls = cls elif os.path.isdir(path): kls = cls.directory_class else: kls = cls.file_class return kls(path=path, app=app)
[ "def", "from_urlpath", "(", "cls", ",", "path", ",", "app", "=", "None", ")", ":", "app", "=", "app", "or", "current_app", "base", "=", "app", ".", "config", "[", "'directory_base'", "]", "path", "=", "urlpath_to_abspath", "(", "path", ",", "base", ")", "if", "not", "cls", ".", "generic", ":", "kls", "=", "cls", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "kls", "=", "cls", ".", "directory_class", "else", ":", "kls", "=", "cls", ".", "file_class", "return", "kls", "(", "path", "=", "path", ",", "app", "=", "app", ")" ]
Alternative constructor which accepts a path as taken from URL and uses the given app or the current app config to get the real path. If class has attribute `generic` set to True, `directory_class` or `file_class` will be used as type. :param path: relative path as from URL :param app: optional, flask application :return: file object pointing to path :rtype: File
[ "Alternative", "constructor", "which", "accepts", "a", "path", "as", "taken", "from", "URL", "and", "uses", "the", "given", "app", "or", "the", "current", "app", "config", "to", "get", "the", "real", "path", "." ]
train
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L274-L296
brutasse/graphite-api
graphite_api/finders/whisper.py
WhisperFinder._find_paths
def _find_paths(self, current_dir, patterns): """Recursively generates absolute paths whose components underneath current_dir match the corresponding pattern in patterns""" pattern = patterns[0] patterns = patterns[1:] has_wildcard = is_pattern(pattern) using_globstar = pattern == "**" # This avoids os.listdir() for performance if has_wildcard: entries = [x.name for x in scandir(current_dir)] else: entries = [pattern] if using_globstar: matching_subdirs = map(lambda x: x[0], walk(current_dir)) else: subdirs = [e for e in entries if os.path.isdir(os.path.join(current_dir, e))] matching_subdirs = match_entries(subdirs, pattern) # For terminal globstar, add a pattern for all files in subdirs if using_globstar and not patterns: patterns = ['*'] if patterns: # we've still got more directories to traverse for subdir in matching_subdirs: absolute_path = os.path.join(current_dir, subdir) for match in self._find_paths(absolute_path, patterns): yield match else: # we've got the last pattern if not has_wildcard: entries = [pattern + '.wsp', pattern + '.wsp.gz'] files = [e for e in entries if os.path.isfile(os.path.join(current_dir, e))] matching_files = match_entries(files, pattern + '.*') for _basename in matching_files + matching_subdirs: yield os.path.join(current_dir, _basename)
python
def _find_paths(self, current_dir, patterns): """Recursively generates absolute paths whose components underneath current_dir match the corresponding pattern in patterns""" pattern = patterns[0] patterns = patterns[1:] has_wildcard = is_pattern(pattern) using_globstar = pattern == "**" # This avoids os.listdir() for performance if has_wildcard: entries = [x.name for x in scandir(current_dir)] else: entries = [pattern] if using_globstar: matching_subdirs = map(lambda x: x[0], walk(current_dir)) else: subdirs = [e for e in entries if os.path.isdir(os.path.join(current_dir, e))] matching_subdirs = match_entries(subdirs, pattern) # For terminal globstar, add a pattern for all files in subdirs if using_globstar and not patterns: patterns = ['*'] if patterns: # we've still got more directories to traverse for subdir in matching_subdirs: absolute_path = os.path.join(current_dir, subdir) for match in self._find_paths(absolute_path, patterns): yield match else: # we've got the last pattern if not has_wildcard: entries = [pattern + '.wsp', pattern + '.wsp.gz'] files = [e for e in entries if os.path.isfile(os.path.join(current_dir, e))] matching_files = match_entries(files, pattern + '.*') for _basename in matching_files + matching_subdirs: yield os.path.join(current_dir, _basename)
[ "def", "_find_paths", "(", "self", ",", "current_dir", ",", "patterns", ")", ":", "pattern", "=", "patterns", "[", "0", "]", "patterns", "=", "patterns", "[", "1", ":", "]", "has_wildcard", "=", "is_pattern", "(", "pattern", ")", "using_globstar", "=", "pattern", "==", "\"**\"", "# This avoids os.listdir() for performance", "if", "has_wildcard", ":", "entries", "=", "[", "x", ".", "name", "for", "x", "in", "scandir", "(", "current_dir", ")", "]", "else", ":", "entries", "=", "[", "pattern", "]", "if", "using_globstar", ":", "matching_subdirs", "=", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "walk", "(", "current_dir", ")", ")", "else", ":", "subdirs", "=", "[", "e", "for", "e", "in", "entries", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "e", ")", ")", "]", "matching_subdirs", "=", "match_entries", "(", "subdirs", ",", "pattern", ")", "# For terminal globstar, add a pattern for all files in subdirs", "if", "using_globstar", "and", "not", "patterns", ":", "patterns", "=", "[", "'*'", "]", "if", "patterns", ":", "# we've still got more directories to traverse", "for", "subdir", "in", "matching_subdirs", ":", "absolute_path", "=", "os", ".", "path", ".", "join", "(", "current_dir", ",", "subdir", ")", "for", "match", "in", "self", ".", "_find_paths", "(", "absolute_path", ",", "patterns", ")", ":", "yield", "match", "else", ":", "# we've got the last pattern", "if", "not", "has_wildcard", ":", "entries", "=", "[", "pattern", "+", "'.wsp'", ",", "pattern", "+", "'.wsp.gz'", "]", "files", "=", "[", "e", "for", "e", "in", "entries", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "current_dir", ",", "e", ")", ")", "]", "matching_files", "=", "match_entries", "(", "files", ",", "pattern", "+", "'.*'", ")", "for", "_basename", "in", "matching_files", "+", "matching_subdirs", ":", "yield", "os", ".", "path", ".", "join", "(", "current_dir", ",", "_basename", ")" ]
Recursively generates absolute paths whose components underneath current_dir match the corresponding pattern in patterns
[ "Recursively", "generates", "absolute", "paths", "whose", "components", "underneath", "current_dir", "match", "the", "corresponding", "pattern", "in", "patterns" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/finders/whisper.py#L73-L113
brutasse/graphite-api
graphite_api/intervals.py
union_overlapping
def union_overlapping(intervals): """Union any overlapping intervals in the given set.""" disjoint_intervals = [] for interval in intervals: if disjoint_intervals and disjoint_intervals[-1].overlaps(interval): disjoint_intervals[-1] = disjoint_intervals[-1].union(interval) else: disjoint_intervals.append(interval) return disjoint_intervals
python
def union_overlapping(intervals): """Union any overlapping intervals in the given set.""" disjoint_intervals = [] for interval in intervals: if disjoint_intervals and disjoint_intervals[-1].overlaps(interval): disjoint_intervals[-1] = disjoint_intervals[-1].union(interval) else: disjoint_intervals.append(interval) return disjoint_intervals
[ "def", "union_overlapping", "(", "intervals", ")", ":", "disjoint_intervals", "=", "[", "]", "for", "interval", "in", "intervals", ":", "if", "disjoint_intervals", "and", "disjoint_intervals", "[", "-", "1", "]", ".", "overlaps", "(", "interval", ")", ":", "disjoint_intervals", "[", "-", "1", "]", "=", "disjoint_intervals", "[", "-", "1", "]", ".", "union", "(", "interval", ")", "else", ":", "disjoint_intervals", ".", "append", "(", "interval", ")", "return", "disjoint_intervals" ]
Union any overlapping intervals in the given set.
[ "Union", "any", "overlapping", "intervals", "in", "the", "given", "set", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/intervals.py#L128-L138
brutasse/graphite-api
graphite_api/app.py
recurse
def recurse(query, index): """ Recursively walk across paths, adding leaves to the index as they're found. """ for node in app.store.find(query): if node.is_leaf: index.add(node.path) else: recurse('{0}.*'.format(node.path), index)
python
def recurse(query, index): """ Recursively walk across paths, adding leaves to the index as they're found. """ for node in app.store.find(query): if node.is_leaf: index.add(node.path) else: recurse('{0}.*'.format(node.path), index)
[ "def", "recurse", "(", "query", ",", "index", ")", ":", "for", "node", "in", "app", ".", "store", ".", "find", "(", "query", ")", ":", "if", "node", ".", "is_leaf", ":", "index", ".", "add", "(", "node", ".", "path", ")", "else", ":", "recurse", "(", "'{0}.*'", ".", "format", "(", "node", ".", "path", ")", ",", "index", ")" ]
Recursively walk across paths, adding leaves to the index as they're found.
[ "Recursively", "walk", "across", "paths", "adding", "leaves", "to", "the", "index", "as", "they", "re", "found", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/app.py#L204-L212
brutasse/graphite-api
graphite_api/_vendor/whisper.py
setAggregationMethod
def setAggregationMethod(path, aggregationMethod, xFilesFactor=None): """setAggregationMethod(path,aggregationMethod,xFilesFactor=None) path is a string aggregationMethod specifies the method to use when propagating data (see ``whisper.aggregationMethods``) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur. If None, the existing xFilesFactor in path will not be changed """ fh = None try: fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) packedMetadata = fh.read(metadataSize) try: (aggregationType,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) except: raise CorruptWhisperFile("Unable to read header", fh.name) try: newAggregationType = struct.pack( longFormat, aggregationMethodToType[aggregationMethod] ) except KeyError: raise InvalidAggregationMethod("Unrecognized aggregation method: %s" % aggregationMethod) if xFilesFactor is not None: #use specified xFilesFactor xff = struct.pack( floatFormat, float(xFilesFactor) ) else: #retain old value xff = struct.pack( floatFormat, xff ) #repack the remaining header information maxRetention = struct.pack( longFormat, maxRetention ) archiveCount = struct.pack(longFormat, archiveCount) packedMetadata = newAggregationType + maxRetention + xff + archiveCount fh.seek(0) #fh.write(newAggregationType) fh.write(packedMetadata) if AUTOFLUSH: fh.flush() os.fsync(fh.fileno()) if CACHE_HEADERS and fh.name in __headerCache: del __headerCache[fh.name] finally: if fh: fh.close() return aggregationTypeToMethod.get(aggregationType, 'average')
python
def setAggregationMethod(path, aggregationMethod, xFilesFactor=None): """setAggregationMethod(path,aggregationMethod,xFilesFactor=None) path is a string aggregationMethod specifies the method to use when propagating data (see ``whisper.aggregationMethods``) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur. If None, the existing xFilesFactor in path will not be changed """ fh = None try: fh = open(path,'r+b') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) packedMetadata = fh.read(metadataSize) try: (aggregationType,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) except: raise CorruptWhisperFile("Unable to read header", fh.name) try: newAggregationType = struct.pack( longFormat, aggregationMethodToType[aggregationMethod] ) except KeyError: raise InvalidAggregationMethod("Unrecognized aggregation method: %s" % aggregationMethod) if xFilesFactor is not None: #use specified xFilesFactor xff = struct.pack( floatFormat, float(xFilesFactor) ) else: #retain old value xff = struct.pack( floatFormat, xff ) #repack the remaining header information maxRetention = struct.pack( longFormat, maxRetention ) archiveCount = struct.pack(longFormat, archiveCount) packedMetadata = newAggregationType + maxRetention + xff + archiveCount fh.seek(0) #fh.write(newAggregationType) fh.write(packedMetadata) if AUTOFLUSH: fh.flush() os.fsync(fh.fileno()) if CACHE_HEADERS and fh.name in __headerCache: del __headerCache[fh.name] finally: if fh: fh.close() return aggregationTypeToMethod.get(aggregationType, 'average')
[ "def", "setAggregationMethod", "(", "path", ",", "aggregationMethod", ",", "xFilesFactor", "=", "None", ")", ":", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'r+b'", ")", "if", "LOCK", ":", "fcntl", ".", "flock", "(", "fh", ".", "fileno", "(", ")", ",", "fcntl", ".", "LOCK_EX", ")", "packedMetadata", "=", "fh", ".", "read", "(", "metadataSize", ")", "try", ":", "(", "aggregationType", ",", "maxRetention", ",", "xff", ",", "archiveCount", ")", "=", "struct", ".", "unpack", "(", "metadataFormat", ",", "packedMetadata", ")", "except", ":", "raise", "CorruptWhisperFile", "(", "\"Unable to read header\"", ",", "fh", ".", "name", ")", "try", ":", "newAggregationType", "=", "struct", ".", "pack", "(", "longFormat", ",", "aggregationMethodToType", "[", "aggregationMethod", "]", ")", "except", "KeyError", ":", "raise", "InvalidAggregationMethod", "(", "\"Unrecognized aggregation method: %s\"", "%", "aggregationMethod", ")", "if", "xFilesFactor", "is", "not", "None", ":", "#use specified xFilesFactor", "xff", "=", "struct", ".", "pack", "(", "floatFormat", ",", "float", "(", "xFilesFactor", ")", ")", "else", ":", "#retain old value", "xff", "=", "struct", ".", "pack", "(", "floatFormat", ",", "xff", ")", "#repack the remaining header information", "maxRetention", "=", "struct", ".", "pack", "(", "longFormat", ",", "maxRetention", ")", "archiveCount", "=", "struct", ".", "pack", "(", "longFormat", ",", "archiveCount", ")", "packedMetadata", "=", "newAggregationType", "+", "maxRetention", "+", "xff", "+", "archiveCount", "fh", ".", "seek", "(", "0", ")", "#fh.write(newAggregationType)", "fh", ".", "write", "(", "packedMetadata", ")", "if", "AUTOFLUSH", ":", "fh", ".", "flush", "(", ")", "os", ".", "fsync", "(", "fh", ".", "fileno", "(", ")", ")", "if", "CACHE_HEADERS", "and", "fh", ".", "name", "in", "__headerCache", ":", "del", "__headerCache", "[", "fh", ".", "name", "]", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")", "return", "aggregationTypeToMethod", ".", "get", "(", "aggregationType", ",", "'average'", ")" ]
setAggregationMethod(path,aggregationMethod,xFilesFactor=None) path is a string aggregationMethod specifies the method to use when propagating data (see ``whisper.aggregationMethods``) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur. If None, the existing xFilesFactor in path will not be changed
[ "setAggregationMethod", "(", "path", "aggregationMethod", "xFilesFactor", "=", "None", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L265-L319
brutasse/graphite-api
graphite_api/_vendor/whisper.py
validateArchiveList
def validateArchiveList(archiveList): """ Validates an archiveList. An ArchiveList must: 1. Have at least one archive config. Example: (60, 86400) 2. No archive may be a duplicate of another. 3. Higher precision archives' precision must evenly divide all lower precision archives' precision. 4. Lower precision archives must cover larger time intervals than higher precision archives. 5. Each archive must have at least enough points to consolidate to the next archive Returns True or False """ if not archiveList: raise InvalidConfiguration("You must specify at least one archive configuration!") archiveList = sorted(archiveList, key=lambda a: a[0]) #sort by precision (secondsPerPoint) for i,archive in enumerate(archiveList): if i == len(archiveList) - 1: break nextArchive = archiveList[i+1] if not archive[0] < nextArchive[0]: raise InvalidConfiguration("A Whisper database may not configured having" "two archives with the same precision (archive%d: %s, archive%d: %s)" % (i, archive, i + 1, nextArchive)) if nextArchive[0] % archive[0] != 0: raise InvalidConfiguration("Higher precision archives' precision " "must evenly divide all lower precision archives' precision " "(archive%d: %s, archive%d: %s)" % (i, archive[0], i + 1, nextArchive[0])) retention = archive[0] * archive[1] nextRetention = nextArchive[0] * nextArchive[1] if not nextRetention > retention: raise InvalidConfiguration("Lower precision archives must cover " "larger time intervals than higher precision archives " "(archive%d: %s seconds, archive%d: %s seconds)" % (i, retention, i + 1, nextRetention)) archivePoints = archive[1] pointsPerConsolidation = nextArchive[0] // archive[0] if not archivePoints >= pointsPerConsolidation: raise InvalidConfiguration("Each archive must have at least enough points " "to consolidate to the next archive (archive%d consolidates %d of " "archive%d's points but it has only %d total points)" % (i + 1, pointsPerConsolidation, i, archivePoints))
python
def validateArchiveList(archiveList): """ Validates an archiveList. An ArchiveList must: 1. Have at least one archive config. Example: (60, 86400) 2. No archive may be a duplicate of another. 3. Higher precision archives' precision must evenly divide all lower precision archives' precision. 4. Lower precision archives must cover larger time intervals than higher precision archives. 5. Each archive must have at least enough points to consolidate to the next archive Returns True or False """ if not archiveList: raise InvalidConfiguration("You must specify at least one archive configuration!") archiveList = sorted(archiveList, key=lambda a: a[0]) #sort by precision (secondsPerPoint) for i,archive in enumerate(archiveList): if i == len(archiveList) - 1: break nextArchive = archiveList[i+1] if not archive[0] < nextArchive[0]: raise InvalidConfiguration("A Whisper database may not configured having" "two archives with the same precision (archive%d: %s, archive%d: %s)" % (i, archive, i + 1, nextArchive)) if nextArchive[0] % archive[0] != 0: raise InvalidConfiguration("Higher precision archives' precision " "must evenly divide all lower precision archives' precision " "(archive%d: %s, archive%d: %s)" % (i, archive[0], i + 1, nextArchive[0])) retention = archive[0] * archive[1] nextRetention = nextArchive[0] * nextArchive[1] if not nextRetention > retention: raise InvalidConfiguration("Lower precision archives must cover " "larger time intervals than higher precision archives " "(archive%d: %s seconds, archive%d: %s seconds)" % (i, retention, i + 1, nextRetention)) archivePoints = archive[1] pointsPerConsolidation = nextArchive[0] // archive[0] if not archivePoints >= pointsPerConsolidation: raise InvalidConfiguration("Each archive must have at least enough points " "to consolidate to the next archive (archive%d consolidates %d of " "archive%d's points but it has only %d total points)" % (i + 1, pointsPerConsolidation, i, archivePoints))
[ "def", "validateArchiveList", "(", "archiveList", ")", ":", "if", "not", "archiveList", ":", "raise", "InvalidConfiguration", "(", "\"You must specify at least one archive configuration!\"", ")", "archiveList", "=", "sorted", "(", "archiveList", ",", "key", "=", "lambda", "a", ":", "a", "[", "0", "]", ")", "#sort by precision (secondsPerPoint)", "for", "i", ",", "archive", "in", "enumerate", "(", "archiveList", ")", ":", "if", "i", "==", "len", "(", "archiveList", ")", "-", "1", ":", "break", "nextArchive", "=", "archiveList", "[", "i", "+", "1", "]", "if", "not", "archive", "[", "0", "]", "<", "nextArchive", "[", "0", "]", ":", "raise", "InvalidConfiguration", "(", "\"A Whisper database may not configured having\"", "\"two archives with the same precision (archive%d: %s, archive%d: %s)\"", "%", "(", "i", ",", "archive", ",", "i", "+", "1", ",", "nextArchive", ")", ")", "if", "nextArchive", "[", "0", "]", "%", "archive", "[", "0", "]", "!=", "0", ":", "raise", "InvalidConfiguration", "(", "\"Higher precision archives' precision \"", "\"must evenly divide all lower precision archives' precision \"", "\"(archive%d: %s, archive%d: %s)\"", "%", "(", "i", ",", "archive", "[", "0", "]", ",", "i", "+", "1", ",", "nextArchive", "[", "0", "]", ")", ")", "retention", "=", "archive", "[", "0", "]", "*", "archive", "[", "1", "]", "nextRetention", "=", "nextArchive", "[", "0", "]", "*", "nextArchive", "[", "1", "]", "if", "not", "nextRetention", ">", "retention", ":", "raise", "InvalidConfiguration", "(", "\"Lower precision archives must cover \"", "\"larger time intervals than higher precision archives \"", "\"(archive%d: %s seconds, archive%d: %s seconds)\"", "%", "(", "i", ",", "retention", ",", "i", "+", "1", ",", "nextRetention", ")", ")", "archivePoints", "=", "archive", "[", "1", "]", "pointsPerConsolidation", "=", "nextArchive", "[", "0", "]", "//", "archive", "[", "0", "]", "if", "not", "archivePoints", ">=", "pointsPerConsolidation", ":", "raise", "InvalidConfiguration", "(", "\"Each archive must have at least enough points \"", "\"to consolidate to the next archive (archive%d consolidates %d of \"", "\"archive%d's points but it has only %d total points)\"", "%", "(", "i", "+", "1", ",", "pointsPerConsolidation", ",", "i", ",", "archivePoints", ")", ")" ]
Validates an archiveList. An ArchiveList must: 1. Have at least one archive config. Example: (60, 86400) 2. No archive may be a duplicate of another. 3. Higher precision archives' precision must evenly divide all lower precision archives' precision. 4. Lower precision archives must cover larger time intervals than higher precision archives. 5. Each archive must have at least enough points to consolidate to the next archive Returns True or False
[ "Validates", "an", "archiveList", ".", "An", "ArchiveList", "must", ":", "1", ".", "Have", "at", "least", "one", "archive", "config", ".", "Example", ":", "(", "60", "86400", ")", "2", ".", "No", "archive", "may", "be", "a", "duplicate", "of", "another", ".", "3", ".", "Higher", "precision", "archives", "precision", "must", "evenly", "divide", "all", "lower", "precision", "archives", "precision", ".", "4", ".", "Lower", "precision", "archives", "must", "cover", "larger", "time", "intervals", "than", "higher", "precision", "archives", ".", "5", ".", "Each", "archive", "must", "have", "at", "least", "enough", "points", "to", "consolidate", "to", "the", "next", "archive" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L322-L370
brutasse/graphite-api
graphite_api/_vendor/whisper.py
create
def create(path,archiveList,xFilesFactor=None,aggregationMethod=None,sparse=False,useFallocate=False): """create(path,archiveList,xFilesFactor=0.5,aggregationMethod='average') path is a string archiveList is a list of archives, each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur aggregationMethod specifies the function to use when propagating data (see ``whisper.aggregationMethods``) """ # Set default params if xFilesFactor is None: xFilesFactor = 0.5 if aggregationMethod is None: aggregationMethod = 'average' #Validate archive configurations... validateArchiveList(archiveList) #Looks good, now we create the file and write the header if os.path.exists(path): raise InvalidConfiguration("File %s already exists!" % path) fh = None try: fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) aggregationType = struct.pack( longFormat, aggregationMethodToType.get(aggregationMethod, 1) ) oldest = max([secondsPerPoint * points for secondsPerPoint,points in archiveList]) maxRetention = struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = aggregationType + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) #If configured to use fallocate and capable of fallocate use that, else #attempt sparse if configure or zero pre-allocate if sparse isn't configured. if CAN_FALLOCATE and useFallocate: remaining = archiveOffsetPointer - headerSize fallocate(fh, headerSize, remaining) elif sparse: fh.seek(archiveOffsetPointer - 1) fh.write('\x00') else: remaining = archiveOffsetPointer - headerSize chunksize = 16384 zeroes = b'\x00' * chunksize while remaining > chunksize: fh.write(zeroes) remaining -= chunksize fh.write(zeroes[:remaining]) if AUTOFLUSH: fh.flush() os.fsync(fh.fileno()) finally: if fh: fh.close()
python
def create(path,archiveList,xFilesFactor=None,aggregationMethod=None,sparse=False,useFallocate=False): """create(path,archiveList,xFilesFactor=0.5,aggregationMethod='average') path is a string archiveList is a list of archives, each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur aggregationMethod specifies the function to use when propagating data (see ``whisper.aggregationMethods``) """ # Set default params if xFilesFactor is None: xFilesFactor = 0.5 if aggregationMethod is None: aggregationMethod = 'average' #Validate archive configurations... validateArchiveList(archiveList) #Looks good, now we create the file and write the header if os.path.exists(path): raise InvalidConfiguration("File %s already exists!" % path) fh = None try: fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) aggregationType = struct.pack( longFormat, aggregationMethodToType.get(aggregationMethod, 1) ) oldest = max([secondsPerPoint * points for secondsPerPoint,points in archiveList]) maxRetention = struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = aggregationType + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) #If configured to use fallocate and capable of fallocate use that, else #attempt sparse if configure or zero pre-allocate if sparse isn't configured. if CAN_FALLOCATE and useFallocate: remaining = archiveOffsetPointer - headerSize fallocate(fh, headerSize, remaining) elif sparse: fh.seek(archiveOffsetPointer - 1) fh.write('\x00') else: remaining = archiveOffsetPointer - headerSize chunksize = 16384 zeroes = b'\x00' * chunksize while remaining > chunksize: fh.write(zeroes) remaining -= chunksize fh.write(zeroes[:remaining]) if AUTOFLUSH: fh.flush() os.fsync(fh.fileno()) finally: if fh: fh.close()
[ "def", "create", "(", "path", ",", "archiveList", ",", "xFilesFactor", "=", "None", ",", "aggregationMethod", "=", "None", ",", "sparse", "=", "False", ",", "useFallocate", "=", "False", ")", ":", "# Set default params", "if", "xFilesFactor", "is", "None", ":", "xFilesFactor", "=", "0.5", "if", "aggregationMethod", "is", "None", ":", "aggregationMethod", "=", "'average'", "#Validate archive configurations...", "validateArchiveList", "(", "archiveList", ")", "#Looks good, now we create the file and write the header", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "InvalidConfiguration", "(", "\"File %s already exists!\"", "%", "path", ")", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'wb'", ")", "if", "LOCK", ":", "fcntl", ".", "flock", "(", "fh", ".", "fileno", "(", ")", ",", "fcntl", ".", "LOCK_EX", ")", "aggregationType", "=", "struct", ".", "pack", "(", "longFormat", ",", "aggregationMethodToType", ".", "get", "(", "aggregationMethod", ",", "1", ")", ")", "oldest", "=", "max", "(", "[", "secondsPerPoint", "*", "points", "for", "secondsPerPoint", ",", "points", "in", "archiveList", "]", ")", "maxRetention", "=", "struct", ".", "pack", "(", "longFormat", ",", "oldest", ")", "xFilesFactor", "=", "struct", ".", "pack", "(", "floatFormat", ",", "float", "(", "xFilesFactor", ")", ")", "archiveCount", "=", "struct", ".", "pack", "(", "longFormat", ",", "len", "(", "archiveList", ")", ")", "packedMetadata", "=", "aggregationType", "+", "maxRetention", "+", "xFilesFactor", "+", "archiveCount", "fh", ".", "write", "(", "packedMetadata", ")", "headerSize", "=", "metadataSize", "+", "(", "archiveInfoSize", "*", "len", "(", "archiveList", ")", ")", "archiveOffsetPointer", "=", "headerSize", "for", "secondsPerPoint", ",", "points", "in", "archiveList", ":", "archiveInfo", "=", "struct", ".", "pack", "(", "archiveInfoFormat", ",", "archiveOffsetPointer", ",", "secondsPerPoint", ",", "points", ")", "fh", ".", "write", "(", "archiveInfo", ")", "archiveOffsetPointer", "+=", "(", "points", "*", "pointSize", ")", "#If configured to use fallocate and capable of fallocate use that, else", "#attempt sparse if configure or zero pre-allocate if sparse isn't configured.", "if", "CAN_FALLOCATE", "and", "useFallocate", ":", "remaining", "=", "archiveOffsetPointer", "-", "headerSize", "fallocate", "(", "fh", ",", "headerSize", ",", "remaining", ")", "elif", "sparse", ":", "fh", ".", "seek", "(", "archiveOffsetPointer", "-", "1", ")", "fh", ".", "write", "(", "'\\x00'", ")", "else", ":", "remaining", "=", "archiveOffsetPointer", "-", "headerSize", "chunksize", "=", "16384", "zeroes", "=", "b'\\x00'", "*", "chunksize", "while", "remaining", ">", "chunksize", ":", "fh", ".", "write", "(", "zeroes", ")", "remaining", "-=", "chunksize", "fh", ".", "write", "(", "zeroes", "[", ":", "remaining", "]", ")", "if", "AUTOFLUSH", ":", "fh", ".", "flush", "(", ")", "os", ".", "fsync", "(", "fh", ".", "fileno", "(", ")", ")", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")" ]
create(path,archiveList,xFilesFactor=0.5,aggregationMethod='average') path is a string archiveList is a list of archives, each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the fraction of data points in a propagation interval that must have known values for a propagation to occur aggregationMethod specifies the function to use when propagating data (see ``whisper.aggregationMethods``)
[ "create", "(", "path", "archiveList", "xFilesFactor", "=", "0", ".", "5", "aggregationMethod", "=", "average", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L373-L436
brutasse/graphite-api
graphite_api/_vendor/whisper.py
update
def update(path,value,timestamp=None): """update(path,value,timestamp=None) path is a string value is a float timestamp is either an int or float """ value = float(value) fh = None try: fh = open(path,'r+b') return file_update(fh, value, timestamp) finally: if fh: fh.close()
python
def update(path,value,timestamp=None): """update(path,value,timestamp=None) path is a string value is a float timestamp is either an int or float """ value = float(value) fh = None try: fh = open(path,'r+b') return file_update(fh, value, timestamp) finally: if fh: fh.close()
[ "def", "update", "(", "path", ",", "value", ",", "timestamp", "=", "None", ")", ":", "value", "=", "float", "(", "value", ")", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'r+b'", ")", "return", "file_update", "(", "fh", ",", "value", ",", "timestamp", ")", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")" ]
update(path,value,timestamp=None) path is a string value is a float timestamp is either an int or float
[ "update", "(", "path", "value", "timestamp", "=", "None", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L535-L549
brutasse/graphite-api
graphite_api/_vendor/whisper.py
update_many
def update_many(path,points): """update_many(path,points) path is a string points is a list of (timestamp,value) points """ if not points: return points = [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest first fh = None try: fh = open(path,'r+b') return file_update_many(fh, points) finally: if fh: fh.close()
python
def update_many(path,points): """update_many(path,points) path is a string points is a list of (timestamp,value) points """ if not points: return points = [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest first fh = None try: fh = open(path,'r+b') return file_update_many(fh, points) finally: if fh: fh.close()
[ "def", "update_many", "(", "path", ",", "points", ")", ":", "if", "not", "points", ":", "return", "points", "=", "[", "(", "int", "(", "t", ")", ",", "float", "(", "v", ")", ")", "for", "(", "t", ",", "v", ")", "in", "points", "]", "points", ".", "sort", "(", "key", "=", "lambda", "p", ":", "p", "[", "0", "]", ",", "reverse", "=", "True", ")", "#order points by timestamp, newest first", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'r+b'", ")", "return", "file_update_many", "(", "fh", ",", "points", ")", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")" ]
update_many(path,points) path is a string points is a list of (timestamp,value) points
[ "update_many", "(", "path", "points", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L603-L618
brutasse/graphite-api
graphite_api/_vendor/whisper.py
info
def info(path): """info(path) path is a string """ fh = None try: fh = open(path,'rb') return __readHeader(fh) finally: if fh: fh.close() return None
python
def info(path): """info(path) path is a string """ fh = None try: fh = open(path,'rb') return __readHeader(fh) finally: if fh: fh.close() return None
[ "def", "info", "(", "path", ")", ":", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'rb'", ")", "return", "__readHeader", "(", "fh", ")", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")", "return", "None" ]
info(path) path is a string
[ "info", "(", "path", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L727-L739
brutasse/graphite-api
graphite_api/_vendor/whisper.py
fetch
def fetch(path,fromTime,untilTime=None,now=None): """fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time untilTime is also an epoch time, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTime, untilTime, step) Returns None if no data can be returned """ fh = None try: fh = open(path,'rb') return file_fetch(fh, fromTime, untilTime, now) finally: if fh: fh.close()
python
def fetch(path,fromTime,untilTime=None,now=None): """fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time untilTime is also an epoch time, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTime, untilTime, step) Returns None if no data can be returned """ fh = None try: fh = open(path,'rb') return file_fetch(fh, fromTime, untilTime, now) finally: if fh: fh.close()
[ "def", "fetch", "(", "path", ",", "fromTime", ",", "untilTime", "=", "None", ",", "now", "=", "None", ")", ":", "fh", "=", "None", "try", ":", "fh", "=", "open", "(", "path", ",", "'rb'", ")", "return", "file_fetch", "(", "fh", ",", "fromTime", ",", "untilTime", ",", "now", ")", "finally", ":", "if", "fh", ":", "fh", ".", "close", "(", ")" ]
fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time untilTime is also an epoch time, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTime, untilTime, step) Returns None if no data can be returned
[ "fetch", "(", "path", "fromTime", "untilTime", "=", "None", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L741-L759
brutasse/graphite-api
graphite_api/_vendor/whisper.py
__archive_fetch
def __archive_fetch(fh, archive, fromTime, untilTime): """ Fetch data from a single archive. Note that checks for validity of the time period requested happen above this level so it's possible to wrap around the archive on a read and request data older than the archive's retention """ fromInterval = int( fromTime - (fromTime % archive['secondsPerPoint']) ) + archive['secondsPerPoint'] untilInterval = int( untilTime - (untilTime % archive['secondsPerPoint']) ) + archive['secondsPerPoint'] if fromInterval == untilInterval: # Zero-length time range: always include the next point untilInterval += archive['secondsPerPoint'] fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step = archive['secondsPerPoint'] points = (untilInterval - fromInterval) // step timeInfo = (fromInterval,untilInterval,step) valueList = [None] * points return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval - baseInterval pointDistance = timeDistance // archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset = archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset timeDistance = untilInterval - baseInterval pointDistance = timeDistance // archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset = archive['offset'] + (byteDistance % archive['size']) #Read all the points in the interval fh.seek(fromOffset) if fromOffset < untilOffset: #If we don't wrap around the archive seriesString = fh.read(untilOffset - fromOffset) else: #We do wrap around the archive, so we need two reads archiveEnd = archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now we unpack the series data we just read (anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) // pointSize seriesFormat = byteOrder + (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we construct a list of values (optimize this!) valueList = [None] * points #pre-allocate entire list for speed currentInterval = fromInterval step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i//2] = pointValue #in-place reassignment is faster than append() currentInterval += step timeInfo = (fromInterval,untilInterval,step) return (timeInfo,valueList)
python
def __archive_fetch(fh, archive, fromTime, untilTime): """ Fetch data from a single archive. Note that checks for validity of the time period requested happen above this level so it's possible to wrap around the archive on a read and request data older than the archive's retention """ fromInterval = int( fromTime - (fromTime % archive['secondsPerPoint']) ) + archive['secondsPerPoint'] untilInterval = int( untilTime - (untilTime % archive['secondsPerPoint']) ) + archive['secondsPerPoint'] if fromInterval == untilInterval: # Zero-length time range: always include the next point untilInterval += archive['secondsPerPoint'] fh.seek(archive['offset']) packedPoint = fh.read(pointSize) (baseInterval,baseValue) = struct.unpack(pointFormat,packedPoint) if baseInterval == 0: step = archive['secondsPerPoint'] points = (untilInterval - fromInterval) // step timeInfo = (fromInterval,untilInterval,step) valueList = [None] * points return (timeInfo,valueList) #Determine fromOffset timeDistance = fromInterval - baseInterval pointDistance = timeDistance // archive['secondsPerPoint'] byteDistance = pointDistance * pointSize fromOffset = archive['offset'] + (byteDistance % archive['size']) #Determine untilOffset timeDistance = untilInterval - baseInterval pointDistance = timeDistance // archive['secondsPerPoint'] byteDistance = pointDistance * pointSize untilOffset = archive['offset'] + (byteDistance % archive['size']) #Read all the points in the interval fh.seek(fromOffset) if fromOffset < untilOffset: #If we don't wrap around the archive seriesString = fh.read(untilOffset - fromOffset) else: #We do wrap around the archive, so we need two reads archiveEnd = archive['offset'] + archive['size'] seriesString = fh.read(archiveEnd - fromOffset) fh.seek(archive['offset']) seriesString += fh.read(untilOffset - archive['offset']) #Now we unpack the series data we just read (anything faster than unpack?) byteOrder,pointTypes = pointFormat[0],pointFormat[1:] points = len(seriesString) // pointSize seriesFormat = byteOrder + (pointTypes * points) unpackedSeries = struct.unpack(seriesFormat, seriesString) #And finally we construct a list of values (optimize this!) valueList = [None] * points #pre-allocate entire list for speed currentInterval = fromInterval step = archive['secondsPerPoint'] for i in xrange(0,len(unpackedSeries),2): pointTime = unpackedSeries[i] if pointTime == currentInterval: pointValue = unpackedSeries[i+1] valueList[i//2] = pointValue #in-place reassignment is faster than append() currentInterval += step timeInfo = (fromInterval,untilInterval,step) return (timeInfo,valueList)
[ "def", "__archive_fetch", "(", "fh", ",", "archive", ",", "fromTime", ",", "untilTime", ")", ":", "fromInterval", "=", "int", "(", "fromTime", "-", "(", "fromTime", "%", "archive", "[", "'secondsPerPoint'", "]", ")", ")", "+", "archive", "[", "'secondsPerPoint'", "]", "untilInterval", "=", "int", "(", "untilTime", "-", "(", "untilTime", "%", "archive", "[", "'secondsPerPoint'", "]", ")", ")", "+", "archive", "[", "'secondsPerPoint'", "]", "if", "fromInterval", "==", "untilInterval", ":", "# Zero-length time range: always include the next point", "untilInterval", "+=", "archive", "[", "'secondsPerPoint'", "]", "fh", ".", "seek", "(", "archive", "[", "'offset'", "]", ")", "packedPoint", "=", "fh", ".", "read", "(", "pointSize", ")", "(", "baseInterval", ",", "baseValue", ")", "=", "struct", ".", "unpack", "(", "pointFormat", ",", "packedPoint", ")", "if", "baseInterval", "==", "0", ":", "step", "=", "archive", "[", "'secondsPerPoint'", "]", "points", "=", "(", "untilInterval", "-", "fromInterval", ")", "//", "step", "timeInfo", "=", "(", "fromInterval", ",", "untilInterval", ",", "step", ")", "valueList", "=", "[", "None", "]", "*", "points", "return", "(", "timeInfo", ",", "valueList", ")", "#Determine fromOffset", "timeDistance", "=", "fromInterval", "-", "baseInterval", "pointDistance", "=", "timeDistance", "//", "archive", "[", "'secondsPerPoint'", "]", "byteDistance", "=", "pointDistance", "*", "pointSize", "fromOffset", "=", "archive", "[", "'offset'", "]", "+", "(", "byteDistance", "%", "archive", "[", "'size'", "]", ")", "#Determine untilOffset", "timeDistance", "=", "untilInterval", "-", "baseInterval", "pointDistance", "=", "timeDistance", "//", "archive", "[", "'secondsPerPoint'", "]", "byteDistance", "=", "pointDistance", "*", "pointSize", "untilOffset", "=", "archive", "[", "'offset'", "]", "+", "(", "byteDistance", "%", "archive", "[", "'size'", "]", ")", "#Read all the points in the interval", "fh", ".", "seek", "(", "fromOffset", ")", "if", "fromOffset", "<", "untilOffset", ":", "#If we don't wrap around the archive", "seriesString", "=", "fh", ".", "read", "(", "untilOffset", "-", "fromOffset", ")", "else", ":", "#We do wrap around the archive, so we need two reads", "archiveEnd", "=", "archive", "[", "'offset'", "]", "+", "archive", "[", "'size'", "]", "seriesString", "=", "fh", ".", "read", "(", "archiveEnd", "-", "fromOffset", ")", "fh", ".", "seek", "(", "archive", "[", "'offset'", "]", ")", "seriesString", "+=", "fh", ".", "read", "(", "untilOffset", "-", "archive", "[", "'offset'", "]", ")", "#Now we unpack the series data we just read (anything faster than unpack?)", "byteOrder", ",", "pointTypes", "=", "pointFormat", "[", "0", "]", ",", "pointFormat", "[", "1", ":", "]", "points", "=", "len", "(", "seriesString", ")", "//", "pointSize", "seriesFormat", "=", "byteOrder", "+", "(", "pointTypes", "*", "points", ")", "unpackedSeries", "=", "struct", ".", "unpack", "(", "seriesFormat", ",", "seriesString", ")", "#And finally we construct a list of values (optimize this!)", "valueList", "=", "[", "None", "]", "*", "points", "#pre-allocate entire list for speed", "currentInterval", "=", "fromInterval", "step", "=", "archive", "[", "'secondsPerPoint'", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "unpackedSeries", ")", ",", "2", ")", ":", "pointTime", "=", "unpackedSeries", "[", "i", "]", "if", "pointTime", "==", "currentInterval", ":", "pointValue", "=", "unpackedSeries", "[", "i", "+", "1", "]", "valueList", "[", "i", "//", "2", "]", "=", "pointValue", "#in-place reassignment is faster than append()", "currentInterval", "+=", "step", "timeInfo", "=", "(", "fromInterval", ",", "untilInterval", ",", "step", ")", "return", "(", "timeInfo", ",", "valueList", ")" ]
Fetch data from a single archive. Note that checks for validity of the time period requested happen above this level so it's possible to wrap around the archive on a read and request data older than the archive's retention
[ "Fetch", "data", "from", "a", "single", "archive", ".", "Note", "that", "checks", "for", "validity", "of", "the", "time", "period", "requested", "happen", "above", "this", "level", "so", "it", "s", "possible", "to", "wrap", "around", "the", "archive", "on", "a", "read", "and", "request", "data", "older", "than", "the", "archive", "s", "retention" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L797-L860
brutasse/graphite-api
graphite_api/_vendor/whisper.py
merge
def merge(path_from, path_to): """ Merges the data from one whisper file into another. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb+') return file_merge(fh_from, fh_to)
python
def merge(path_from, path_to): """ Merges the data from one whisper file into another. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb+') return file_merge(fh_from, fh_to)
[ "def", "merge", "(", "path_from", ",", "path_to", ")", ":", "fh_from", "=", "open", "(", "path_from", ",", "'rb'", ")", "fh_to", "=", "open", "(", "path_to", ",", "'rb+'", ")", "return", "file_merge", "(", "fh_from", ",", "fh_to", ")" ]
Merges the data from one whisper file into another. Each file must have the same archive configuration
[ "Merges", "the", "data", "from", "one", "whisper", "file", "into", "another", ".", "Each", "file", "must", "have", "the", "same", "archive", "configuration" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L862-L868
brutasse/graphite-api
graphite_api/_vendor/whisper.py
diff
def diff(path_from, path_to, ignore_empty = False): """ Compare two whisper databases. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb') diffs = file_diff(fh_from, fh_to, ignore_empty) fh_to.close() fh_from.close() return diffs
python
def diff(path_from, path_to, ignore_empty = False): """ Compare two whisper databases. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb') diffs = file_diff(fh_from, fh_to, ignore_empty) fh_to.close() fh_from.close() return diffs
[ "def", "diff", "(", "path_from", ",", "path_to", ",", "ignore_empty", "=", "False", ")", ":", "fh_from", "=", "open", "(", "path_from", ",", "'rb'", ")", "fh_to", "=", "open", "(", "path_to", ",", "'rb'", ")", "diffs", "=", "file_diff", "(", "fh_from", ",", "fh_to", ",", "ignore_empty", ")", "fh_to", ".", "close", "(", ")", "fh_from", ".", "close", "(", ")", "return", "diffs" ]
Compare two whisper databases. Each file must have the same archive configuration
[ "Compare", "two", "whisper", "databases", ".", "Each", "file", "must", "have", "the", "same", "archive", "configuration" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L895-L902
brutasse/graphite-api
graphite_api/render/datalib.py
DataStore.add_data
def add_data(self, path, time_info, data, exprs): """ Stores data before it can be put into a time series """ # Dont add if empty if not nonempty(data): for d in self.data[path]: if nonempty(d['values']): return # Add data to path for expr in exprs: self.paths[expr].add(path) self.data[path].append({ 'time_info': time_info, 'values': data })
python
def add_data(self, path, time_info, data, exprs): """ Stores data before it can be put into a time series """ # Dont add if empty if not nonempty(data): for d in self.data[path]: if nonempty(d['values']): return # Add data to path for expr in exprs: self.paths[expr].add(path) self.data[path].append({ 'time_info': time_info, 'values': data })
[ "def", "add_data", "(", "self", ",", "path", ",", "time_info", ",", "data", ",", "exprs", ")", ":", "# Dont add if empty", "if", "not", "nonempty", "(", "data", ")", ":", "for", "d", "in", "self", ".", "data", "[", "path", "]", ":", "if", "nonempty", "(", "d", "[", "'values'", "]", ")", ":", "return", "# Add data to path", "for", "expr", "in", "exprs", ":", "self", ".", "paths", "[", "expr", "]", ".", "add", "(", "path", ")", "self", ".", "data", "[", "path", "]", ".", "append", "(", "{", "'time_info'", ":", "time_info", ",", "'values'", ":", "data", "}", ")" ]
Stores data before it can be put into a time series
[ "Stores", "data", "before", "it", "can", "be", "put", "into", "a", "time", "series" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/datalib.py#L117-L133
brutasse/graphite-api
graphite_api/finders/__init__.py
extract_variants
def extract_variants(pattern): """Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz).""" v1, v2 = pattern.find('{'), pattern.find('}') if v1 > -1 and v2 > v1: variations = pattern[v1+1:v2].split(',') variants = [pattern[:v1] + v + pattern[v2+1:] for v in variations] else: variants = [pattern] return list(_deduplicate(variants))
python
def extract_variants(pattern): """Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz).""" v1, v2 = pattern.find('{'), pattern.find('}') if v1 > -1 and v2 > v1: variations = pattern[v1+1:v2].split(',') variants = [pattern[:v1] + v + pattern[v2+1:] for v in variations] else: variants = [pattern] return list(_deduplicate(variants))
[ "def", "extract_variants", "(", "pattern", ")", ":", "v1", ",", "v2", "=", "pattern", ".", "find", "(", "'{'", ")", ",", "pattern", ".", "find", "(", "'}'", ")", "if", "v1", ">", "-", "1", "and", "v2", ">", "v1", ":", "variations", "=", "pattern", "[", "v1", "+", "1", ":", "v2", "]", ".", "split", "(", "','", ")", "variants", "=", "[", "pattern", "[", ":", "v1", "]", "+", "v", "+", "pattern", "[", "v2", "+", "1", ":", "]", "for", "v", "in", "variations", "]", "else", ":", "variants", "=", "[", "pattern", "]", "return", "list", "(", "_deduplicate", "(", "variants", ")", ")" ]
Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz).
[ "Extract", "the", "pattern", "variants", "(", "ie", ".", "{", "foo", "bar", "}", "baz", "=", "foobaz", "or", "barbaz", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/finders/__init__.py#L35-L43
brutasse/graphite-api
graphite_api/finders/__init__.py
match_entries
def match_entries(entries, pattern): """A drop-in replacement for fnmatch.filter that supports pattern variants (ie. {foo,bar}baz = foobaz or barbaz).""" matching = [] for variant in expand_braces(pattern): matching.extend(fnmatch.filter(entries, variant)) return list(_deduplicate(matching))
python
def match_entries(entries, pattern): """A drop-in replacement for fnmatch.filter that supports pattern variants (ie. {foo,bar}baz = foobaz or barbaz).""" matching = [] for variant in expand_braces(pattern): matching.extend(fnmatch.filter(entries, variant)) return list(_deduplicate(matching))
[ "def", "match_entries", "(", "entries", ",", "pattern", ")", ":", "matching", "=", "[", "]", "for", "variant", "in", "expand_braces", "(", "pattern", ")", ":", "matching", ".", "extend", "(", "fnmatch", ".", "filter", "(", "entries", ",", "variant", ")", ")", "return", "list", "(", "_deduplicate", "(", "matching", ")", ")" ]
A drop-in replacement for fnmatch.filter that supports pattern variants (ie. {foo,bar}baz = foobaz or barbaz).
[ "A", "drop", "-", "in", "replacement", "for", "fnmatch", ".", "filter", "that", "supports", "pattern", "variants", "(", "ie", ".", "{", "foo", "bar", "}", "baz", "=", "foobaz", "or", "barbaz", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/finders/__init__.py#L46-L54
brutasse/graphite-api
graphite_api/finders/__init__.py
expand_braces
def expand_braces(pattern): """Find the rightmost, innermost set of braces and, if it contains a comma-separated list, expand its contents recursively (any of its items may itself be a list enclosed in braces). Return the full list of expanded strings. """ res = set() # Used instead of s.strip('{}') because strip is greedy. # We want to remove only ONE leading { and ONE trailing }, if both exist def remove_outer_braces(s): if s[0] == '{' and s[-1] == '}': return s[1:-1] return s match = EXPAND_BRACES_RE.search(pattern) if match is not None: sub = match.group(1) v1, v2 = match.span(1) if "," in sub: for pat in sub.strip('{}').split(','): subpattern = pattern[:v1] + pat + pattern[v2:] res.update(expand_braces(subpattern)) else: subpattern = pattern[:v1] + remove_outer_braces(sub) + pattern[v2:] res.update(expand_braces(subpattern)) else: res.add(pattern.replace('\\}', '}')) return list(res)
python
def expand_braces(pattern): """Find the rightmost, innermost set of braces and, if it contains a comma-separated list, expand its contents recursively (any of its items may itself be a list enclosed in braces). Return the full list of expanded strings. """ res = set() # Used instead of s.strip('{}') because strip is greedy. # We want to remove only ONE leading { and ONE trailing }, if both exist def remove_outer_braces(s): if s[0] == '{' and s[-1] == '}': return s[1:-1] return s match = EXPAND_BRACES_RE.search(pattern) if match is not None: sub = match.group(1) v1, v2 = match.span(1) if "," in sub: for pat in sub.strip('{}').split(','): subpattern = pattern[:v1] + pat + pattern[v2:] res.update(expand_braces(subpattern)) else: subpattern = pattern[:v1] + remove_outer_braces(sub) + pattern[v2:] res.update(expand_braces(subpattern)) else: res.add(pattern.replace('\\}', '}')) return list(res)
[ "def", "expand_braces", "(", "pattern", ")", ":", "res", "=", "set", "(", ")", "# Used instead of s.strip('{}') because strip is greedy.", "# We want to remove only ONE leading { and ONE trailing }, if both exist", "def", "remove_outer_braces", "(", "s", ")", ":", "if", "s", "[", "0", "]", "==", "'{'", "and", "s", "[", "-", "1", "]", "==", "'}'", ":", "return", "s", "[", "1", ":", "-", "1", "]", "return", "s", "match", "=", "EXPAND_BRACES_RE", ".", "search", "(", "pattern", ")", "if", "match", "is", "not", "None", ":", "sub", "=", "match", ".", "group", "(", "1", ")", "v1", ",", "v2", "=", "match", ".", "span", "(", "1", ")", "if", "\",\"", "in", "sub", ":", "for", "pat", "in", "sub", ".", "strip", "(", "'{}'", ")", ".", "split", "(", "','", ")", ":", "subpattern", "=", "pattern", "[", ":", "v1", "]", "+", "pat", "+", "pattern", "[", "v2", ":", "]", "res", ".", "update", "(", "expand_braces", "(", "subpattern", ")", ")", "else", ":", "subpattern", "=", "pattern", "[", ":", "v1", "]", "+", "remove_outer_braces", "(", "sub", ")", "+", "pattern", "[", "v2", ":", "]", "res", ".", "update", "(", "expand_braces", "(", "subpattern", ")", ")", "else", ":", "res", ".", "add", "(", "pattern", ".", "replace", "(", "'\\\\}'", ",", "'}'", ")", ")", "return", "list", "(", "res", ")" ]
Find the rightmost, innermost set of braces and, if it contains a comma-separated list, expand its contents recursively (any of its items may itself be a list enclosed in braces). Return the full list of expanded strings.
[ "Find", "the", "rightmost", "innermost", "set", "of", "braces", "and", "if", "it", "contains", "a", "comma", "-", "separated", "list", "expand", "its", "contents", "recursively", "(", "any", "of", "its", "items", "may", "itself", "be", "a", "list", "enclosed", "in", "braces", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/finders/__init__.py#L57-L87
brutasse/graphite-api
graphite_api/carbonlink.py
CarbonLinkPool.select_host
def select_host(self, metric): """ Returns the carbon host that has data for the given metric. """ key = self.keyfunc(metric) nodes = [] servers = set() for node in self.hash_ring.get_nodes(key): server, instance = node if server in servers: continue servers.add(server) nodes.append(node) if len(servers) >= self.replication_factor: break available = [n for n in nodes if self.is_available(n)] return random.choice(available or nodes)
python
def select_host(self, metric): """ Returns the carbon host that has data for the given metric. """ key = self.keyfunc(metric) nodes = [] servers = set() for node in self.hash_ring.get_nodes(key): server, instance = node if server in servers: continue servers.add(server) nodes.append(node) if len(servers) >= self.replication_factor: break available = [n for n in nodes if self.is_available(n)] return random.choice(available or nodes)
[ "def", "select_host", "(", "self", ",", "metric", ")", ":", "key", "=", "self", ".", "keyfunc", "(", "metric", ")", "nodes", "=", "[", "]", "servers", "=", "set", "(", ")", "for", "node", "in", "self", ".", "hash_ring", ".", "get_nodes", "(", "key", ")", ":", "server", ",", "instance", "=", "node", "if", "server", "in", "servers", ":", "continue", "servers", ".", "add", "(", "server", ")", "nodes", ".", "append", "(", "node", ")", "if", "len", "(", "servers", ")", ">=", "self", ".", "replication_factor", ":", "break", "available", "=", "[", "n", "for", "n", "in", "nodes", "if", "self", ".", "is_available", "(", "n", ")", "]", "return", "random", ".", "choice", "(", "available", "or", "nodes", ")" ]
Returns the carbon host that has data for the given metric.
[ "Returns", "the", "carbon", "host", "that", "has", "data", "for", "the", "given", "metric", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/carbonlink.py#L180-L196
brutasse/graphite-api
graphite_api/render/glyph.py
safeArgs
def safeArgs(args): """Iterate over valid, finite values in an iterable. Skip any items that are None, NaN, or infinite. """ return (arg for arg in args if arg is not None and not math.isnan(arg) and not math.isinf(arg))
python
def safeArgs(args): """Iterate over valid, finite values in an iterable. Skip any items that are None, NaN, or infinite. """ return (arg for arg in args if arg is not None and not math.isnan(arg) and not math.isinf(arg))
[ "def", "safeArgs", "(", "args", ")", ":", "return", "(", "arg", "for", "arg", "in", "args", "if", "arg", "is", "not", "None", "and", "not", "math", ".", "isnan", "(", "arg", ")", "and", "not", "math", ".", "isinf", "(", "arg", ")", ")" ]
Iterate over valid, finite values in an iterable. Skip any items that are None, NaN, or infinite.
[ "Iterate", "over", "valid", "finite", "values", "in", "an", "iterable", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L2147-L2153
brutasse/graphite-api
graphite_api/render/glyph.py
dataLimits
def dataLimits(data, drawNullAsZero=False, stacked=False): """Return the range of values in data as (yMinValue, yMaxValue). data is an array of TimeSeries objects. """ missingValues = any(None in series for series in data) finiteData = [series for series in data if not series.options.get('drawAsInfinite')] yMinValue = safeMin(safeMin(series) for series in finiteData) if yMinValue is None: # This can only happen if there are no valid, non-infinite data. return (0.0, 1.0) if yMinValue > 0.0 and drawNullAsZero and missingValues: yMinValue = 0.0 if stacked: length = safeMin(len(series) for series in finiteData) sumSeries = [] for i in range(0, length): sumSeries.append(safeSum(series[i] for series in finiteData)) yMaxValue = safeMax(sumSeries) else: yMaxValue = safeMax(safeMax(series) for series in finiteData) if yMaxValue < 0.0 and drawNullAsZero and missingValues: yMaxValue = 0.0 return (yMinValue, yMaxValue)
python
def dataLimits(data, drawNullAsZero=False, stacked=False): """Return the range of values in data as (yMinValue, yMaxValue). data is an array of TimeSeries objects. """ missingValues = any(None in series for series in data) finiteData = [series for series in data if not series.options.get('drawAsInfinite')] yMinValue = safeMin(safeMin(series) for series in finiteData) if yMinValue is None: # This can only happen if there are no valid, non-infinite data. return (0.0, 1.0) if yMinValue > 0.0 and drawNullAsZero and missingValues: yMinValue = 0.0 if stacked: length = safeMin(len(series) for series in finiteData) sumSeries = [] for i in range(0, length): sumSeries.append(safeSum(series[i] for series in finiteData)) yMaxValue = safeMax(sumSeries) else: yMaxValue = safeMax(safeMax(series) for series in finiteData) if yMaxValue < 0.0 and drawNullAsZero and missingValues: yMaxValue = 0.0 return (yMinValue, yMaxValue)
[ "def", "dataLimits", "(", "data", ",", "drawNullAsZero", "=", "False", ",", "stacked", "=", "False", ")", ":", "missingValues", "=", "any", "(", "None", "in", "series", "for", "series", "in", "data", ")", "finiteData", "=", "[", "series", "for", "series", "in", "data", "if", "not", "series", ".", "options", ".", "get", "(", "'drawAsInfinite'", ")", "]", "yMinValue", "=", "safeMin", "(", "safeMin", "(", "series", ")", "for", "series", "in", "finiteData", ")", "if", "yMinValue", "is", "None", ":", "# This can only happen if there are no valid, non-infinite data.", "return", "(", "0.0", ",", "1.0", ")", "if", "yMinValue", ">", "0.0", "and", "drawNullAsZero", "and", "missingValues", ":", "yMinValue", "=", "0.0", "if", "stacked", ":", "length", "=", "safeMin", "(", "len", "(", "series", ")", "for", "series", "in", "finiteData", ")", "sumSeries", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "length", ")", ":", "sumSeries", ".", "append", "(", "safeSum", "(", "series", "[", "i", "]", "for", "series", "in", "finiteData", ")", ")", "yMaxValue", "=", "safeMax", "(", "sumSeries", ")", "else", ":", "yMaxValue", "=", "safeMax", "(", "safeMax", "(", "series", ")", "for", "series", "in", "finiteData", ")", "if", "yMaxValue", "<", "0.0", "and", "drawNullAsZero", "and", "missingValues", ":", "yMaxValue", "=", "0.0", "return", "(", "yMinValue", ",", "yMaxValue", ")" ]
Return the range of values in data as (yMinValue, yMaxValue). data is an array of TimeSeries objects.
[ "Return", "the", "range", "of", "values", "in", "data", "as", "(", "yMinValue", "yMaxValue", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L2172-L2203
brutasse/graphite-api
graphite_api/render/glyph.py
format_units
def format_units(v, step=None, system="si", units=None): """Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix """ if v is None: return 0, '' for prefix, size in UnitSystems[system]: if condition(v, size, step): v2 = v / size if v2 - math.floor(v2) < 0.00000000001 and v > 1: v2 = float(math.floor(v2)) if units: prefix = "%s%s" % (prefix, units) return v2, prefix if v - math.floor(v) < 0.00000000001 and v > 1: v = float(math.floor(v)) if units: prefix = units else: prefix = '' return v, prefix
python
def format_units(v, step=None, system="si", units=None): """Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix """ if v is None: return 0, '' for prefix, size in UnitSystems[system]: if condition(v, size, step): v2 = v / size if v2 - math.floor(v2) < 0.00000000001 and v > 1: v2 = float(math.floor(v2)) if units: prefix = "%s%s" % (prefix, units) return v2, prefix if v - math.floor(v) < 0.00000000001 and v > 1: v = float(math.floor(v)) if units: prefix = units else: prefix = '' return v, prefix
[ "def", "format_units", "(", "v", ",", "step", "=", "None", ",", "system", "=", "\"si\"", ",", "units", "=", "None", ")", ":", "if", "v", "is", "None", ":", "return", "0", ",", "''", "for", "prefix", ",", "size", "in", "UnitSystems", "[", "system", "]", ":", "if", "condition", "(", "v", ",", "size", ",", "step", ")", ":", "v2", "=", "v", "/", "size", "if", "v2", "-", "math", ".", "floor", "(", "v2", ")", "<", "0.00000000001", "and", "v", ">", "1", ":", "v2", "=", "float", "(", "math", ".", "floor", "(", "v2", ")", ")", "if", "units", ":", "prefix", "=", "\"%s%s\"", "%", "(", "prefix", ",", "units", ")", "return", "v2", ",", "prefix", "if", "v", "-", "math", ".", "floor", "(", "v", ")", "<", "0.00000000001", "and", "v", ">", "1", ":", "v", "=", "float", "(", "math", ".", "floor", "(", "v", ")", ")", "if", "units", ":", "prefix", "=", "units", "else", ":", "prefix", "=", "''", "return", "v", ",", "prefix" ]
Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix
[ "Format", "the", "given", "value", "in", "standardized", "units", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L2219-L2246
brutasse/graphite-api
graphite_api/render/glyph.py
_AxisTics.checkFinite
def checkFinite(value, name='value'): """Check that value is a finite number. If it is, return it. If not, raise GraphError describing the problem, using name in the error message. """ if math.isnan(value): raise GraphError('Encountered NaN %s' % (name,)) elif math.isinf(value): raise GraphError('Encountered infinite %s' % (name,)) return value
python
def checkFinite(value, name='value'): """Check that value is a finite number. If it is, return it. If not, raise GraphError describing the problem, using name in the error message. """ if math.isnan(value): raise GraphError('Encountered NaN %s' % (name,)) elif math.isinf(value): raise GraphError('Encountered infinite %s' % (name,)) return value
[ "def", "checkFinite", "(", "value", ",", "name", "=", "'value'", ")", ":", "if", "math", ".", "isnan", "(", "value", ")", ":", "raise", "GraphError", "(", "'Encountered NaN %s'", "%", "(", "name", ",", ")", ")", "elif", "math", ".", "isinf", "(", "value", ")", ":", "raise", "GraphError", "(", "'Encountered infinite %s'", "%", "(", "name", ",", ")", ")", "return", "value" ]
Check that value is a finite number. If it is, return it. If not, raise GraphError describing the problem, using name in the error message.
[ "Check", "that", "value", "is", "a", "finite", "number", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L347-L357
brutasse/graphite-api
graphite_api/render/glyph.py
_AxisTics.reconcileLimits
def reconcileLimits(self): """If self.minValue is not less than self.maxValue, fix the problem. If self.minValue is not less than self.maxValue, adjust self.minValue and/or self.maxValue (depending on which was not specified explicitly by the user) to make self.minValue < self.maxValue. If the user specified both limits explicitly, then raise GraphError. """ if self.minValue < self.maxValue: # The limits are already OK. return minFixed = (self.minValueSource in ['min']) maxFixed = (self.maxValueSource in ['max', 'limit']) if minFixed and maxFixed: raise GraphError('The %s must be less than the %s' % (self.minValueSource, self.maxValueSource)) elif minFixed: self.maxValue = self.minValue + self.chooseDelta(self.minValue) elif maxFixed: self.minValue = self.maxValue - self.chooseDelta(self.maxValue) else: delta = self.chooseDelta(max(abs(self.minValue), abs(self.maxValue))) average = (self.minValue + self.maxValue) / 2.0 self.minValue = average - delta self.maxValue = average + delta
python
def reconcileLimits(self): """If self.minValue is not less than self.maxValue, fix the problem. If self.minValue is not less than self.maxValue, adjust self.minValue and/or self.maxValue (depending on which was not specified explicitly by the user) to make self.minValue < self.maxValue. If the user specified both limits explicitly, then raise GraphError. """ if self.minValue < self.maxValue: # The limits are already OK. return minFixed = (self.minValueSource in ['min']) maxFixed = (self.maxValueSource in ['max', 'limit']) if minFixed and maxFixed: raise GraphError('The %s must be less than the %s' % (self.minValueSource, self.maxValueSource)) elif minFixed: self.maxValue = self.minValue + self.chooseDelta(self.minValue) elif maxFixed: self.minValue = self.maxValue - self.chooseDelta(self.maxValue) else: delta = self.chooseDelta(max(abs(self.minValue), abs(self.maxValue))) average = (self.minValue + self.maxValue) / 2.0 self.minValue = average - delta self.maxValue = average + delta
[ "def", "reconcileLimits", "(", "self", ")", ":", "if", "self", ".", "minValue", "<", "self", ".", "maxValue", ":", "# The limits are already OK.", "return", "minFixed", "=", "(", "self", ".", "minValueSource", "in", "[", "'min'", "]", ")", "maxFixed", "=", "(", "self", ".", "maxValueSource", "in", "[", "'max'", ",", "'limit'", "]", ")", "if", "minFixed", "and", "maxFixed", ":", "raise", "GraphError", "(", "'The %s must be less than the %s'", "%", "(", "self", ".", "minValueSource", ",", "self", ".", "maxValueSource", ")", ")", "elif", "minFixed", ":", "self", ".", "maxValue", "=", "self", ".", "minValue", "+", "self", ".", "chooseDelta", "(", "self", ".", "minValue", ")", "elif", "maxFixed", ":", "self", ".", "minValue", "=", "self", ".", "maxValue", "-", "self", ".", "chooseDelta", "(", "self", ".", "maxValue", ")", "else", ":", "delta", "=", "self", ".", "chooseDelta", "(", "max", "(", "abs", "(", "self", ".", "minValue", ")", ",", "abs", "(", "self", ".", "maxValue", ")", ")", ")", "average", "=", "(", "self", ".", "minValue", "+", "self", ".", "maxValue", ")", "/", "2.0", "self", ".", "minValue", "=", "average", "-", "delta", "self", ".", "maxValue", "=", "average", "+", "delta" ]
If self.minValue is not less than self.maxValue, fix the problem. If self.minValue is not less than self.maxValue, adjust self.minValue and/or self.maxValue (depending on which was not specified explicitly by the user) to make self.minValue < self.maxValue. If the user specified both limits explicitly, then raise GraphError.
[ "If", "self", ".", "minValue", "is", "not", "less", "than", "self", ".", "maxValue", "fix", "the", "problem", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L371-L399
brutasse/graphite-api
graphite_api/render/glyph.py
_AxisTics.applySettings
def applySettings(self, axisMin=None, axisMax=None, axisLimit=None): """Apply the specified settings to this axis. Set self.minValue, self.minValueSource, self.maxValue, self.maxValueSource, and self.axisLimit reasonably based on the parameters provided. Arguments: axisMin -- a finite number, or None to choose a round minimum limit that includes all of the data. axisMax -- a finite number, 'max' to use the maximum value contained in the data, or None to choose a round maximum limit that includes all of the data. axisLimit -- a finite number to use as an upper limit on maxValue, or None to impose no upper limit. """ if axisMin is not None and not math.isnan(axisMin): self.minValueSource = 'min' self.minValue = self.checkFinite(axisMin, 'axis min') if axisMax == 'max': self.maxValueSource = 'extremum' elif axisMax is not None and not math.isnan(axisMax): self.maxValueSource = 'max' self.maxValue = self.checkFinite(axisMax, 'axis max') if axisLimit is None or math.isnan(axisLimit): self.axisLimit = None elif axisLimit < self.maxValue: self.maxValue = self.checkFinite(axisLimit, 'axis limit') self.maxValueSource = 'limit' # The limit has already been imposed, so there is no need to # remember it: self.axisLimit = None elif math.isinf(axisLimit): # It must be positive infinity, which is the same as no limit: self.axisLimit = None else: # We still need to remember axisLimit to avoid rounding top to # a value larger than axisLimit: self.axisLimit = axisLimit self.reconcileLimits()
python
def applySettings(self, axisMin=None, axisMax=None, axisLimit=None): """Apply the specified settings to this axis. Set self.minValue, self.minValueSource, self.maxValue, self.maxValueSource, and self.axisLimit reasonably based on the parameters provided. Arguments: axisMin -- a finite number, or None to choose a round minimum limit that includes all of the data. axisMax -- a finite number, 'max' to use the maximum value contained in the data, or None to choose a round maximum limit that includes all of the data. axisLimit -- a finite number to use as an upper limit on maxValue, or None to impose no upper limit. """ if axisMin is not None and not math.isnan(axisMin): self.minValueSource = 'min' self.minValue = self.checkFinite(axisMin, 'axis min') if axisMax == 'max': self.maxValueSource = 'extremum' elif axisMax is not None and not math.isnan(axisMax): self.maxValueSource = 'max' self.maxValue = self.checkFinite(axisMax, 'axis max') if axisLimit is None or math.isnan(axisLimit): self.axisLimit = None elif axisLimit < self.maxValue: self.maxValue = self.checkFinite(axisLimit, 'axis limit') self.maxValueSource = 'limit' # The limit has already been imposed, so there is no need to # remember it: self.axisLimit = None elif math.isinf(axisLimit): # It must be positive infinity, which is the same as no limit: self.axisLimit = None else: # We still need to remember axisLimit to avoid rounding top to # a value larger than axisLimit: self.axisLimit = axisLimit self.reconcileLimits()
[ "def", "applySettings", "(", "self", ",", "axisMin", "=", "None", ",", "axisMax", "=", "None", ",", "axisLimit", "=", "None", ")", ":", "if", "axisMin", "is", "not", "None", "and", "not", "math", ".", "isnan", "(", "axisMin", ")", ":", "self", ".", "minValueSource", "=", "'min'", "self", ".", "minValue", "=", "self", ".", "checkFinite", "(", "axisMin", ",", "'axis min'", ")", "if", "axisMax", "==", "'max'", ":", "self", ".", "maxValueSource", "=", "'extremum'", "elif", "axisMax", "is", "not", "None", "and", "not", "math", ".", "isnan", "(", "axisMax", ")", ":", "self", ".", "maxValueSource", "=", "'max'", "self", ".", "maxValue", "=", "self", ".", "checkFinite", "(", "axisMax", ",", "'axis max'", ")", "if", "axisLimit", "is", "None", "or", "math", ".", "isnan", "(", "axisLimit", ")", ":", "self", ".", "axisLimit", "=", "None", "elif", "axisLimit", "<", "self", ".", "maxValue", ":", "self", ".", "maxValue", "=", "self", ".", "checkFinite", "(", "axisLimit", ",", "'axis limit'", ")", "self", ".", "maxValueSource", "=", "'limit'", "# The limit has already been imposed, so there is no need to", "# remember it:", "self", ".", "axisLimit", "=", "None", "elif", "math", ".", "isinf", "(", "axisLimit", ")", ":", "# It must be positive infinity, which is the same as no limit:", "self", ".", "axisLimit", "=", "None", "else", ":", "# We still need to remember axisLimit to avoid rounding top to", "# a value larger than axisLimit:", "self", ".", "axisLimit", "=", "axisLimit", "self", ".", "reconcileLimits", "(", ")" ]
Apply the specified settings to this axis. Set self.minValue, self.minValueSource, self.maxValue, self.maxValueSource, and self.axisLimit reasonably based on the parameters provided. Arguments: axisMin -- a finite number, or None to choose a round minimum limit that includes all of the data. axisMax -- a finite number, 'max' to use the maximum value contained in the data, or None to choose a round maximum limit that includes all of the data. axisLimit -- a finite number to use as an upper limit on maxValue, or None to impose no upper limit.
[ "Apply", "the", "specified", "settings", "to", "this", "axis", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L401-L446
brutasse/graphite-api
graphite_api/render/glyph.py
_AxisTics.makeLabel
def makeLabel(self, value): """Create a label for the specified value. Create a label string containing the value and its units (if any), based on the values of self.step, self.span, and self.unitSystem. """ value, prefix = format_units(value, self.step, system=self.unitSystem) span, spanPrefix = format_units(self.span, self.step, system=self.unitSystem) if prefix: prefix += " " if value < 0.1: return "%g %s" % (float(value), prefix) elif value < 1.0: return "%.2f %s" % (float(value), prefix) if span > 10 or spanPrefix != prefix: if type(value) is float: return "%.1f %s" % (value, prefix) else: return "%d %s" % (int(value), prefix) elif span > 3: return "%.1f %s" % (float(value), prefix) elif span > 0.1: return "%.2f %s" % (float(value), prefix) else: return "%g %s" % (float(value), prefix)
python
def makeLabel(self, value): """Create a label for the specified value. Create a label string containing the value and its units (if any), based on the values of self.step, self.span, and self.unitSystem. """ value, prefix = format_units(value, self.step, system=self.unitSystem) span, spanPrefix = format_units(self.span, self.step, system=self.unitSystem) if prefix: prefix += " " if value < 0.1: return "%g %s" % (float(value), prefix) elif value < 1.0: return "%.2f %s" % (float(value), prefix) if span > 10 or spanPrefix != prefix: if type(value) is float: return "%.1f %s" % (value, prefix) else: return "%d %s" % (int(value), prefix) elif span > 3: return "%.1f %s" % (float(value), prefix) elif span > 0.1: return "%.2f %s" % (float(value), prefix) else: return "%g %s" % (float(value), prefix)
[ "def", "makeLabel", "(", "self", ",", "value", ")", ":", "value", ",", "prefix", "=", "format_units", "(", "value", ",", "self", ".", "step", ",", "system", "=", "self", ".", "unitSystem", ")", "span", ",", "spanPrefix", "=", "format_units", "(", "self", ".", "span", ",", "self", ".", "step", ",", "system", "=", "self", ".", "unitSystem", ")", "if", "prefix", ":", "prefix", "+=", "\" \"", "if", "value", "<", "0.1", ":", "return", "\"%g %s\"", "%", "(", "float", "(", "value", ")", ",", "prefix", ")", "elif", "value", "<", "1.0", ":", "return", "\"%.2f %s\"", "%", "(", "float", "(", "value", ")", ",", "prefix", ")", "if", "span", ">", "10", "or", "spanPrefix", "!=", "prefix", ":", "if", "type", "(", "value", ")", "is", "float", ":", "return", "\"%.1f %s\"", "%", "(", "value", ",", "prefix", ")", "else", ":", "return", "\"%d %s\"", "%", "(", "int", "(", "value", ")", ",", "prefix", ")", "elif", "span", ">", "3", ":", "return", "\"%.1f %s\"", "%", "(", "float", "(", "value", ")", ",", "prefix", ")", "elif", "span", ">", "0.1", ":", "return", "\"%.2f %s\"", "%", "(", "float", "(", "value", ")", ",", "prefix", ")", "else", ":", "return", "\"%g %s\"", "%", "(", "float", "(", "value", ")", ",", "prefix", ")" ]
Create a label for the specified value. Create a label string containing the value and its units (if any), based on the values of self.step, self.span, and self.unitSystem.
[ "Create", "a", "label", "for", "the", "specified", "value", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L448-L474
brutasse/graphite-api
graphite_api/render/glyph.py
_LinearAxisTics.generateSteps
def generateSteps(self, minStep): """Generate allowed steps with step >= minStep in increasing order.""" self.checkFinite(minStep) if self.binary: base = 2.0 mantissas = [1.0] exponent = math.floor(math.log(minStep, 2) - EPSILON) else: base = 10.0 mantissas = [1.0, 2.0, 5.0] exponent = math.floor(math.log10(minStep) - EPSILON) while True: multiplier = base ** exponent for mantissa in mantissas: value = mantissa * multiplier if value >= minStep * (1.0 - EPSILON): yield value exponent += 1
python
def generateSteps(self, minStep): """Generate allowed steps with step >= minStep in increasing order.""" self.checkFinite(minStep) if self.binary: base = 2.0 mantissas = [1.0] exponent = math.floor(math.log(minStep, 2) - EPSILON) else: base = 10.0 mantissas = [1.0, 2.0, 5.0] exponent = math.floor(math.log10(minStep) - EPSILON) while True: multiplier = base ** exponent for mantissa in mantissas: value = mantissa * multiplier if value >= minStep * (1.0 - EPSILON): yield value exponent += 1
[ "def", "generateSteps", "(", "self", ",", "minStep", ")", ":", "self", ".", "checkFinite", "(", "minStep", ")", "if", "self", ".", "binary", ":", "base", "=", "2.0", "mantissas", "=", "[", "1.0", "]", "exponent", "=", "math", ".", "floor", "(", "math", ".", "log", "(", "minStep", ",", "2", ")", "-", "EPSILON", ")", "else", ":", "base", "=", "10.0", "mantissas", "=", "[", "1.0", ",", "2.0", ",", "5.0", "]", "exponent", "=", "math", ".", "floor", "(", "math", ".", "log10", "(", "minStep", ")", "-", "EPSILON", ")", "while", "True", ":", "multiplier", "=", "base", "**", "exponent", "for", "mantissa", "in", "mantissas", ":", "value", "=", "mantissa", "*", "multiplier", "if", "value", ">=", "minStep", "*", "(", "1.0", "-", "EPSILON", ")", ":", "yield", "value", "exponent", "+=", "1" ]
Generate allowed steps with step >= minStep in increasing order.
[ "Generate", "allowed", "steps", "with", "step", ">", "=", "minStep", "in", "increasing", "order", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L490-L509
brutasse/graphite-api
graphite_api/render/glyph.py
_LinearAxisTics.computeSlop
def computeSlop(self, step, divisor): """Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop". """ bottom = step * math.floor(self.minValue / float(step) + EPSILON) top = bottom + step * divisor if top >= self.maxValue - EPSILON * step: return max(top - self.maxValue, self.minValue - bottom) else: return None
python
def computeSlop(self, step, divisor): """Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop". """ bottom = step * math.floor(self.minValue / float(step) + EPSILON) top = bottom + step * divisor if top >= self.maxValue - EPSILON * step: return max(top - self.maxValue, self.minValue - bottom) else: return None
[ "def", "computeSlop", "(", "self", ",", "step", ",", "divisor", ")", ":", "bottom", "=", "step", "*", "math", ".", "floor", "(", "self", ".", "minValue", "/", "float", "(", "step", ")", "+", "EPSILON", ")", "top", "=", "bottom", "+", "step", "*", "divisor", "if", "top", ">=", "self", ".", "maxValue", "-", "EPSILON", "*", "step", ":", "return", "max", "(", "top", "-", "self", ".", "maxValue", ",", "self", ".", "minValue", "-", "bottom", ")", "else", ":", "return", "None" ]
Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop".
[ "Compute", "the", "slop", "that", "would", "result", "from", "step", "and", "divisor", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L511-L524
brutasse/graphite-api
graphite_api/render/glyph.py
_LinearAxisTics.chooseStep
def chooseStep(self, divisors=None, binary=False): """Choose a nice, pretty size for the steps between axis labels. Our main constraint is that the number of divisions must be taken from the divisors list. We pick a number of divisions and a step size that minimizes the amount of whitespace ("slop") that would need to be included outside of the range [self.minValue, self.maxValue] if we were to push out the axis values to the next larger multiples of the step size. The minimum step that could possibly cover the variance satisfies minStep * max(divisors) >= variance or minStep = variance / max(divisors) It's not necessarily possible to cover the variance with a step that size, but we know that any smaller step definitely *cannot* cover it. So we can start there. For a sufficiently large step size, it is definitely possible to cover the variance, but at some point the slop will start growing. Let's define the slop to be slop = max(minValue - bottom, top - maxValue) Then for a given, step size, we know that slop >= (1/2) * (step * min(divisors) - variance) (the factor of 1/2 is for the best-case scenario that the slop is distributed equally on the two sides of the range). So suppose we already have a choice that yields bestSlop. Then there is no need to choose steps so large that the slop is guaranteed to be larger than bestSlop. Therefore, the maximum step size that we need to consider is maxStep = (2 * bestSlop + variance) / min(divisors) """ self.binary = binary if divisors is None: divisors = [4, 5, 6] else: for divisor in divisors: self.checkFinite(divisor, 'divisor') if divisor < 1: raise GraphError('Divisors must be greater than or equal ' 'to one') if self.minValue == self.maxValue: if self.minValue == 0.0: self.maxValue = 1.0 elif self.minValue < 0.0: self.minValue *= 1.1 self.maxValue *= 0.9 else: self.minValue *= 0.9 self.maxValue *= 1.1 variance = self.maxValue - self.minValue bestSlop = None bestStep = None for step in self.generateSteps(variance / float(max(divisors))): if ( bestSlop is not None and step * min(divisors) >= 2 * bestSlop + variance ): break for divisor in divisors: slop = self.computeSlop(step, divisor) if slop is not None and (bestSlop is None or slop < bestSlop): bestSlop = slop bestStep = step self.step = bestStep
python
def chooseStep(self, divisors=None, binary=False): """Choose a nice, pretty size for the steps between axis labels. Our main constraint is that the number of divisions must be taken from the divisors list. We pick a number of divisions and a step size that minimizes the amount of whitespace ("slop") that would need to be included outside of the range [self.minValue, self.maxValue] if we were to push out the axis values to the next larger multiples of the step size. The minimum step that could possibly cover the variance satisfies minStep * max(divisors) >= variance or minStep = variance / max(divisors) It's not necessarily possible to cover the variance with a step that size, but we know that any smaller step definitely *cannot* cover it. So we can start there. For a sufficiently large step size, it is definitely possible to cover the variance, but at some point the slop will start growing. Let's define the slop to be slop = max(minValue - bottom, top - maxValue) Then for a given, step size, we know that slop >= (1/2) * (step * min(divisors) - variance) (the factor of 1/2 is for the best-case scenario that the slop is distributed equally on the two sides of the range). So suppose we already have a choice that yields bestSlop. Then there is no need to choose steps so large that the slop is guaranteed to be larger than bestSlop. Therefore, the maximum step size that we need to consider is maxStep = (2 * bestSlop + variance) / min(divisors) """ self.binary = binary if divisors is None: divisors = [4, 5, 6] else: for divisor in divisors: self.checkFinite(divisor, 'divisor') if divisor < 1: raise GraphError('Divisors must be greater than or equal ' 'to one') if self.minValue == self.maxValue: if self.minValue == 0.0: self.maxValue = 1.0 elif self.minValue < 0.0: self.minValue *= 1.1 self.maxValue *= 0.9 else: self.minValue *= 0.9 self.maxValue *= 1.1 variance = self.maxValue - self.minValue bestSlop = None bestStep = None for step in self.generateSteps(variance / float(max(divisors))): if ( bestSlop is not None and step * min(divisors) >= 2 * bestSlop + variance ): break for divisor in divisors: slop = self.computeSlop(step, divisor) if slop is not None and (bestSlop is None or slop < bestSlop): bestSlop = slop bestStep = step self.step = bestStep
[ "def", "chooseStep", "(", "self", ",", "divisors", "=", "None", ",", "binary", "=", "False", ")", ":", "self", ".", "binary", "=", "binary", "if", "divisors", "is", "None", ":", "divisors", "=", "[", "4", ",", "5", ",", "6", "]", "else", ":", "for", "divisor", "in", "divisors", ":", "self", ".", "checkFinite", "(", "divisor", ",", "'divisor'", ")", "if", "divisor", "<", "1", ":", "raise", "GraphError", "(", "'Divisors must be greater than or equal '", "'to one'", ")", "if", "self", ".", "minValue", "==", "self", ".", "maxValue", ":", "if", "self", ".", "minValue", "==", "0.0", ":", "self", ".", "maxValue", "=", "1.0", "elif", "self", ".", "minValue", "<", "0.0", ":", "self", ".", "minValue", "*=", "1.1", "self", ".", "maxValue", "*=", "0.9", "else", ":", "self", ".", "minValue", "*=", "0.9", "self", ".", "maxValue", "*=", "1.1", "variance", "=", "self", ".", "maxValue", "-", "self", ".", "minValue", "bestSlop", "=", "None", "bestStep", "=", "None", "for", "step", "in", "self", ".", "generateSteps", "(", "variance", "/", "float", "(", "max", "(", "divisors", ")", ")", ")", ":", "if", "(", "bestSlop", "is", "not", "None", "and", "step", "*", "min", "(", "divisors", ")", ">=", "2", "*", "bestSlop", "+", "variance", ")", ":", "break", "for", "divisor", "in", "divisors", ":", "slop", "=", "self", ".", "computeSlop", "(", "step", ",", "divisor", ")", "if", "slop", "is", "not", "None", "and", "(", "bestSlop", "is", "None", "or", "slop", "<", "bestSlop", ")", ":", "bestSlop", "=", "slop", "bestStep", "=", "step", "self", ".", "step", "=", "bestStep" ]
Choose a nice, pretty size for the steps between axis labels. Our main constraint is that the number of divisions must be taken from the divisors list. We pick a number of divisions and a step size that minimizes the amount of whitespace ("slop") that would need to be included outside of the range [self.minValue, self.maxValue] if we were to push out the axis values to the next larger multiples of the step size. The minimum step that could possibly cover the variance satisfies minStep * max(divisors) >= variance or minStep = variance / max(divisors) It's not necessarily possible to cover the variance with a step that size, but we know that any smaller step definitely *cannot* cover it. So we can start there. For a sufficiently large step size, it is definitely possible to cover the variance, but at some point the slop will start growing. Let's define the slop to be slop = max(minValue - bottom, top - maxValue) Then for a given, step size, we know that slop >= (1/2) * (step * min(divisors) - variance) (the factor of 1/2 is for the best-case scenario that the slop is distributed equally on the two sides of the range). So suppose we already have a choice that yields bestSlop. Then there is no need to choose steps so large that the slop is guaranteed to be larger than bestSlop. Therefore, the maximum step size that we need to consider is maxStep = (2 * bestSlop + variance) / min(divisors)
[ "Choose", "a", "nice", "pretty", "size", "for", "the", "steps", "between", "axis", "labels", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L526-L604
brutasse/graphite-api
graphite_api/functions.py
formatPathExpressions
def formatPathExpressions(seriesList): """ Returns a comma-separated list of unique path expressions. """ pathExpressions = sorted(set([s.pathExpression for s in seriesList])) return ','.join(pathExpressions)
python
def formatPathExpressions(seriesList): """ Returns a comma-separated list of unique path expressions. """ pathExpressions = sorted(set([s.pathExpression for s in seriesList])) return ','.join(pathExpressions)
[ "def", "formatPathExpressions", "(", "seriesList", ")", ":", "pathExpressions", "=", "sorted", "(", "set", "(", "[", "s", ".", "pathExpression", "for", "s", "in", "seriesList", "]", ")", ")", "return", "','", ".", "join", "(", "pathExpressions", ")" ]
Returns a comma-separated list of unique path expressions.
[ "Returns", "a", "comma", "-", "separated", "list", "of", "unique", "path", "expressions", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L185-L190
brutasse/graphite-api
graphite_api/functions.py
sumSeries
def sumSeries(requestContext, *seriesLists): """ Short form: sum() This will add metrics together and return the sum at each datapoint. (See integral for a sum over time) Example:: &target=sum(company.server.application*.requestsHandled) This would show the sum of all requests handled per minute (provided requestsHandled are collected once a minute). If metrics with different retention rates are combined, the coarsest metric is graphed, and the sum of the other metrics is averaged for the metrics with finer retention rates. """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "sumSeries(%s)" % formatPathExpressions(seriesList) values = (safeSum(row) for row in zip_longest(*seriesList)) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
python
def sumSeries(requestContext, *seriesLists): """ Short form: sum() This will add metrics together and return the sum at each datapoint. (See integral for a sum over time) Example:: &target=sum(company.server.application*.requestsHandled) This would show the sum of all requests handled per minute (provided requestsHandled are collected once a minute). If metrics with different retention rates are combined, the coarsest metric is graphed, and the sum of the other metrics is averaged for the metrics with finer retention rates. """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "sumSeries(%s)" % formatPathExpressions(seriesList) values = (safeSum(row) for row in zip_longest(*seriesList)) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
[ "def", "sumSeries", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "not", "seriesLists", "or", "not", "any", "(", "seriesLists", ")", ":", "return", "[", "]", "seriesList", ",", "start", ",", "end", ",", "step", "=", "normalize", "(", "seriesLists", ")", "name", "=", "\"sumSeries(%s)\"", "%", "formatPathExpressions", "(", "seriesList", ")", "values", "=", "(", "safeSum", "(", "row", ")", "for", "row", "in", "zip_longest", "(", "*", "seriesList", ")", ")", "series", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "series", ".", "pathExpression", "=", "name", "return", "[", "series", "]" ]
Short form: sum() This will add metrics together and return the sum at each datapoint. (See integral for a sum over time) Example:: &target=sum(company.server.application*.requestsHandled) This would show the sum of all requests handled per minute (provided requestsHandled are collected once a minute). If metrics with different retention rates are combined, the coarsest metric is graphed, and the sum of the other metrics is averaged for the metrics with finer retention rates.
[ "Short", "form", ":", "sum", "()" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L195-L220
brutasse/graphite-api
graphite_api/functions.py
sumSeriesWithWildcards
def sumSeriesWithWildcards(requestContext, seriesList, *positions): """ Call sumSeries after inserting wildcards at the given position(s). Example:: &target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=sumSeries(host.*.cpu-user.value)&target=sumSeries( host.*.cpu-system.value) """ newSeries = {} newNames = list() for series in seriesList: newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) if newname in newSeries: newSeries[newname] = sumSeries(requestContext, (series, newSeries[newname]))[0] else: newSeries[newname] = series newNames.append(newname) newSeries[newname].name = newname return [newSeries[name] for name in newNames]
python
def sumSeriesWithWildcards(requestContext, seriesList, *positions): """ Call sumSeries after inserting wildcards at the given position(s). Example:: &target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=sumSeries(host.*.cpu-user.value)&target=sumSeries( host.*.cpu-system.value) """ newSeries = {} newNames = list() for series in seriesList: newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) if newname in newSeries: newSeries[newname] = sumSeries(requestContext, (series, newSeries[newname]))[0] else: newSeries[newname] = series newNames.append(newname) newSeries[newname].name = newname return [newSeries[name] for name in newNames]
[ "def", "sumSeriesWithWildcards", "(", "requestContext", ",", "seriesList", ",", "*", "positions", ")", ":", "newSeries", "=", "{", "}", "newNames", "=", "list", "(", ")", "for", "series", "in", "seriesList", ":", "newname", "=", "'.'", ".", "join", "(", "map", "(", "lambda", "x", ":", "x", "[", "1", "]", ",", "filter", "(", "lambda", "i", ":", "i", "[", "0", "]", "not", "in", "positions", ",", "enumerate", "(", "series", ".", "name", ".", "split", "(", "'.'", ")", ")", ")", ")", ")", "if", "newname", "in", "newSeries", ":", "newSeries", "[", "newname", "]", "=", "sumSeries", "(", "requestContext", ",", "(", "series", ",", "newSeries", "[", "newname", "]", ")", ")", "[", "0", "]", "else", ":", "newSeries", "[", "newname", "]", "=", "series", "newNames", ".", "append", "(", "newname", ")", "newSeries", "[", "newname", "]", ".", "name", "=", "newname", "return", "[", "newSeries", "[", "name", "]", "for", "name", "in", "newNames", "]" ]
Call sumSeries after inserting wildcards at the given position(s). Example:: &target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=sumSeries(host.*.cpu-user.value)&target=sumSeries( host.*.cpu-system.value)
[ "Call", "sumSeries", "after", "inserting", "wildcards", "at", "the", "given", "position", "(", "s", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L223-L253
brutasse/graphite-api
graphite_api/functions.py
averageSeriesWithWildcards
def averageSeriesWithWildcards(requestContext, seriesList, *positions): """ Call averageSeries after inserting wildcards at the given position(s). Example:: &target=averageSeriesWithWildcards( host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=averageSeries(host.*.cpu-user.value)&target=averageSeries( host.*.cpu-system.value) """ matchedList = defaultdict(list) for series in seriesList: newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) matchedList[newname].append(series) result = [] for name in matchedList: [series] = averageSeries(requestContext, (matchedList[name])) series.name = name result.append(series) return result
python
def averageSeriesWithWildcards(requestContext, seriesList, *positions): """ Call averageSeries after inserting wildcards at the given position(s). Example:: &target=averageSeriesWithWildcards( host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=averageSeries(host.*.cpu-user.value)&target=averageSeries( host.*.cpu-system.value) """ matchedList = defaultdict(list) for series in seriesList: newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) matchedList[newname].append(series) result = [] for name in matchedList: [series] = averageSeries(requestContext, (matchedList[name])) series.name = name result.append(series) return result
[ "def", "averageSeriesWithWildcards", "(", "requestContext", ",", "seriesList", ",", "*", "positions", ")", ":", "matchedList", "=", "defaultdict", "(", "list", ")", "for", "series", "in", "seriesList", ":", "newname", "=", "'.'", ".", "join", "(", "map", "(", "lambda", "x", ":", "x", "[", "1", "]", ",", "filter", "(", "lambda", "i", ":", "i", "[", "0", "]", "not", "in", "positions", ",", "enumerate", "(", "series", ".", "name", ".", "split", "(", "'.'", ")", ")", ")", ")", ")", "matchedList", "[", "newname", "]", ".", "append", "(", "series", ")", "result", "=", "[", "]", "for", "name", "in", "matchedList", ":", "[", "series", "]", "=", "averageSeries", "(", "requestContext", ",", "(", "matchedList", "[", "name", "]", ")", ")", "series", ".", "name", "=", "name", "result", ".", "append", "(", "series", ")", "return", "result" ]
Call averageSeries after inserting wildcards at the given position(s). Example:: &target=averageSeriesWithWildcards( host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=averageSeries(host.*.cpu-user.value)&target=averageSeries( host.*.cpu-system.value)
[ "Call", "averageSeries", "after", "inserting", "wildcards", "at", "the", "given", "position", "(", "s", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L256-L282
brutasse/graphite-api
graphite_api/functions.py
multiplySeriesWithWildcards
def multiplySeriesWithWildcards(requestContext, seriesList, *position): """ Call multiplySeries after inserting wildcards at the given position(s). Example:: &target=multiplySeriesWithWildcards( web.host-[0-7].{avg-response,total-request}.value, 2) This would be the equivalent of:: &target=multiplySeries(web.host-0.{avg-response,total-request}.value) &target=multiplySeries(web.host-1.{avg-response,total-request}.value) ... """ positions = [position] if isinstance(position, int) else position newSeries = {} newNames = [] for series in seriesList: new_name = ".".join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) if new_name in newSeries: [newSeries[new_name]] = multiplySeries(requestContext, (newSeries[new_name], series)) else: newSeries[new_name] = series newNames.append(new_name) newSeries[new_name].name = new_name return [newSeries[name] for name in newNames]
python
def multiplySeriesWithWildcards(requestContext, seriesList, *position): """ Call multiplySeries after inserting wildcards at the given position(s). Example:: &target=multiplySeriesWithWildcards( web.host-[0-7].{avg-response,total-request}.value, 2) This would be the equivalent of:: &target=multiplySeries(web.host-0.{avg-response,total-request}.value) &target=multiplySeries(web.host-1.{avg-response,total-request}.value) ... """ positions = [position] if isinstance(position, int) else position newSeries = {} newNames = [] for series in seriesList: new_name = ".".join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.'))))) if new_name in newSeries: [newSeries[new_name]] = multiplySeries(requestContext, (newSeries[new_name], series)) else: newSeries[new_name] = series newNames.append(new_name) newSeries[new_name].name = new_name return [newSeries[name] for name in newNames]
[ "def", "multiplySeriesWithWildcards", "(", "requestContext", ",", "seriesList", ",", "*", "position", ")", ":", "positions", "=", "[", "position", "]", "if", "isinstance", "(", "position", ",", "int", ")", "else", "position", "newSeries", "=", "{", "}", "newNames", "=", "[", "]", "for", "series", "in", "seriesList", ":", "new_name", "=", "\".\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "x", "[", "1", "]", ",", "filter", "(", "lambda", "i", ":", "i", "[", "0", "]", "not", "in", "positions", ",", "enumerate", "(", "series", ".", "name", ".", "split", "(", "'.'", ")", ")", ")", ")", ")", "if", "new_name", "in", "newSeries", ":", "[", "newSeries", "[", "new_name", "]", "]", "=", "multiplySeries", "(", "requestContext", ",", "(", "newSeries", "[", "new_name", "]", ",", "series", ")", ")", "else", ":", "newSeries", "[", "new_name", "]", "=", "series", "newNames", ".", "append", "(", "new_name", ")", "newSeries", "[", "new_name", "]", ".", "name", "=", "new_name", "return", "[", "newSeries", "[", "name", "]", "for", "name", "in", "newNames", "]" ]
Call multiplySeries after inserting wildcards at the given position(s). Example:: &target=multiplySeriesWithWildcards( web.host-[0-7].{avg-response,total-request}.value, 2) This would be the equivalent of:: &target=multiplySeries(web.host-0.{avg-response,total-request}.value) &target=multiplySeries(web.host-1.{avg-response,total-request}.value) ...
[ "Call", "multiplySeries", "after", "inserting", "wildcards", "at", "the", "given", "position", "(", "s", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L285-L318
brutasse/graphite-api
graphite_api/functions.py
rangeOfSeries
def rangeOfSeries(requestContext, *seriesLists): """ Takes a wildcard seriesList. Distills down a set of inputs into the range of the series Example:: &target=rangeOfSeries(Server*.connections.total) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "rangeOfSeries(%s)" % formatPathExpressions(seriesList) values = (safeSubtract(max(row), min(row)) for row in zip_longest(*seriesList)) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
python
def rangeOfSeries(requestContext, *seriesLists): """ Takes a wildcard seriesList. Distills down a set of inputs into the range of the series Example:: &target=rangeOfSeries(Server*.connections.total) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "rangeOfSeries(%s)" % formatPathExpressions(seriesList) values = (safeSubtract(max(row), min(row)) for row in zip_longest(*seriesList)) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
[ "def", "rangeOfSeries", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "not", "seriesLists", "or", "not", "any", "(", "seriesLists", ")", ":", "return", "[", "]", "seriesList", ",", "start", ",", "end", ",", "step", "=", "normalize", "(", "seriesLists", ")", "name", "=", "\"rangeOfSeries(%s)\"", "%", "formatPathExpressions", "(", "seriesList", ")", "values", "=", "(", "safeSubtract", "(", "max", "(", "row", ")", ",", "min", "(", "row", ")", ")", "for", "row", "in", "zip_longest", "(", "*", "seriesList", ")", ")", "series", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "series", ".", "pathExpression", "=", "name", "return", "[", "series", "]" ]
Takes a wildcard seriesList. Distills down a set of inputs into the range of the series Example:: &target=rangeOfSeries(Server*.connections.total)
[ "Takes", "a", "wildcard", "seriesList", ".", "Distills", "down", "a", "set", "of", "inputs", "into", "the", "range", "of", "the", "series" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L434-L452
brutasse/graphite-api
graphite_api/functions.py
percentileOfSeries
def percentileOfSeries(requestContext, seriesList, n, interpolate=False): """ percentileOfSeries returns a single series which is composed of the n-percentile values taken across a wildcard series at each point. Unless `interpolate` is set to True, percentile values are actual values contained in one of the supplied series. """ if n <= 0: raise ValueError( 'The requested percent is required to be greater than 0') if not seriesList: return [] name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n) start, end, step = normalize([seriesList])[1:] values = [_getPercentile(row, n, interpolate) for row in zip_longest(*seriesList)] resultSeries = TimeSeries(name, start, end, step, values) resultSeries.pathExpression = name return [resultSeries]
python
def percentileOfSeries(requestContext, seriesList, n, interpolate=False): """ percentileOfSeries returns a single series which is composed of the n-percentile values taken across a wildcard series at each point. Unless `interpolate` is set to True, percentile values are actual values contained in one of the supplied series. """ if n <= 0: raise ValueError( 'The requested percent is required to be greater than 0') if not seriesList: return [] name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n) start, end, step = normalize([seriesList])[1:] values = [_getPercentile(row, n, interpolate) for row in zip_longest(*seriesList)] resultSeries = TimeSeries(name, start, end, step, values) resultSeries.pathExpression = name return [resultSeries]
[ "def", "percentileOfSeries", "(", "requestContext", ",", "seriesList", ",", "n", ",", "interpolate", "=", "False", ")", ":", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "'The requested percent is required to be greater than 0'", ")", "if", "not", "seriesList", ":", "return", "[", "]", "name", "=", "'percentileOfSeries(%s,%g)'", "%", "(", "seriesList", "[", "0", "]", ".", "pathExpression", ",", "n", ")", "start", ",", "end", ",", "step", "=", "normalize", "(", "[", "seriesList", "]", ")", "[", "1", ":", "]", "values", "=", "[", "_getPercentile", "(", "row", ",", "n", ",", "interpolate", ")", "for", "row", "in", "zip_longest", "(", "*", "seriesList", ")", "]", "resultSeries", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "resultSeries", ".", "pathExpression", "=", "name", "return", "[", "resultSeries", "]" ]
percentileOfSeries returns a single series which is composed of the n-percentile values taken across a wildcard series at each point. Unless `interpolate` is set to True, percentile values are actual values contained in one of the supplied series.
[ "percentileOfSeries", "returns", "a", "single", "series", "which", "is", "composed", "of", "the", "n", "-", "percentile", "values", "taken", "across", "a", "wildcard", "series", "at", "each", "point", ".", "Unless", "interpolate", "is", "set", "to", "True", "percentile", "values", "are", "actual", "values", "contained", "in", "one", "of", "the", "supplied", "series", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L455-L474
brutasse/graphite-api
graphite_api/functions.py
keepLastValue
def keepLastValue(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=keepLastValue(Server01.connections.handled) &target=keepLastValue(Server01.connections.handled, 10) """ for series in seriesList: series.name = "keepLastValue(%s)" % (series.name) series.pathExpression = series.name consecutiveNones = 0 for i, value in enumerate(series): series[i] = value # No 'keeping' can be done on the first value because we have no # idea what came before it. if i == 0: continue if value is None: consecutiveNones += 1 else: if 0 < consecutiveNones <= limit: # If a non-None value is seen before the limit of Nones is # hit, backfill all the missing datapoints with the last # known value. for index in range(i - consecutiveNones, i): series[index] = series[i - consecutiveNones - 1] consecutiveNones = 0 # If the series ends with some None values, try to backfill a bit to # cover it. if 0 < consecutiveNones <= limit: for index in range(len(series) - consecutiveNones, len(series)): series[index] = series[len(series) - consecutiveNones - 1] return seriesList
python
def keepLastValue(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=keepLastValue(Server01.connections.handled) &target=keepLastValue(Server01.connections.handled, 10) """ for series in seriesList: series.name = "keepLastValue(%s)" % (series.name) series.pathExpression = series.name consecutiveNones = 0 for i, value in enumerate(series): series[i] = value # No 'keeping' can be done on the first value because we have no # idea what came before it. if i == 0: continue if value is None: consecutiveNones += 1 else: if 0 < consecutiveNones <= limit: # If a non-None value is seen before the limit of Nones is # hit, backfill all the missing datapoints with the last # known value. for index in range(i - consecutiveNones, i): series[index] = series[i - consecutiveNones - 1] consecutiveNones = 0 # If the series ends with some None values, try to backfill a bit to # cover it. if 0 < consecutiveNones <= limit: for index in range(len(series) - consecutiveNones, len(series)): series[index] = series[len(series) - consecutiveNones - 1] return seriesList
[ "def", "keepLastValue", "(", "requestContext", ",", "seriesList", ",", "limit", "=", "INF", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"keepLastValue(%s)\"", "%", "(", "series", ".", "name", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "consecutiveNones", "=", "0", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "value", "# No 'keeping' can be done on the first value because we have no", "# idea what came before it.", "if", "i", "==", "0", ":", "continue", "if", "value", "is", "None", ":", "consecutiveNones", "+=", "1", "else", ":", "if", "0", "<", "consecutiveNones", "<=", "limit", ":", "# If a non-None value is seen before the limit of Nones is", "# hit, backfill all the missing datapoints with the last", "# known value.", "for", "index", "in", "range", "(", "i", "-", "consecutiveNones", ",", "i", ")", ":", "series", "[", "index", "]", "=", "series", "[", "i", "-", "consecutiveNones", "-", "1", "]", "consecutiveNones", "=", "0", "# If the series ends with some None values, try to backfill a bit to", "# cover it.", "if", "0", "<", "consecutiveNones", "<=", "limit", ":", "for", "index", "in", "range", "(", "len", "(", "series", ")", "-", "consecutiveNones", ",", "len", "(", "series", ")", ")", ":", "series", "[", "index", "]", "=", "series", "[", "len", "(", "series", ")", "-", "consecutiveNones", "-", "1", "]", "return", "seriesList" ]
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=keepLastValue(Server01.connections.handled) &target=keepLastValue(Server01.connections.handled, 10)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "optionally", "a", "limit", "to", "the", "number", "of", "None", "values", "to", "skip", "over", ".", "Continues", "the", "line", "with", "the", "last", "received", "value", "when", "gaps", "(", "None", "values", ")", "appear", "in", "your", "data", "rather", "than", "breaking", "your", "line", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L477-L520
brutasse/graphite-api
graphite_api/functions.py
interpolate
def interpolate(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=interpolate(Server01.connections.handled) &target=interpolate(Server01.connections.handled, 10) """ for series in seriesList: series.name = "interpolate(%s)" % (series.name) series.pathExpression = series.name consecutiveNones = 0 for i, value in enumerate(series): series[i] = value # No 'keeping' can be done on the first value because we have no # idea what came before it. if i == 0: continue if value is None: consecutiveNones += 1 elif consecutiveNones == 0: # Have a value but no need to interpolate continue elif series[i - consecutiveNones - 1] is None: # Have a value but can't interpolate: reset count consecutiveNones = 0 continue else: # Have a value and can interpolate. If a non-None value is # seen before the limit of Nones is hit, backfill all the # missing datapoints with the last known value. if consecutiveNones > 0 and consecutiveNones <= limit: lastIndex = i - consecutiveNones - 1 lastValue = series[lastIndex] for index in range(i - consecutiveNones, i): nextValue = lastValue + (index - lastIndex) nextValue = nextValue * (value - lastValue) nextValue = nextValue / (consecutiveNones + 1) series[index] = nextValue consecutiveNones = 0 return seriesList
python
def interpolate(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=interpolate(Server01.connections.handled) &target=interpolate(Server01.connections.handled, 10) """ for series in seriesList: series.name = "interpolate(%s)" % (series.name) series.pathExpression = series.name consecutiveNones = 0 for i, value in enumerate(series): series[i] = value # No 'keeping' can be done on the first value because we have no # idea what came before it. if i == 0: continue if value is None: consecutiveNones += 1 elif consecutiveNones == 0: # Have a value but no need to interpolate continue elif series[i - consecutiveNones - 1] is None: # Have a value but can't interpolate: reset count consecutiveNones = 0 continue else: # Have a value and can interpolate. If a non-None value is # seen before the limit of Nones is hit, backfill all the # missing datapoints with the last known value. if consecutiveNones > 0 and consecutiveNones <= limit: lastIndex = i - consecutiveNones - 1 lastValue = series[lastIndex] for index in range(i - consecutiveNones, i): nextValue = lastValue + (index - lastIndex) nextValue = nextValue * (value - lastValue) nextValue = nextValue / (consecutiveNones + 1) series[index] = nextValue consecutiveNones = 0 return seriesList
[ "def", "interpolate", "(", "requestContext", ",", "seriesList", ",", "limit", "=", "INF", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"interpolate(%s)\"", "%", "(", "series", ".", "name", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "consecutiveNones", "=", "0", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "value", "# No 'keeping' can be done on the first value because we have no", "# idea what came before it.", "if", "i", "==", "0", ":", "continue", "if", "value", "is", "None", ":", "consecutiveNones", "+=", "1", "elif", "consecutiveNones", "==", "0", ":", "# Have a value but no need to interpolate", "continue", "elif", "series", "[", "i", "-", "consecutiveNones", "-", "1", "]", "is", "None", ":", "# Have a value but can't interpolate: reset count", "consecutiveNones", "=", "0", "continue", "else", ":", "# Have a value and can interpolate. If a non-None value is", "# seen before the limit of Nones is hit, backfill all the", "# missing datapoints with the last known value.", "if", "consecutiveNones", ">", "0", "and", "consecutiveNones", "<=", "limit", ":", "lastIndex", "=", "i", "-", "consecutiveNones", "-", "1", "lastValue", "=", "series", "[", "lastIndex", "]", "for", "index", "in", "range", "(", "i", "-", "consecutiveNones", ",", "i", ")", ":", "nextValue", "=", "lastValue", "+", "(", "index", "-", "lastIndex", ")", "nextValue", "=", "nextValue", "*", "(", "value", "-", "lastValue", ")", "nextValue", "=", "nextValue", "/", "(", "consecutiveNones", "+", "1", ")", "series", "[", "index", "]", "=", "nextValue", "consecutiveNones", "=", "0", "return", "seriesList" ]
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=interpolate(Server01.connections.handled) &target=interpolate(Server01.connections.handled, 10)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "optionally", "a", "limit", "to", "the", "number", "of", "None", "values", "to", "skip", "over", ".", "Continues", "the", "line", "with", "the", "last", "received", "value", "when", "gaps", "(", "None", "values", ")", "appear", "in", "your", "data", "rather", "than", "breaking", "your", "line", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L523-L571
brutasse/graphite-api
graphite_api/functions.py
changed
def changed(requestContext, seriesList): """ Takes one metric or a wildcard seriesList. Output 1 when the value changed, 0 when null or the same Example:: &target=changed(Server01.connections.handled) """ for series in seriesList: series.name = series.pathExpression = 'changed(%s)' % series.name previous = None for index, value in enumerate(series): if previous is None: series[index] = 0 elif value is not None and previous != value: series[index] = 1 else: series[index] = 0 previous = value return seriesList
python
def changed(requestContext, seriesList): """ Takes one metric or a wildcard seriesList. Output 1 when the value changed, 0 when null or the same Example:: &target=changed(Server01.connections.handled) """ for series in seriesList: series.name = series.pathExpression = 'changed(%s)' % series.name previous = None for index, value in enumerate(series): if previous is None: series[index] = 0 elif value is not None and previous != value: series[index] = 1 else: series[index] = 0 previous = value return seriesList
[ "def", "changed", "(", "requestContext", ",", "seriesList", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "series", ".", "pathExpression", "=", "'changed(%s)'", "%", "series", ".", "name", "previous", "=", "None", "for", "index", ",", "value", "in", "enumerate", "(", "series", ")", ":", "if", "previous", "is", "None", ":", "series", "[", "index", "]", "=", "0", "elif", "value", "is", "not", "None", "and", "previous", "!=", "value", ":", "series", "[", "index", "]", "=", "1", "else", ":", "series", "[", "index", "]", "=", "0", "previous", "=", "value", "return", "seriesList" ]
Takes one metric or a wildcard seriesList. Output 1 when the value changed, 0 when null or the same Example:: &target=changed(Server01.connections.handled)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", ".", "Output", "1", "when", "the", "value", "changed", "0", "when", "null", "or", "the", "same", "Example", "::" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L574-L593
brutasse/graphite-api
graphite_api/functions.py
divideSeriesLists
def divideSeriesLists(requestContext, dividendSeriesList, divisorSeriesList): """ Iterates over a two lists and divides list1[0] by list2[0], list1[1] by list2[1] and so on. The lists need to be the same length """ if len(dividendSeriesList) != len(divisorSeriesList): raise ValueError("dividendSeriesList and divisorSeriesList argument\ must have equal length") results = [] for dividendSeries, divisorSeries in zip(dividendSeriesList, divisorSeriesList): name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name) bothSeries = (dividendSeries, divisorSeries) step = reduce(lcm, [s.step for s in bothSeries]) for s in bothSeries: s.consolidate(step // s.step) start = min([s.start for s in bothSeries]) end = max([s.end for s in bothSeries]) end -= (end - start) % step values = (safeDiv(v1, v2) for v1, v2 in zip(*bothSeries)) quotientSeries = TimeSeries(name, start, end, step, values) results.append(quotientSeries) return results
python
def divideSeriesLists(requestContext, dividendSeriesList, divisorSeriesList): """ Iterates over a two lists and divides list1[0] by list2[0], list1[1] by list2[1] and so on. The lists need to be the same length """ if len(dividendSeriesList) != len(divisorSeriesList): raise ValueError("dividendSeriesList and divisorSeriesList argument\ must have equal length") results = [] for dividendSeries, divisorSeries in zip(dividendSeriesList, divisorSeriesList): name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name) bothSeries = (dividendSeries, divisorSeries) step = reduce(lcm, [s.step for s in bothSeries]) for s in bothSeries: s.consolidate(step // s.step) start = min([s.start for s in bothSeries]) end = max([s.end for s in bothSeries]) end -= (end - start) % step values = (safeDiv(v1, v2) for v1, v2 in zip(*bothSeries)) quotientSeries = TimeSeries(name, start, end, step, values) results.append(quotientSeries) return results
[ "def", "divideSeriesLists", "(", "requestContext", ",", "dividendSeriesList", ",", "divisorSeriesList", ")", ":", "if", "len", "(", "dividendSeriesList", ")", "!=", "len", "(", "divisorSeriesList", ")", ":", "raise", "ValueError", "(", "\"dividendSeriesList and divisorSeriesList argument\\\n must have equal length\"", ")", "results", "=", "[", "]", "for", "dividendSeries", ",", "divisorSeries", "in", "zip", "(", "dividendSeriesList", ",", "divisorSeriesList", ")", ":", "name", "=", "\"divideSeries(%s,%s)\"", "%", "(", "dividendSeries", ".", "name", ",", "divisorSeries", ".", "name", ")", "bothSeries", "=", "(", "dividendSeries", ",", "divisorSeries", ")", "step", "=", "reduce", "(", "lcm", ",", "[", "s", ".", "step", "for", "s", "in", "bothSeries", "]", ")", "for", "s", "in", "bothSeries", ":", "s", ".", "consolidate", "(", "step", "//", "s", ".", "step", ")", "start", "=", "min", "(", "[", "s", ".", "start", "for", "s", "in", "bothSeries", "]", ")", "end", "=", "max", "(", "[", "s", ".", "end", "for", "s", "in", "bothSeries", "]", ")", "end", "-=", "(", "end", "-", "start", ")", "%", "step", "values", "=", "(", "safeDiv", "(", "v1", ",", "v2", ")", "for", "v1", ",", "v2", "in", "zip", "(", "*", "bothSeries", ")", ")", "quotientSeries", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "results", ".", "append", "(", "quotientSeries", ")", "return", "results" ]
Iterates over a two lists and divides list1[0] by list2[0], list1[1] by list2[1] and so on. The lists need to be the same length
[ "Iterates", "over", "a", "two", "lists", "and", "divides", "list1", "[", "0", "]", "by", "list2", "[", "0", "]", "list1", "[", "1", "]", "by", "list2", "[", "1", "]", "and", "so", "on", ".", "The", "lists", "need", "to", "be", "the", "same", "length" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L664-L695
brutasse/graphite-api
graphite_api/functions.py
divideSeries
def divideSeries(requestContext, dividendSeriesList, divisorSeriesList): """ Takes a dividend metric and a divisor metric and draws the division result. A constant may *not* be passed. To divide by a constant, use the scale() function (which is essentially a multiplication operation) and use the inverse of the dividend. (Division by 8 = multiplication by 1/8 or 0.125) Example:: &target=divideSeries(Series.dividends,Series.divisors) """ if len(divisorSeriesList) == 0: for series in dividendSeriesList: series.name = "divideSeries(%s,MISSING)" % series.name series.pathExpression = series.name for i in range(len(series)): series[i] = None return dividendSeriesList if len(divisorSeriesList) > 1: raise ValueError( "divideSeries second argument must reference exactly 1 series" " (got {0})".format(len(divisorSeriesList))) [divisorSeries] = divisorSeriesList results = [] for dividendSeries in dividendSeriesList: name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name) bothSeries = (dividendSeries, divisorSeries) step = reduce(lcm, [s.step for s in bothSeries]) for s in bothSeries: s.consolidate(step / s.step) start = min([s.start for s in bothSeries]) end = max([s.end for s in bothSeries]) end -= (end - start) % step values = (safeDiv(v1, v2) for v1, v2 in zip_longest(*bothSeries)) quotientSeries = TimeSeries(name, start, end, step, values) quotientSeries.pathExpression = name results.append(quotientSeries) return results
python
def divideSeries(requestContext, dividendSeriesList, divisorSeriesList): """ Takes a dividend metric and a divisor metric and draws the division result. A constant may *not* be passed. To divide by a constant, use the scale() function (which is essentially a multiplication operation) and use the inverse of the dividend. (Division by 8 = multiplication by 1/8 or 0.125) Example:: &target=divideSeries(Series.dividends,Series.divisors) """ if len(divisorSeriesList) == 0: for series in dividendSeriesList: series.name = "divideSeries(%s,MISSING)" % series.name series.pathExpression = series.name for i in range(len(series)): series[i] = None return dividendSeriesList if len(divisorSeriesList) > 1: raise ValueError( "divideSeries second argument must reference exactly 1 series" " (got {0})".format(len(divisorSeriesList))) [divisorSeries] = divisorSeriesList results = [] for dividendSeries in dividendSeriesList: name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name) bothSeries = (dividendSeries, divisorSeries) step = reduce(lcm, [s.step for s in bothSeries]) for s in bothSeries: s.consolidate(step / s.step) start = min([s.start for s in bothSeries]) end = max([s.end for s in bothSeries]) end -= (end - start) % step values = (safeDiv(v1, v2) for v1, v2 in zip_longest(*bothSeries)) quotientSeries = TimeSeries(name, start, end, step, values) quotientSeries.pathExpression = name results.append(quotientSeries) return results
[ "def", "divideSeries", "(", "requestContext", ",", "dividendSeriesList", ",", "divisorSeriesList", ")", ":", "if", "len", "(", "divisorSeriesList", ")", "==", "0", ":", "for", "series", "in", "dividendSeriesList", ":", "series", ".", "name", "=", "\"divideSeries(%s,MISSING)\"", "%", "series", ".", "name", "series", ".", "pathExpression", "=", "series", ".", "name", "for", "i", "in", "range", "(", "len", "(", "series", ")", ")", ":", "series", "[", "i", "]", "=", "None", "return", "dividendSeriesList", "if", "len", "(", "divisorSeriesList", ")", ">", "1", ":", "raise", "ValueError", "(", "\"divideSeries second argument must reference exactly 1 series\"", "\" (got {0})\"", ".", "format", "(", "len", "(", "divisorSeriesList", ")", ")", ")", "[", "divisorSeries", "]", "=", "divisorSeriesList", "results", "=", "[", "]", "for", "dividendSeries", "in", "dividendSeriesList", ":", "name", "=", "\"divideSeries(%s,%s)\"", "%", "(", "dividendSeries", ".", "name", ",", "divisorSeries", ".", "name", ")", "bothSeries", "=", "(", "dividendSeries", ",", "divisorSeries", ")", "step", "=", "reduce", "(", "lcm", ",", "[", "s", ".", "step", "for", "s", "in", "bothSeries", "]", ")", "for", "s", "in", "bothSeries", ":", "s", ".", "consolidate", "(", "step", "/", "s", ".", "step", ")", "start", "=", "min", "(", "[", "s", ".", "start", "for", "s", "in", "bothSeries", "]", ")", "end", "=", "max", "(", "[", "s", ".", "end", "for", "s", "in", "bothSeries", "]", ")", "end", "-=", "(", "end", "-", "start", ")", "%", "step", "values", "=", "(", "safeDiv", "(", "v1", ",", "v2", ")", "for", "v1", ",", "v2", "in", "zip_longest", "(", "*", "bothSeries", ")", ")", "quotientSeries", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "quotientSeries", ".", "pathExpression", "=", "name", "results", ".", "append", "(", "quotientSeries", ")", "return", "results" ]
Takes a dividend metric and a divisor metric and draws the division result. A constant may *not* be passed. To divide by a constant, use the scale() function (which is essentially a multiplication operation) and use the inverse of the dividend. (Division by 8 = multiplication by 1/8 or 0.125) Example:: &target=divideSeries(Series.dividends,Series.divisors)
[ "Takes", "a", "dividend", "metric", "and", "a", "divisor", "metric", "and", "draws", "the", "division", "result", ".", "A", "constant", "may", "*", "not", "*", "be", "passed", ".", "To", "divide", "by", "a", "constant", "use", "the", "scale", "()", "function", "(", "which", "is", "essentially", "a", "multiplication", "operation", ")", "and", "use", "the", "inverse", "of", "the", "dividend", ".", "(", "Division", "by", "8", "=", "multiplication", "by", "1", "/", "8", "or", "0", ".", "125", ")" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L698-L745
brutasse/graphite-api
graphite_api/functions.py
multiplySeries
def multiplySeries(requestContext, *seriesLists): """ Takes two or more series and multiplies their points. A constant may not be used. To multiply by a constant, use the scale() function. Example:: &target=multiplySeries(Series.dividends,Series.divisors) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) if len(seriesList) == 1: return seriesList name = "multiplySeries(%s)" % ','.join([s.name for s in seriesList]) product = map(lambda x: safeMul(*x), zip_longest(*seriesList)) resultSeries = TimeSeries(name, start, end, step, product) resultSeries.pathExpression = name return [resultSeries]
python
def multiplySeries(requestContext, *seriesLists): """ Takes two or more series and multiplies their points. A constant may not be used. To multiply by a constant, use the scale() function. Example:: &target=multiplySeries(Series.dividends,Series.divisors) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) if len(seriesList) == 1: return seriesList name = "multiplySeries(%s)" % ','.join([s.name for s in seriesList]) product = map(lambda x: safeMul(*x), zip_longest(*seriesList)) resultSeries = TimeSeries(name, start, end, step, product) resultSeries.pathExpression = name return [resultSeries]
[ "def", "multiplySeries", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "not", "seriesLists", "or", "not", "any", "(", "seriesLists", ")", ":", "return", "[", "]", "seriesList", ",", "start", ",", "end", ",", "step", "=", "normalize", "(", "seriesLists", ")", "if", "len", "(", "seriesList", ")", "==", "1", ":", "return", "seriesList", "name", "=", "\"multiplySeries(%s)\"", "%", "','", ".", "join", "(", "[", "s", ".", "name", "for", "s", "in", "seriesList", "]", ")", "product", "=", "map", "(", "lambda", "x", ":", "safeMul", "(", "*", "x", ")", ",", "zip_longest", "(", "*", "seriesList", ")", ")", "resultSeries", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "product", ")", "resultSeries", ".", "pathExpression", "=", "name", "return", "[", "resultSeries", "]" ]
Takes two or more series and multiplies their points. A constant may not be used. To multiply by a constant, use the scale() function. Example:: &target=multiplySeries(Series.dividends,Series.divisors)
[ "Takes", "two", "or", "more", "series", "and", "multiplies", "their", "points", ".", "A", "constant", "may", "not", "be", "used", ".", "To", "multiply", "by", "a", "constant", "use", "the", "scale", "()", "function", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L748-L770
brutasse/graphite-api
graphite_api/functions.py
weightedAverage
def weightedAverage(requestContext, seriesListAvg, seriesListWeight, *nodes): """ Takes a series of average values and a series of weights and produces a weighted average for all values. The corresponding values should share one or more zero-indexed nodes. Example:: &target=weightedAverage(*.transactions.mean,*.transactions.count,0) &target=weightedAverage(*.transactions.mean,*.transactions.count,1,3,4) """ if isinstance(nodes, int): nodes = [nodes] sortedSeries = {} for seriesAvg, seriesWeight in zip_longest( seriesListAvg, seriesListWeight): key = '' for node in nodes: key += seriesAvg.name.split(".")[node] sortedSeries.setdefault(key, {}) sortedSeries[key]['avg'] = seriesAvg key = '' for node in nodes: key += seriesWeight.name.split(".")[node] sortedSeries.setdefault(key, {}) sortedSeries[key]['weight'] = seriesWeight productList = [] for key in sortedSeries: if 'weight' not in sortedSeries[key]: continue if 'avg' not in sortedSeries[key]: continue seriesWeight = sortedSeries[key]['weight'] seriesAvg = sortedSeries[key]['avg'] productValues = [safeMul(val1, val2) for val1, val2 in zip_longest(seriesAvg, seriesWeight)] name = 'product(%s,%s)' % (seriesWeight.name, seriesAvg.name) productSeries = TimeSeries(name, seriesAvg.start, seriesAvg.end, seriesAvg.step, productValues) productSeries.pathExpression = name productList.append(productSeries) if not productList: return [] [sumProducts] = sumSeries(requestContext, productList) [sumWeights] = sumSeries(requestContext, seriesListWeight) resultValues = [safeDiv(val1, val2) for val1, val2 in zip_longest(sumProducts, sumWeights)] name = "weightedAverage(%s, %s, %s)" % ( ','.join(sorted(set(s.pathExpression for s in seriesListAvg))), ','.join(sorted(set(s.pathExpression for s in seriesListWeight))), ','.join(map(str, nodes))) resultSeries = TimeSeries(name, sumProducts.start, sumProducts.end, sumProducts.step, resultValues) resultSeries.pathExpression = name return resultSeries
python
def weightedAverage(requestContext, seriesListAvg, seriesListWeight, *nodes): """ Takes a series of average values and a series of weights and produces a weighted average for all values. The corresponding values should share one or more zero-indexed nodes. Example:: &target=weightedAverage(*.transactions.mean,*.transactions.count,0) &target=weightedAverage(*.transactions.mean,*.transactions.count,1,3,4) """ if isinstance(nodes, int): nodes = [nodes] sortedSeries = {} for seriesAvg, seriesWeight in zip_longest( seriesListAvg, seriesListWeight): key = '' for node in nodes: key += seriesAvg.name.split(".")[node] sortedSeries.setdefault(key, {}) sortedSeries[key]['avg'] = seriesAvg key = '' for node in nodes: key += seriesWeight.name.split(".")[node] sortedSeries.setdefault(key, {}) sortedSeries[key]['weight'] = seriesWeight productList = [] for key in sortedSeries: if 'weight' not in sortedSeries[key]: continue if 'avg' not in sortedSeries[key]: continue seriesWeight = sortedSeries[key]['weight'] seriesAvg = sortedSeries[key]['avg'] productValues = [safeMul(val1, val2) for val1, val2 in zip_longest(seriesAvg, seriesWeight)] name = 'product(%s,%s)' % (seriesWeight.name, seriesAvg.name) productSeries = TimeSeries(name, seriesAvg.start, seriesAvg.end, seriesAvg.step, productValues) productSeries.pathExpression = name productList.append(productSeries) if not productList: return [] [sumProducts] = sumSeries(requestContext, productList) [sumWeights] = sumSeries(requestContext, seriesListWeight) resultValues = [safeDiv(val1, val2) for val1, val2 in zip_longest(sumProducts, sumWeights)] name = "weightedAverage(%s, %s, %s)" % ( ','.join(sorted(set(s.pathExpression for s in seriesListAvg))), ','.join(sorted(set(s.pathExpression for s in seriesListWeight))), ','.join(map(str, nodes))) resultSeries = TimeSeries(name, sumProducts.start, sumProducts.end, sumProducts.step, resultValues) resultSeries.pathExpression = name return resultSeries
[ "def", "weightedAverage", "(", "requestContext", ",", "seriesListAvg", ",", "seriesListWeight", ",", "*", "nodes", ")", ":", "if", "isinstance", "(", "nodes", ",", "int", ")", ":", "nodes", "=", "[", "nodes", "]", "sortedSeries", "=", "{", "}", "for", "seriesAvg", ",", "seriesWeight", "in", "zip_longest", "(", "seriesListAvg", ",", "seriesListWeight", ")", ":", "key", "=", "''", "for", "node", "in", "nodes", ":", "key", "+=", "seriesAvg", ".", "name", ".", "split", "(", "\".\"", ")", "[", "node", "]", "sortedSeries", ".", "setdefault", "(", "key", ",", "{", "}", ")", "sortedSeries", "[", "key", "]", "[", "'avg'", "]", "=", "seriesAvg", "key", "=", "''", "for", "node", "in", "nodes", ":", "key", "+=", "seriesWeight", ".", "name", ".", "split", "(", "\".\"", ")", "[", "node", "]", "sortedSeries", ".", "setdefault", "(", "key", ",", "{", "}", ")", "sortedSeries", "[", "key", "]", "[", "'weight'", "]", "=", "seriesWeight", "productList", "=", "[", "]", "for", "key", "in", "sortedSeries", ":", "if", "'weight'", "not", "in", "sortedSeries", "[", "key", "]", ":", "continue", "if", "'avg'", "not", "in", "sortedSeries", "[", "key", "]", ":", "continue", "seriesWeight", "=", "sortedSeries", "[", "key", "]", "[", "'weight'", "]", "seriesAvg", "=", "sortedSeries", "[", "key", "]", "[", "'avg'", "]", "productValues", "=", "[", "safeMul", "(", "val1", ",", "val2", ")", "for", "val1", ",", "val2", "in", "zip_longest", "(", "seriesAvg", ",", "seriesWeight", ")", "]", "name", "=", "'product(%s,%s)'", "%", "(", "seriesWeight", ".", "name", ",", "seriesAvg", ".", "name", ")", "productSeries", "=", "TimeSeries", "(", "name", ",", "seriesAvg", ".", "start", ",", "seriesAvg", ".", "end", ",", "seriesAvg", ".", "step", ",", "productValues", ")", "productSeries", ".", "pathExpression", "=", "name", "productList", ".", "append", "(", "productSeries", ")", "if", "not", "productList", ":", "return", "[", "]", "[", "sumProducts", "]", "=", "sumSeries", "(", "requestContext", ",", "productList", ")", "[", "sumWeights", "]", "=", "sumSeries", "(", "requestContext", ",", "seriesListWeight", ")", "resultValues", "=", "[", "safeDiv", "(", "val1", ",", "val2", ")", "for", "val1", ",", "val2", "in", "zip_longest", "(", "sumProducts", ",", "sumWeights", ")", "]", "name", "=", "\"weightedAverage(%s, %s, %s)\"", "%", "(", "','", ".", "join", "(", "sorted", "(", "set", "(", "s", ".", "pathExpression", "for", "s", "in", "seriesListAvg", ")", ")", ")", ",", "','", ".", "join", "(", "sorted", "(", "set", "(", "s", ".", "pathExpression", "for", "s", "in", "seriesListWeight", ")", ")", ")", ",", "','", ".", "join", "(", "map", "(", "str", ",", "nodes", ")", ")", ")", "resultSeries", "=", "TimeSeries", "(", "name", ",", "sumProducts", ".", "start", ",", "sumProducts", ".", "end", ",", "sumProducts", ".", "step", ",", "resultValues", ")", "resultSeries", ".", "pathExpression", "=", "name", "return", "resultSeries" ]
Takes a series of average values and a series of weights and produces a weighted average for all values. The corresponding values should share one or more zero-indexed nodes. Example:: &target=weightedAverage(*.transactions.mean,*.transactions.count,0) &target=weightedAverage(*.transactions.mean,*.transactions.count,1,3,4)
[ "Takes", "a", "series", "of", "average", "values", "and", "a", "series", "of", "weights", "and", "produces", "a", "weighted", "average", "for", "all", "values", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L773-L843
brutasse/graphite-api
graphite_api/functions.py
exponentialMovingAverage
def exponentialMovingAverage(requestContext, seriesList, windowSize): """ Takes a series of values and a window size and produces an exponential moving average utilizing the following formula: ema(current) = constant * (Current Value) + (1 - constant) * ema(previous) The Constant is calculated as: constant = 2 / (windowSize + 1) The first period EMA uses a simple moving average for its value. Example:: &target=exponentialMovingAverage(*.transactions.count, 10) &target=exponentialMovingAverage(*.transactions.count, '-10s') """ # EMA = C * (current_value) + (1 - C) + EMA # C = 2 / (windowSize + 1) # The following was copied from movingAverage, and altered for ema if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) # set previewSeconds and constant based on windowSize string or integer if windowInterval: previewSeconds = windowInterval constant = (float(2) / (int(windowInterval) + 1)) else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) constant = (float(2) / (int(windowSize) + 1)) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'exponentialMovingAverage(%s,"%s")' % ( series.name, windowSize) else: newName = "exponentialMovingAverage(%s,%s)" % ( series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName window_sum = safeSum(series[:windowPoints]) or 0 count = safeLen(series[:windowPoints]) ema = safeDiv(window_sum, count) newSeries.append(ema) if ema is None: ema = 0.0 else: ema = float(ema) for i in range(windowPoints, len(series) - 1): if series[i] is not None: ema = (float(constant) * float(series[i]) + (1 - float(constant)) * float(ema)) newSeries.append(round(ema, 3)) else: newSeries.append(None) result.append(newSeries) return result
python
def exponentialMovingAverage(requestContext, seriesList, windowSize): """ Takes a series of values and a window size and produces an exponential moving average utilizing the following formula: ema(current) = constant * (Current Value) + (1 - constant) * ema(previous) The Constant is calculated as: constant = 2 / (windowSize + 1) The first period EMA uses a simple moving average for its value. Example:: &target=exponentialMovingAverage(*.transactions.count, 10) &target=exponentialMovingAverage(*.transactions.count, '-10s') """ # EMA = C * (current_value) + (1 - C) + EMA # C = 2 / (windowSize + 1) # The following was copied from movingAverage, and altered for ema if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) # set previewSeconds and constant based on windowSize string or integer if windowInterval: previewSeconds = windowInterval constant = (float(2) / (int(windowInterval) + 1)) else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) constant = (float(2) / (int(windowSize) + 1)) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'exponentialMovingAverage(%s,"%s")' % ( series.name, windowSize) else: newName = "exponentialMovingAverage(%s,%s)" % ( series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName window_sum = safeSum(series[:windowPoints]) or 0 count = safeLen(series[:windowPoints]) ema = safeDiv(window_sum, count) newSeries.append(ema) if ema is None: ema = 0.0 else: ema = float(ema) for i in range(windowPoints, len(series) - 1): if series[i] is not None: ema = (float(constant) * float(series[i]) + (1 - float(constant)) * float(ema)) newSeries.append(round(ema, 3)) else: newSeries.append(None) result.append(newSeries) return result
[ "def", "exponentialMovingAverage", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "# EMA = C * (current_value) + (1 - C) + EMA", "# C = 2 / (windowSize + 1)", "# The following was copied from movingAverage, and altered for ema", "if", "not", "seriesList", ":", "return", "[", "]", "windowInterval", "=", "None", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "delta", "=", "parseTimeOffset", "(", "windowSize", ")", "windowInterval", "=", "abs", "(", "delta", ".", "seconds", "+", "(", "delta", ".", "days", "*", "86400", ")", ")", "# set previewSeconds and constant based on windowSize string or integer", "if", "windowInterval", ":", "previewSeconds", "=", "windowInterval", "constant", "=", "(", "float", "(", "2", ")", "/", "(", "int", "(", "windowInterval", ")", "+", "1", ")", ")", "else", ":", "previewSeconds", "=", "max", "(", "[", "s", ".", "step", "for", "s", "in", "seriesList", "]", ")", "*", "int", "(", "windowSize", ")", "constant", "=", "(", "float", "(", "2", ")", "/", "(", "int", "(", "windowSize", ")", "+", "1", ")", ")", "# ignore original data and pull new, including our preview", "# data from earlier is needed to calculate the early results", "newContext", "=", "requestContext", ".", "copy", "(", ")", "newContext", "[", "'startTime'", "]", "=", "(", "requestContext", "[", "'startTime'", "]", "-", "timedelta", "(", "seconds", "=", "previewSeconds", ")", ")", "previewList", "=", "evaluateTokens", "(", "newContext", ",", "requestContext", "[", "'args'", "]", "[", "0", "]", ")", "result", "=", "[", "]", "for", "series", "in", "previewList", ":", "if", "windowInterval", ":", "windowPoints", "=", "windowInterval", "//", "series", ".", "step", "else", ":", "windowPoints", "=", "int", "(", "windowSize", ")", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "newName", "=", "'exponentialMovingAverage(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "windowSize", ")", "else", ":", "newName", "=", "\"exponentialMovingAverage(%s,%s)\"", "%", "(", "series", ".", "name", ",", "windowSize", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", "+", "previewSeconds", ",", "series", ".", "end", ",", "series", ".", "step", ",", "[", "]", ")", "newSeries", ".", "pathExpression", "=", "newName", "window_sum", "=", "safeSum", "(", "series", "[", ":", "windowPoints", "]", ")", "or", "0", "count", "=", "safeLen", "(", "series", "[", ":", "windowPoints", "]", ")", "ema", "=", "safeDiv", "(", "window_sum", ",", "count", ")", "newSeries", ".", "append", "(", "ema", ")", "if", "ema", "is", "None", ":", "ema", "=", "0.0", "else", ":", "ema", "=", "float", "(", "ema", ")", "for", "i", "in", "range", "(", "windowPoints", ",", "len", "(", "series", ")", "-", "1", ")", ":", "if", "series", "[", "i", "]", "is", "not", "None", ":", "ema", "=", "(", "float", "(", "constant", ")", "*", "float", "(", "series", "[", "i", "]", ")", "+", "(", "1", "-", "float", "(", "constant", ")", ")", "*", "float", "(", "ema", ")", ")", "newSeries", ".", "append", "(", "round", "(", "ema", ",", "3", ")", ")", "else", ":", "newSeries", ".", "append", "(", "None", ")", "result", ".", "append", "(", "newSeries", ")", "return", "result" ]
Takes a series of values and a window size and produces an exponential moving average utilizing the following formula: ema(current) = constant * (Current Value) + (1 - constant) * ema(previous) The Constant is calculated as: constant = 2 / (windowSize + 1) The first period EMA uses a simple moving average for its value. Example:: &target=exponentialMovingAverage(*.transactions.count, 10) &target=exponentialMovingAverage(*.transactions.count, '-10s')
[ "Takes", "a", "series", "of", "values", "and", "a", "window", "size", "and", "produces", "an", "exponential", "moving", "average", "utilizing", "the", "following", "formula", ":" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L846-L928
brutasse/graphite-api
graphite_api/functions.py
movingMedian
def movingMedian(requestContext, seriesList, windowSize): """ Graphs the moving median of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the median of the preceding datapoints for each point on the graph. Example:: &target=movingMedian(Server.instance01.threads.busy,10) &target=movingMedian(Server.instance*.threads.idle,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = to_seconds(delta) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingMedian(%s,"%s")' % (series.name, windowSize) else: newName = "movingMedian(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName for i in range(windowPoints, len(series)): window = series[i - windowPoints:i] nonNull = [v for v in window if v is not None] if nonNull: m_index = len(nonNull) // 2 newSeries.append(sorted(nonNull)[m_index]) else: newSeries.append(None) result.append(newSeries) return result
python
def movingMedian(requestContext, seriesList, windowSize): """ Graphs the moving median of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the median of the preceding datapoints for each point on the graph. Example:: &target=movingMedian(Server.instance01.threads.busy,10) &target=movingMedian(Server.instance*.threads.idle,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = to_seconds(delta) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingMedian(%s,"%s")' % (series.name, windowSize) else: newName = "movingMedian(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName for i in range(windowPoints, len(series)): window = series[i - windowPoints:i] nonNull = [v for v in window if v is not None] if nonNull: m_index = len(nonNull) // 2 newSeries.append(sorted(nonNull)[m_index]) else: newSeries.append(None) result.append(newSeries) return result
[ "def", "movingMedian", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "if", "not", "seriesList", ":", "return", "[", "]", "windowInterval", "=", "None", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "delta", "=", "parseTimeOffset", "(", "windowSize", ")", "windowInterval", "=", "to_seconds", "(", "delta", ")", "if", "windowInterval", ":", "previewSeconds", "=", "windowInterval", "else", ":", "previewSeconds", "=", "max", "(", "[", "s", ".", "step", "for", "s", "in", "seriesList", "]", ")", "*", "int", "(", "windowSize", ")", "# ignore original data and pull new, including our preview", "# data from earlier is needed to calculate the early results", "newContext", "=", "requestContext", ".", "copy", "(", ")", "newContext", "[", "'startTime'", "]", "=", "(", "requestContext", "[", "'startTime'", "]", "-", "timedelta", "(", "seconds", "=", "previewSeconds", ")", ")", "previewList", "=", "evaluateTokens", "(", "newContext", ",", "requestContext", "[", "'args'", "]", "[", "0", "]", ")", "result", "=", "[", "]", "for", "series", "in", "previewList", ":", "if", "windowInterval", ":", "windowPoints", "=", "windowInterval", "//", "series", ".", "step", "else", ":", "windowPoints", "=", "int", "(", "windowSize", ")", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "newName", "=", "'movingMedian(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "windowSize", ")", "else", ":", "newName", "=", "\"movingMedian(%s,%s)\"", "%", "(", "series", ".", "name", ",", "windowSize", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", "+", "previewSeconds", ",", "series", ".", "end", ",", "series", ".", "step", ",", "[", "]", ")", "newSeries", ".", "pathExpression", "=", "newName", "for", "i", "in", "range", "(", "windowPoints", ",", "len", "(", "series", ")", ")", ":", "window", "=", "series", "[", "i", "-", "windowPoints", ":", "i", "]", "nonNull", "=", "[", "v", "for", "v", "in", "window", "if", "v", "is", "not", "None", "]", "if", "nonNull", ":", "m_index", "=", "len", "(", "nonNull", ")", "//", "2", "newSeries", ".", "append", "(", "sorted", "(", "nonNull", ")", "[", "m_index", "]", ")", "else", ":", "newSeries", ".", "append", "(", "None", ")", "result", ".", "append", "(", "newSeries", ")", "return", "result" ]
Graphs the moving median of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the median of the preceding datapoints for each point on the graph. Example:: &target=movingMedian(Server.instance01.threads.busy,10) &target=movingMedian(Server.instance*.threads.idle,'5min')
[ "Graphs", "the", "moving", "median", "of", "a", "metric", "(", "or", "metrics", ")", "over", "a", "fixed", "number", "of", "past", "points", "or", "a", "time", "interval", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L931-L991
brutasse/graphite-api
graphite_api/functions.py
scale
def scale(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint by the constant provided at each point. Example:: &target=scale(Server.instance01.threads.busy,10) &target=scale(Server.instance*.threads.busy,10) """ for series in seriesList: series.name = "scale(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safeMul(value, factor) return seriesList
python
def scale(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint by the constant provided at each point. Example:: &target=scale(Server.instance01.threads.busy,10) &target=scale(Server.instance*.threads.busy,10) """ for series in seriesList: series.name = "scale(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safeMul(value, factor) return seriesList
[ "def", "scale", "(", "requestContext", ",", "seriesList", ",", "factor", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"scale(%s,%g)\"", "%", "(", "series", ".", "name", ",", "float", "(", "factor", ")", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safeMul", "(", "value", ",", "factor", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint by the constant provided at each point. Example:: &target=scale(Server.instance01.threads.busy,10) &target=scale(Server.instance*.threads.busy,10)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "a", "constant", "and", "multiplies", "the", "datapoint", "by", "the", "constant", "provided", "at", "each", "point", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L994-L1010
brutasse/graphite-api
graphite_api/functions.py
scaleToSeconds
def scaleToSeconds(requestContext, seriesList, seconds): """ Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolution for arbitrary retentions """ for series in seriesList: series.name = "scaleToSeconds(%s,%d)" % (series.name, seconds) series.pathExpression = series.name factor = seconds * 1.0 / series.step for i, value in enumerate(series): series[i] = safeMul(value, factor) return seriesList
python
def scaleToSeconds(requestContext, seriesList, seconds): """ Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolution for arbitrary retentions """ for series in seriesList: series.name = "scaleToSeconds(%s,%d)" % (series.name, seconds) series.pathExpression = series.name factor = seconds * 1.0 / series.step for i, value in enumerate(series): series[i] = safeMul(value, factor) return seriesList
[ "def", "scaleToSeconds", "(", "requestContext", ",", "seriesList", ",", "seconds", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"scaleToSeconds(%s,%d)\"", "%", "(", "series", ".", "name", ",", "seconds", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "factor", "=", "seconds", "*", "1.0", "/", "series", ".", "step", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safeMul", "(", "value", ",", "factor", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolution for arbitrary retentions
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "returns", "value", "per", "seconds", "where", "seconds", "is", "a", "last", "argument", "to", "this", "functions", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1013-L1028
brutasse/graphite-api
graphite_api/functions.py
pow
def pow(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint by the power of the constant provided at each point. Example:: &target=pow(Server.instance01.threads.busy,10) &target=pow(Server.instance*.threads.busy,10) """ for series in seriesList: series.name = "pow(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safePow(value, factor) return seriesList
python
def pow(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint by the power of the constant provided at each point. Example:: &target=pow(Server.instance01.threads.busy,10) &target=pow(Server.instance*.threads.busy,10) """ for series in seriesList: series.name = "pow(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safePow(value, factor) return seriesList
[ "def", "pow", "(", "requestContext", ",", "seriesList", ",", "factor", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"pow(%s,%g)\"", "%", "(", "series", ".", "name", ",", "float", "(", "factor", ")", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safePow", "(", "value", ",", "factor", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint by the power of the constant provided at each point. Example:: &target=pow(Server.instance01.threads.busy,10) &target=pow(Server.instance*.threads.busy,10)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "a", "constant", "and", "raises", "the", "datapoint", "by", "the", "power", "of", "the", "constant", "provided", "at", "each", "point", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1031-L1047
brutasse/graphite-api
graphite_api/functions.py
powSeries
def powSeries(requestContext, *seriesLists): """ Takes two or more series and pows their points. A constant line may be used. Example:: &target=powSeries(Server.instance01.app.requests, Server.instance01.app.replies) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "powSeries(%s)" % ','.join([s.name for s in seriesList]) values = [] for row in zip_longest(*seriesList): first = True tmpVal = None for element in row: # If it is a first iteration - tmpVal needs to be element if first: tmpVal = element first = False else: tmpVal = safePow(tmpVal, element) values.append(tmpVal) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
python
def powSeries(requestContext, *seriesLists): """ Takes two or more series and pows their points. A constant line may be used. Example:: &target=powSeries(Server.instance01.app.requests, Server.instance01.app.replies) """ if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) name = "powSeries(%s)" % ','.join([s.name for s in seriesList]) values = [] for row in zip_longest(*seriesList): first = True tmpVal = None for element in row: # If it is a first iteration - tmpVal needs to be element if first: tmpVal = element first = False else: tmpVal = safePow(tmpVal, element) values.append(tmpVal) series = TimeSeries(name, start, end, step, values) series.pathExpression = name return [series]
[ "def", "powSeries", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "not", "seriesLists", "or", "not", "any", "(", "seriesLists", ")", ":", "return", "[", "]", "seriesList", ",", "start", ",", "end", ",", "step", "=", "normalize", "(", "seriesLists", ")", "name", "=", "\"powSeries(%s)\"", "%", "','", ".", "join", "(", "[", "s", ".", "name", "for", "s", "in", "seriesList", "]", ")", "values", "=", "[", "]", "for", "row", "in", "zip_longest", "(", "*", "seriesList", ")", ":", "first", "=", "True", "tmpVal", "=", "None", "for", "element", "in", "row", ":", "# If it is a first iteration - tmpVal needs to be element", "if", "first", ":", "tmpVal", "=", "element", "first", "=", "False", "else", ":", "tmpVal", "=", "safePow", "(", "tmpVal", ",", "element", ")", "values", ".", "append", "(", "tmpVal", ")", "series", "=", "TimeSeries", "(", "name", ",", "start", ",", "end", ",", "step", ",", "values", ")", "series", ".", "pathExpression", "=", "name", "return", "[", "series", "]" ]
Takes two or more series and pows their points. A constant line may be used. Example:: &target=powSeries(Server.instance01.app.requests, Server.instance01.app.replies)
[ "Takes", "two", "or", "more", "series", "and", "pows", "their", "points", ".", "A", "constant", "line", "may", "be", "used", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1050-L1079
brutasse/graphite-api
graphite_api/functions.py
squareRoot
def squareRoot(requestContext, seriesList): """ Takes one metric or a wildcard seriesList, and computes the square root of each datapoint. Example:: &target=squareRoot(Server.instance01.threads.busy) """ for series in seriesList: series.name = "squareRoot(%s)" % (series.name) for i, value in enumerate(series): series[i] = safePow(value, 0.5) return seriesList
python
def squareRoot(requestContext, seriesList): """ Takes one metric or a wildcard seriesList, and computes the square root of each datapoint. Example:: &target=squareRoot(Server.instance01.threads.busy) """ for series in seriesList: series.name = "squareRoot(%s)" % (series.name) for i, value in enumerate(series): series[i] = safePow(value, 0.5) return seriesList
[ "def", "squareRoot", "(", "requestContext", ",", "seriesList", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"squareRoot(%s)\"", "%", "(", "series", ".", "name", ")", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safePow", "(", "value", ",", "0.5", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList, and computes the square root of each datapoint. Example:: &target=squareRoot(Server.instance01.threads.busy)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "computes", "the", "square", "root", "of", "each", "datapoint", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1082-L1096
brutasse/graphite-api
graphite_api/functions.py
absolute
def absolute(requestContext, seriesList): """ Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.threads.busy) """ for series in seriesList: series.name = "absolute(%s)" % (series.name) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safeAbs(value) return seriesList
python
def absolute(requestContext, seriesList): """ Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.threads.busy) """ for series in seriesList: series.name = "absolute(%s)" % (series.name) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safeAbs(value) return seriesList
[ "def", "absolute", "(", "requestContext", ",", "seriesList", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"absolute(%s)\"", "%", "(", "series", ".", "name", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safeAbs", "(", "value", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.threads.busy)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "applies", "the", "mathematical", "abs", "function", "to", "each", "datapoint", "transforming", "it", "to", "its", "absolute", "value", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1116-L1131
brutasse/graphite-api
graphite_api/functions.py
offset
def offset(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to each datapoint. Example:: &target=offset(Server.instance01.threads.busy,10) """ for series in seriesList: series.name = "offset(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): if value is not None: series[i] = value + factor return seriesList
python
def offset(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to each datapoint. Example:: &target=offset(Server.instance01.threads.busy,10) """ for series in seriesList: series.name = "offset(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): if value is not None: series[i] = value + factor return seriesList
[ "def", "offset", "(", "requestContext", ",", "seriesList", ",", "factor", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"offset(%s,%g)\"", "%", "(", "series", ".", "name", ",", "float", "(", "factor", ")", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "if", "value", "is", "not", "None", ":", "series", "[", "i", "]", "=", "value", "+", "factor", "return", "seriesList" ]
Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to each datapoint. Example:: &target=offset(Server.instance01.threads.busy,10)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "a", "constant", "and", "adds", "the", "constant", "to", "each", "datapoint", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1134-L1150
brutasse/graphite-api
graphite_api/functions.py
offsetToZero
def offsetToZero(requestContext, seriesList): """ Offsets a metric or wildcard seriesList by subtracting the minimum value in the series from each datapoint. Useful to compare different series where the values in each series may be higher or lower on average but you're only interested in the relative difference. An example use case is for comparing different round trip time results. When measuring RTT (like pinging a server), different devices may come back with consistently different results due to network latency which will be different depending on how many network hops between the probe and the device. To compare different devices in the same graph, the network latency to each has to be factored out of the results. This is a shortcut that takes the fastest response (lowest number in the series) and sets that to zero and then offsets all of the other datapoints in that series by that amount. This makes the assumption that the lowest response is the fastest the device can respond, of course the more datapoints that are in the series the more accurate this assumption is. Example:: &target=offsetToZero(Server.instance01.responseTime) &target=offsetToZero(Server.instance*.responseTime) """ for series in seriesList: series.name = "offsetToZero(%s)" % (series.name) minimum = safeMin(series) for i, value in enumerate(series): if value is not None: series[i] = value - minimum return seriesList
python
def offsetToZero(requestContext, seriesList): """ Offsets a metric or wildcard seriesList by subtracting the minimum value in the series from each datapoint. Useful to compare different series where the values in each series may be higher or lower on average but you're only interested in the relative difference. An example use case is for comparing different round trip time results. When measuring RTT (like pinging a server), different devices may come back with consistently different results due to network latency which will be different depending on how many network hops between the probe and the device. To compare different devices in the same graph, the network latency to each has to be factored out of the results. This is a shortcut that takes the fastest response (lowest number in the series) and sets that to zero and then offsets all of the other datapoints in that series by that amount. This makes the assumption that the lowest response is the fastest the device can respond, of course the more datapoints that are in the series the more accurate this assumption is. Example:: &target=offsetToZero(Server.instance01.responseTime) &target=offsetToZero(Server.instance*.responseTime) """ for series in seriesList: series.name = "offsetToZero(%s)" % (series.name) minimum = safeMin(series) for i, value in enumerate(series): if value is not None: series[i] = value - minimum return seriesList
[ "def", "offsetToZero", "(", "requestContext", ",", "seriesList", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"offsetToZero(%s)\"", "%", "(", "series", ".", "name", ")", "minimum", "=", "safeMin", "(", "series", ")", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "if", "value", "is", "not", "None", ":", "series", "[", "i", "]", "=", "value", "-", "minimum", "return", "seriesList" ]
Offsets a metric or wildcard seriesList by subtracting the minimum value in the series from each datapoint. Useful to compare different series where the values in each series may be higher or lower on average but you're only interested in the relative difference. An example use case is for comparing different round trip time results. When measuring RTT (like pinging a server), different devices may come back with consistently different results due to network latency which will be different depending on how many network hops between the probe and the device. To compare different devices in the same graph, the network latency to each has to be factored out of the results. This is a shortcut that takes the fastest response (lowest number in the series) and sets that to zero and then offsets all of the other datapoints in that series by that amount. This makes the assumption that the lowest response is the fastest the device can respond, of course the more datapoints that are in the series the more accurate this assumption is. Example:: &target=offsetToZero(Server.instance01.responseTime) &target=offsetToZero(Server.instance*.responseTime)
[ "Offsets", "a", "metric", "or", "wildcard", "seriesList", "by", "subtracting", "the", "minimum", "value", "in", "the", "series", "from", "each", "datapoint", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1153-L1187
brutasse/graphite-api
graphite_api/functions.py
movingAverage
def movingAverage(requestContext, seriesList, windowSize): """ Graphs the moving average of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the average of the preceding datapoints for each point on the graph. Example:: &target=movingAverage(Server.instance01.threads.busy,10) &target=movingAverage(Server.instance*.threads.idle,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = to_seconds(delta) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingAverage(%s,"%s")' % (series.name, windowSize) else: newName = "movingAverage(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName windowSum = safeSum(series[:windowPoints]) or 0 count = safeLen(series[:windowPoints]) newSeries.append(safeDiv(windowSum, count)) for n, last in enumerate(series[windowPoints:-1]): if series[n] is not None: windowSum -= series[n] count -= 1 if last is not None: windowSum += last count += 1 newSeries.append(safeDiv(windowSum, count)) result.append(newSeries) return result
python
def movingAverage(requestContext, seriesList, windowSize): """ Graphs the moving average of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the average of the preceding datapoints for each point on the graph. Example:: &target=movingAverage(Server.instance01.threads.busy,10) &target=movingAverage(Server.instance*.threads.idle,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = to_seconds(delta) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingAverage(%s,"%s")' % (series.name, windowSize) else: newName = "movingAverage(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName windowSum = safeSum(series[:windowPoints]) or 0 count = safeLen(series[:windowPoints]) newSeries.append(safeDiv(windowSum, count)) for n, last in enumerate(series[windowPoints:-1]): if series[n] is not None: windowSum -= series[n] count -= 1 if last is not None: windowSum += last count += 1 newSeries.append(safeDiv(windowSum, count)) result.append(newSeries) return result
[ "def", "movingAverage", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "if", "not", "seriesList", ":", "return", "[", "]", "windowInterval", "=", "None", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "delta", "=", "parseTimeOffset", "(", "windowSize", ")", "windowInterval", "=", "to_seconds", "(", "delta", ")", "if", "windowInterval", ":", "previewSeconds", "=", "windowInterval", "else", ":", "previewSeconds", "=", "max", "(", "[", "s", ".", "step", "for", "s", "in", "seriesList", "]", ")", "*", "int", "(", "windowSize", ")", "# ignore original data and pull new, including our preview", "# data from earlier is needed to calculate the early results", "newContext", "=", "requestContext", ".", "copy", "(", ")", "newContext", "[", "'startTime'", "]", "=", "(", "requestContext", "[", "'startTime'", "]", "-", "timedelta", "(", "seconds", "=", "previewSeconds", ")", ")", "previewList", "=", "evaluateTokens", "(", "newContext", ",", "requestContext", "[", "'args'", "]", "[", "0", "]", ")", "result", "=", "[", "]", "for", "series", "in", "previewList", ":", "if", "windowInterval", ":", "windowPoints", "=", "windowInterval", "//", "series", ".", "step", "else", ":", "windowPoints", "=", "int", "(", "windowSize", ")", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "newName", "=", "'movingAverage(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "windowSize", ")", "else", ":", "newName", "=", "\"movingAverage(%s,%s)\"", "%", "(", "series", ".", "name", ",", "windowSize", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", "+", "previewSeconds", ",", "series", ".", "end", ",", "series", ".", "step", ",", "[", "]", ")", "newSeries", ".", "pathExpression", "=", "newName", "windowSum", "=", "safeSum", "(", "series", "[", ":", "windowPoints", "]", ")", "or", "0", "count", "=", "safeLen", "(", "series", "[", ":", "windowPoints", "]", ")", "newSeries", ".", "append", "(", "safeDiv", "(", "windowSum", ",", "count", ")", ")", "for", "n", ",", "last", "in", "enumerate", "(", "series", "[", "windowPoints", ":", "-", "1", "]", ")", ":", "if", "series", "[", "n", "]", "is", "not", "None", ":", "windowSum", "-=", "series", "[", "n", "]", "count", "-=", "1", "if", "last", "is", "not", "None", ":", "windowSum", "+=", "last", "count", "+=", "1", "newSeries", ".", "append", "(", "safeDiv", "(", "windowSum", ",", "count", ")", ")", "result", ".", "append", "(", "newSeries", ")", "return", "result" ]
Graphs the moving average of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the average of the preceding datapoints for each point on the graph. Example:: &target=movingAverage(Server.instance01.threads.busy,10) &target=movingAverage(Server.instance*.threads.idle,'5min')
[ "Graphs", "the", "moving", "average", "of", "a", "metric", "(", "or", "metrics", ")", "over", "a", "fixed", "number", "of", "past", "points", "or", "a", "time", "interval", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1190-L1254
brutasse/graphite-api
graphite_api/functions.py
movingSum
def movingSum(requestContext, seriesList, windowSize): """ Graphs the moving sum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the sum of the preceeding datapoints for each point on the graph. Example:: &target=movingSum(Server.instance01.requests,10) &target=movingSum(Server.instance*.errors,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingSum(%s,"%s")' % (series.name, windowSize) else: newName = "movingSum(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName window_sum = safeSum(series[:windowPoints]) newSeries.append(window_sum) for n, last in enumerate(series[windowPoints:-1]): if series[n] is not None: window_sum -= series[n] if last is not None: window_sum = (window_sum or 0) + last newSeries.append(window_sum) result.append(newSeries) return result
python
def movingSum(requestContext, seriesList, windowSize): """ Graphs the moving sum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the sum of the preceeding datapoints for each point on the graph. Example:: &target=movingSum(Server.instance01.requests,10) &target=movingSum(Server.instance*.errors,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingSum(%s,"%s")' % (series.name, windowSize) else: newName = "movingSum(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName window_sum = safeSum(series[:windowPoints]) newSeries.append(window_sum) for n, last in enumerate(series[windowPoints:-1]): if series[n] is not None: window_sum -= series[n] if last is not None: window_sum = (window_sum or 0) + last newSeries.append(window_sum) result.append(newSeries) return result
[ "def", "movingSum", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "if", "not", "seriesList", ":", "return", "[", "]", "windowInterval", "=", "None", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "delta", "=", "parseTimeOffset", "(", "windowSize", ")", "windowInterval", "=", "abs", "(", "delta", ".", "seconds", "+", "(", "delta", ".", "days", "*", "86400", ")", ")", "if", "windowInterval", ":", "previewSeconds", "=", "windowInterval", "else", ":", "previewSeconds", "=", "max", "(", "[", "s", ".", "step", "for", "s", "in", "seriesList", "]", ")", "*", "int", "(", "windowSize", ")", "# ignore original data and pull new, including our preview", "# data from earlier is needed to calculate the early results", "newContext", "=", "requestContext", ".", "copy", "(", ")", "newContext", "[", "'startTime'", "]", "=", "(", "requestContext", "[", "'startTime'", "]", "-", "timedelta", "(", "seconds", "=", "previewSeconds", ")", ")", "previewList", "=", "evaluateTokens", "(", "newContext", ",", "requestContext", "[", "'args'", "]", "[", "0", "]", ")", "result", "=", "[", "]", "for", "series", "in", "previewList", ":", "if", "windowInterval", ":", "windowPoints", "=", "windowInterval", "//", "series", ".", "step", "else", ":", "windowPoints", "=", "int", "(", "windowSize", ")", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "newName", "=", "'movingSum(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "windowSize", ")", "else", ":", "newName", "=", "\"movingSum(%s,%s)\"", "%", "(", "series", ".", "name", ",", "windowSize", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", "+", "previewSeconds", ",", "series", ".", "end", ",", "series", ".", "step", ",", "[", "]", ")", "newSeries", ".", "pathExpression", "=", "newName", "window_sum", "=", "safeSum", "(", "series", "[", ":", "windowPoints", "]", ")", "newSeries", ".", "append", "(", "window_sum", ")", "for", "n", ",", "last", "in", "enumerate", "(", "series", "[", "windowPoints", ":", "-", "1", "]", ")", ":", "if", "series", "[", "n", "]", "is", "not", "None", ":", "window_sum", "-=", "series", "[", "n", "]", "if", "last", "is", "not", "None", ":", "window_sum", "=", "(", "window_sum", "or", "0", ")", "+", "last", "newSeries", ".", "append", "(", "window_sum", ")", "result", ".", "append", "(", "newSeries", ")", "return", "result" ]
Graphs the moving sum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the sum of the preceeding datapoints for each point on the graph. Example:: &target=movingSum(Server.instance01.requests,10) &target=movingSum(Server.instance*.errors,'5min')
[ "Graphs", "the", "moving", "sum", "of", "a", "metric", "(", "or", "metrics", ")", "over", "a", "fixed", "number", "of", "past", "points", "or", "a", "time", "interval", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1257-L1319
brutasse/graphite-api
graphite_api/functions.py
movingMax
def movingMax(requestContext, seriesList, windowSize): """ Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the maximum of the preceeding datapoints for each point on the graph. Example:: &target=movingMax(Server.instance01.requests,10) &target=movingMax(Server.instance*.errors,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingMax(%s,"%s")' % (series.name, windowSize) else: newName = "movingMax(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName for i in range(windowPoints, len(series)): window = series[i - windowPoints:i] newSeries.append(safeMax(window)) result.append(newSeries) return result
python
def movingMax(requestContext, seriesList, windowSize): """ Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the maximum of the preceeding datapoints for each point on the graph. Example:: &target=movingMax(Server.instance01.requests,10) &target=movingMax(Server.instance*.errors,'5min') """ if not seriesList: return [] windowInterval = None if isinstance(windowSize, six.string_types): delta = parseTimeOffset(windowSize) windowInterval = abs(delta.seconds + (delta.days * 86400)) if windowInterval: previewSeconds = windowInterval else: previewSeconds = max([s.step for s in seriesList]) * int(windowSize) # ignore original data and pull new, including our preview # data from earlier is needed to calculate the early results newContext = requestContext.copy() newContext['startTime'] = (requestContext['startTime'] - timedelta(seconds=previewSeconds)) previewList = evaluateTokens(newContext, requestContext['args'][0]) result = [] for series in previewList: if windowInterval: windowPoints = windowInterval // series.step else: windowPoints = int(windowSize) if isinstance(windowSize, six.string_types): newName = 'movingMax(%s,"%s")' % (series.name, windowSize) else: newName = "movingMax(%s,%s)" % (series.name, windowSize) newSeries = TimeSeries(newName, series.start + previewSeconds, series.end, series.step, []) newSeries.pathExpression = newName for i in range(windowPoints, len(series)): window = series[i - windowPoints:i] newSeries.append(safeMax(window)) result.append(newSeries) return result
[ "def", "movingMax", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "if", "not", "seriesList", ":", "return", "[", "]", "windowInterval", "=", "None", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "delta", "=", "parseTimeOffset", "(", "windowSize", ")", "windowInterval", "=", "abs", "(", "delta", ".", "seconds", "+", "(", "delta", ".", "days", "*", "86400", ")", ")", "if", "windowInterval", ":", "previewSeconds", "=", "windowInterval", "else", ":", "previewSeconds", "=", "max", "(", "[", "s", ".", "step", "for", "s", "in", "seriesList", "]", ")", "*", "int", "(", "windowSize", ")", "# ignore original data and pull new, including our preview", "# data from earlier is needed to calculate the early results", "newContext", "=", "requestContext", ".", "copy", "(", ")", "newContext", "[", "'startTime'", "]", "=", "(", "requestContext", "[", "'startTime'", "]", "-", "timedelta", "(", "seconds", "=", "previewSeconds", ")", ")", "previewList", "=", "evaluateTokens", "(", "newContext", ",", "requestContext", "[", "'args'", "]", "[", "0", "]", ")", "result", "=", "[", "]", "for", "series", "in", "previewList", ":", "if", "windowInterval", ":", "windowPoints", "=", "windowInterval", "//", "series", ".", "step", "else", ":", "windowPoints", "=", "int", "(", "windowSize", ")", "if", "isinstance", "(", "windowSize", ",", "six", ".", "string_types", ")", ":", "newName", "=", "'movingMax(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "windowSize", ")", "else", ":", "newName", "=", "\"movingMax(%s,%s)\"", "%", "(", "series", ".", "name", ",", "windowSize", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", "+", "previewSeconds", ",", "series", ".", "end", ",", "series", ".", "step", ",", "[", "]", ")", "newSeries", ".", "pathExpression", "=", "newName", "for", "i", "in", "range", "(", "windowPoints", ",", "len", "(", "series", ")", ")", ":", "window", "=", "series", "[", "i", "-", "windowPoints", ":", "i", "]", "newSeries", ".", "append", "(", "safeMax", "(", "window", ")", ")", "result", ".", "append", "(", "newSeries", ")", "return", "result" ]
Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for examples of time formats). Graphs the maximum of the preceeding datapoints for each point on the graph. Example:: &target=movingMax(Server.instance01.requests,10) &target=movingMax(Server.instance*.errors,'5min')
[ "Graphs", "the", "moving", "maximum", "of", "a", "metric", "(", "or", "metrics", ")", "over", "a", "fixed", "number", "of", "past", "points", "or", "a", "time", "interval", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1382-L1439
brutasse/graphite-api
graphite_api/functions.py
consolidateBy
def consolidateBy(requestContext, seriesList, consolidationFunc): """ Takes one metric or a wildcard seriesList and a consolidation function name. Valid function names are 'sum', 'average', 'min', and 'max'. When a graph is drawn where width of the graph size in pixels is smaller than the number of datapoints to be graphed, Graphite consolidates the values to to prevent line overlap. The consolidateBy() function changes the consolidation function from the default of 'average' to one of 'sum', 'max', or 'min'. This is especially useful in sales graphs, where fractional values make no sense and a 'sum' of consolidated values is appropriate. Example:: &target=consolidateBy(Sales.widgets.largeBlue, 'sum') &target=consolidateBy(Servers.web01.sda1.free_space, 'max') """ for series in seriesList: # datalib will throw an exception, so it's not necessary to validate # here series.consolidationFunc = consolidationFunc series.name = 'consolidateBy(%s,"%s")' % (series.name, series.consolidationFunc) series.pathExpression = series.name return seriesList
python
def consolidateBy(requestContext, seriesList, consolidationFunc): """ Takes one metric or a wildcard seriesList and a consolidation function name. Valid function names are 'sum', 'average', 'min', and 'max'. When a graph is drawn where width of the graph size in pixels is smaller than the number of datapoints to be graphed, Graphite consolidates the values to to prevent line overlap. The consolidateBy() function changes the consolidation function from the default of 'average' to one of 'sum', 'max', or 'min'. This is especially useful in sales graphs, where fractional values make no sense and a 'sum' of consolidated values is appropriate. Example:: &target=consolidateBy(Sales.widgets.largeBlue, 'sum') &target=consolidateBy(Servers.web01.sda1.free_space, 'max') """ for series in seriesList: # datalib will throw an exception, so it's not necessary to validate # here series.consolidationFunc = consolidationFunc series.name = 'consolidateBy(%s,"%s")' % (series.name, series.consolidationFunc) series.pathExpression = series.name return seriesList
[ "def", "consolidateBy", "(", "requestContext", ",", "seriesList", ",", "consolidationFunc", ")", ":", "for", "series", "in", "seriesList", ":", "# datalib will throw an exception, so it's not necessary to validate", "# here", "series", ".", "consolidationFunc", "=", "consolidationFunc", "series", ".", "name", "=", "'consolidateBy(%s,\"%s\")'", "%", "(", "series", ".", "name", ",", "series", ".", "consolidationFunc", ")", "series", ".", "pathExpression", "=", "series", ".", "name", "return", "seriesList" ]
Takes one metric or a wildcard seriesList and a consolidation function name. Valid function names are 'sum', 'average', 'min', and 'max'. When a graph is drawn where width of the graph size in pixels is smaller than the number of datapoints to be graphed, Graphite consolidates the values to to prevent line overlap. The consolidateBy() function changes the consolidation function from the default of 'average' to one of 'sum', 'max', or 'min'. This is especially useful in sales graphs, where fractional values make no sense and a 'sum' of consolidated values is appropriate. Example:: &target=consolidateBy(Sales.widgets.largeBlue, 'sum') &target=consolidateBy(Servers.web01.sda1.free_space, 'max')
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "a", "consolidation", "function", "name", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1464-L1492
brutasse/graphite-api
graphite_api/functions.py
delay
def delay(requestContext, seriesList, steps): """ This shifts all samples later by an integer number of steps. This can be used for custom derivative calculations, among other things. Note: this will pad the early end of the data with None for every step shifted. This complements other time-displacement functions such as timeShift and timeSlice, in that this function is indifferent about the step intervals being shifted. Example:: &target=divideSeries(server.FreeSpace,delay(server.FreeSpace,1)) This computes the change in server free space as a percentage of the previous free space. """ results = [] for series in seriesList: newValues = [] prev = [] for val in series: if len(prev) < steps: newValues.append(None) prev.append(val) continue newValues.append(prev.pop(0)) prev.append(val) newName = "delay(%s,%d)" % (series.name, steps) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def delay(requestContext, seriesList, steps): """ This shifts all samples later by an integer number of steps. This can be used for custom derivative calculations, among other things. Note: this will pad the early end of the data with None for every step shifted. This complements other time-displacement functions such as timeShift and timeSlice, in that this function is indifferent about the step intervals being shifted. Example:: &target=divideSeries(server.FreeSpace,delay(server.FreeSpace,1)) This computes the change in server free space as a percentage of the previous free space. """ results = [] for series in seriesList: newValues = [] prev = [] for val in series: if len(prev) < steps: newValues.append(None) prev.append(val) continue newValues.append(prev.pop(0)) prev.append(val) newName = "delay(%s,%d)" % (series.name, steps) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
[ "def", "delay", "(", "requestContext", ",", "seriesList", ",", "steps", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "newValues", "=", "[", "]", "prev", "=", "[", "]", "for", "val", "in", "series", ":", "if", "len", "(", "prev", ")", "<", "steps", ":", "newValues", ".", "append", "(", "None", ")", "prev", ".", "append", "(", "val", ")", "continue", "newValues", ".", "append", "(", "prev", ".", "pop", "(", "0", ")", ")", "prev", ".", "append", "(", "val", ")", "newName", "=", "\"delay(%s,%d)\"", "%", "(", "series", ".", "name", ",", "steps", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "return", "results" ]
This shifts all samples later by an integer number of steps. This can be used for custom derivative calculations, among other things. Note: this will pad the early end of the data with None for every step shifted. This complements other time-displacement functions such as timeShift and timeSlice, in that this function is indifferent about the step intervals being shifted. Example:: &target=divideSeries(server.FreeSpace,delay(server.FreeSpace,1)) This computes the change in server free space as a percentage of the previous free space.
[ "This", "shifts", "all", "samples", "later", "by", "an", "integer", "number", "of", "steps", ".", "This", "can", "be", "used", "for", "custom", "derivative", "calculations", "among", "other", "things", ".", "Note", ":", "this", "will", "pad", "the", "early", "end", "of", "the", "data", "with", "None", "for", "every", "step", "shifted", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1581-L1614
brutasse/graphite-api
graphite_api/functions.py
integral
def integral(requestContext, seriesList): """ This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on the left side of the graph, adding the sales each minute, and show the total sales for the time period selected at the right side, (time now, or the time specified by '&until='). """ results = [] for series in seriesList: newValues = [] current = 0.0 for val in series: if val is None: newValues.append(None) else: current += val newValues.append(current) newName = "integral(%s)" % series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def integral(requestContext, seriesList): """ This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on the left side of the graph, adding the sales each minute, and show the total sales for the time period selected at the right side, (time now, or the time specified by '&until='). """ results = [] for series in seriesList: newValues = [] current = 0.0 for val in series: if val is None: newValues.append(None) else: current += val newValues.append(current) newName = "integral(%s)" % series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
[ "def", "integral", "(", "requestContext", ",", "seriesList", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "newValues", "=", "[", "]", "current", "=", "0.0", "for", "val", "in", "series", ":", "if", "val", "is", "None", ":", "newValues", ".", "append", "(", "None", ")", "else", ":", "current", "+=", "val", "newValues", ".", "append", "(", "current", ")", "newName", "=", "\"integral(%s)\"", "%", "series", ".", "name", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "return", "results" ]
This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on the left side of the graph, adding the sales each minute, and show the total sales for the time period selected at the right side, (time now, or the time specified by '&until=').
[ "This", "will", "show", "the", "sum", "over", "time", "sort", "of", "like", "a", "continuous", "addition", "function", ".", "Useful", "for", "finding", "totals", "or", "trends", "in", "metrics", "that", "are", "collected", "per", "minute", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1617-L1646
brutasse/graphite-api
graphite_api/functions.py
integralByInterval
def integralByInterval(requestContext, seriesList, intervalUnit): """ This will do the same as integral() funcion, except resetting the total to 0 at the given time in the parameter "from" Useful for finding totals per hour/day/week/.. Example:: &target=integralByInterval(company.sales.perMinute, "1d")&from=midnight-10days This would start at zero on the left side of the graph, adding the sales each minute, and show the evolution of sales per day during the last 10 days. """ intervalDuration = int(to_seconds(parseTimeOffset(intervalUnit))) startTime = int(epoch(requestContext['startTime'])) results = [] for series in seriesList: newValues = [] # current time within series iteration currentTime = series.start # current accumulated value current = 0.0 for val in series: # reset integral value if crossing an interval boundary if ( ((currentTime - startTime) // intervalDuration) != ((currentTime - startTime - series.step) // intervalDuration) ): current = 0.0 if val is None: # keep previous value since val can be None when resetting # current to 0.0 newValues.append(current) else: current += val newValues.append(current) currentTime += series.step newName = "integralByInterval(%s,'%s')" % (series.name, intervalUnit) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def integralByInterval(requestContext, seriesList, intervalUnit): """ This will do the same as integral() funcion, except resetting the total to 0 at the given time in the parameter "from" Useful for finding totals per hour/day/week/.. Example:: &target=integralByInterval(company.sales.perMinute, "1d")&from=midnight-10days This would start at zero on the left side of the graph, adding the sales each minute, and show the evolution of sales per day during the last 10 days. """ intervalDuration = int(to_seconds(parseTimeOffset(intervalUnit))) startTime = int(epoch(requestContext['startTime'])) results = [] for series in seriesList: newValues = [] # current time within series iteration currentTime = series.start # current accumulated value current = 0.0 for val in series: # reset integral value if crossing an interval boundary if ( ((currentTime - startTime) // intervalDuration) != ((currentTime - startTime - series.step) // intervalDuration) ): current = 0.0 if val is None: # keep previous value since val can be None when resetting # current to 0.0 newValues.append(current) else: current += val newValues.append(current) currentTime += series.step newName = "integralByInterval(%s,'%s')" % (series.name, intervalUnit) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
[ "def", "integralByInterval", "(", "requestContext", ",", "seriesList", ",", "intervalUnit", ")", ":", "intervalDuration", "=", "int", "(", "to_seconds", "(", "parseTimeOffset", "(", "intervalUnit", ")", ")", ")", "startTime", "=", "int", "(", "epoch", "(", "requestContext", "[", "'startTime'", "]", ")", ")", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "newValues", "=", "[", "]", "# current time within series iteration", "currentTime", "=", "series", ".", "start", "# current accumulated value", "current", "=", "0.0", "for", "val", "in", "series", ":", "# reset integral value if crossing an interval boundary", "if", "(", "(", "(", "currentTime", "-", "startTime", ")", "//", "intervalDuration", ")", "!=", "(", "(", "currentTime", "-", "startTime", "-", "series", ".", "step", ")", "//", "intervalDuration", ")", ")", ":", "current", "=", "0.0", "if", "val", "is", "None", ":", "# keep previous value since val can be None when resetting", "# current to 0.0", "newValues", ".", "append", "(", "current", ")", "else", ":", "current", "+=", "val", "newValues", ".", "append", "(", "current", ")", "currentTime", "+=", "series", ".", "step", "newName", "=", "\"integralByInterval(%s,'%s')\"", "%", "(", "series", ".", "name", ",", "intervalUnit", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "return", "results" ]
This will do the same as integral() funcion, except resetting the total to 0 at the given time in the parameter "from" Useful for finding totals per hour/day/week/.. Example:: &target=integralByInterval(company.sales.perMinute, "1d")&from=midnight-10days This would start at zero on the left side of the graph, adding the sales each minute, and show the evolution of sales per day during the last 10 days.
[ "This", "will", "do", "the", "same", "as", "integral", "()", "funcion", "except", "resetting", "the", "total", "to", "0", "at", "the", "given", "time", "in", "the", "parameter", "from", "Useful", "for", "finding", "totals", "per", "hour", "/", "day", "/", "week", "/", ".." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1649-L1694
brutasse/graphite-api
graphite_api/functions.py
nonNegativeDerivative
def nonNegativeDerivative(requestContext, seriesList, maxValue=None): """ Same as the derivative function above, but ignores datapoints that trend down. Useful for counters that increase for a long time, then wrap or reset. (Such as if a network interface is destroyed and recreated by unloading and re-loading a kernel module, common with USB / WiFi cards. Example:: &target=nonNegativederivative( company.server.application01.ifconfig.TXPackets) """ results = [] for series in seriesList: newValues = [] prev = None for val in series: if None in (prev, val): newValues.append(None) prev = val continue diff = val - prev if diff >= 0: newValues.append(diff) elif maxValue is not None and maxValue >= val: newValues.append((maxValue - prev) + val + 1) else: newValues.append(None) prev = val newName = "nonNegativeDerivative(%s)" % series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def nonNegativeDerivative(requestContext, seriesList, maxValue=None): """ Same as the derivative function above, but ignores datapoints that trend down. Useful for counters that increase for a long time, then wrap or reset. (Such as if a network interface is destroyed and recreated by unloading and re-loading a kernel module, common with USB / WiFi cards. Example:: &target=nonNegativederivative( company.server.application01.ifconfig.TXPackets) """ results = [] for series in seriesList: newValues = [] prev = None for val in series: if None in (prev, val): newValues.append(None) prev = val continue diff = val - prev if diff >= 0: newValues.append(diff) elif maxValue is not None and maxValue >= val: newValues.append((maxValue - prev) + val + 1) else: newValues.append(None) prev = val newName = "nonNegativeDerivative(%s)" % series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
[ "def", "nonNegativeDerivative", "(", "requestContext", ",", "seriesList", ",", "maxValue", "=", "None", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "newValues", "=", "[", "]", "prev", "=", "None", "for", "val", "in", "series", ":", "if", "None", "in", "(", "prev", ",", "val", ")", ":", "newValues", ".", "append", "(", "None", ")", "prev", "=", "val", "continue", "diff", "=", "val", "-", "prev", "if", "diff", ">=", "0", ":", "newValues", ".", "append", "(", "diff", ")", "elif", "maxValue", "is", "not", "None", "and", "maxValue", ">=", "val", ":", "newValues", ".", "append", "(", "(", "maxValue", "-", "prev", ")", "+", "val", "+", "1", ")", "else", ":", "newValues", ".", "append", "(", "None", ")", "prev", "=", "val", "newName", "=", "\"nonNegativeDerivative(%s)\"", "%", "series", ".", "name", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "return", "results" ]
Same as the derivative function above, but ignores datapoints that trend down. Useful for counters that increase for a long time, then wrap or reset. (Such as if a network interface is destroyed and recreated by unloading and re-loading a kernel module, common with USB / WiFi cards. Example:: &target=nonNegativederivative( company.server.application01.ifconfig.TXPackets)
[ "Same", "as", "the", "derivative", "function", "above", "but", "ignores", "datapoints", "that", "trend", "down", ".", "Useful", "for", "counters", "that", "increase", "for", "a", "long", "time", "then", "wrap", "or", "reset", ".", "(", "Such", "as", "if", "a", "network", "interface", "is", "destroyed", "and", "recreated", "by", "unloading", "and", "re", "-", "loading", "a", "kernel", "module", "common", "with", "USB", "/", "WiFi", "cards", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1697-L1738
brutasse/graphite-api
graphite_api/functions.py
stacked
def stacked(requestContext, seriesLists, stackName='__DEFAULT__'): """ Takes one metric or a wildcard seriesList and change them so they are stacked. This is a way of stacking just a couple of metrics without having to use the stacked area mode (that stacks everything). By means of this a mixed stacked and non stacked graph can be made It can also take an optional argument with a name of the stack, in case there is more than one, e.g. for input and output metrics. Example:: &target=stacked(company.server.application01.ifconfig.TXPackets, 'tx') """ if 'totalStack' in requestContext: totalStack = requestContext['totalStack'].get(stackName, []) else: requestContext['totalStack'] = {} totalStack = [] results = [] for series in seriesLists: newValues = [] for i in range(len(series)): if len(totalStack) <= i: totalStack.append(0) if series[i] is not None: totalStack[i] += series[i] newValues.append(totalStack[i]) else: newValues.append(None) # Work-around for the case when legend is set if stackName == '__DEFAULT__': newName = "stacked(%s)" % series.name else: newName = series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.options['stacked'] = True newSeries.pathExpression = newName results.append(newSeries) requestContext['totalStack'][stackName] = totalStack return results
python
def stacked(requestContext, seriesLists, stackName='__DEFAULT__'): """ Takes one metric or a wildcard seriesList and change them so they are stacked. This is a way of stacking just a couple of metrics without having to use the stacked area mode (that stacks everything). By means of this a mixed stacked and non stacked graph can be made It can also take an optional argument with a name of the stack, in case there is more than one, e.g. for input and output metrics. Example:: &target=stacked(company.server.application01.ifconfig.TXPackets, 'tx') """ if 'totalStack' in requestContext: totalStack = requestContext['totalStack'].get(stackName, []) else: requestContext['totalStack'] = {} totalStack = [] results = [] for series in seriesLists: newValues = [] for i in range(len(series)): if len(totalStack) <= i: totalStack.append(0) if series[i] is not None: totalStack[i] += series[i] newValues.append(totalStack[i]) else: newValues.append(None) # Work-around for the case when legend is set if stackName == '__DEFAULT__': newName = "stacked(%s)" % series.name else: newName = series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.options['stacked'] = True newSeries.pathExpression = newName results.append(newSeries) requestContext['totalStack'][stackName] = totalStack return results
[ "def", "stacked", "(", "requestContext", ",", "seriesLists", ",", "stackName", "=", "'__DEFAULT__'", ")", ":", "if", "'totalStack'", "in", "requestContext", ":", "totalStack", "=", "requestContext", "[", "'totalStack'", "]", ".", "get", "(", "stackName", ",", "[", "]", ")", "else", ":", "requestContext", "[", "'totalStack'", "]", "=", "{", "}", "totalStack", "=", "[", "]", "results", "=", "[", "]", "for", "series", "in", "seriesLists", ":", "newValues", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "series", ")", ")", ":", "if", "len", "(", "totalStack", ")", "<=", "i", ":", "totalStack", ".", "append", "(", "0", ")", "if", "series", "[", "i", "]", "is", "not", "None", ":", "totalStack", "[", "i", "]", "+=", "series", "[", "i", "]", "newValues", ".", "append", "(", "totalStack", "[", "i", "]", ")", "else", ":", "newValues", ".", "append", "(", "None", ")", "# Work-around for the case when legend is set", "if", "stackName", "==", "'__DEFAULT__'", ":", "newName", "=", "\"stacked(%s)\"", "%", "series", ".", "name", "else", ":", "newName", "=", "series", ".", "name", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "options", "[", "'stacked'", "]", "=", "True", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "requestContext", "[", "'totalStack'", "]", "[", "stackName", "]", "=", "totalStack", "return", "results" ]
Takes one metric or a wildcard seriesList and change them so they are stacked. This is a way of stacking just a couple of metrics without having to use the stacked area mode (that stacks everything). By means of this a mixed stacked and non stacked graph can be made It can also take an optional argument with a name of the stack, in case there is more than one, e.g. for input and output metrics. Example:: &target=stacked(company.server.application01.ifconfig.TXPackets, 'tx')
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "change", "them", "so", "they", "are", "stacked", ".", "This", "is", "a", "way", "of", "stacking", "just", "a", "couple", "of", "metrics", "without", "having", "to", "use", "the", "stacked", "area", "mode", "(", "that", "stacks", "everything", ")", ".", "By", "means", "of", "this", "a", "mixed", "stacked", "and", "non", "stacked", "graph", "can", "be", "made" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1741-L1786
brutasse/graphite-api
graphite_api/functions.py
areaBetween
def areaBetween(requestContext, *seriesLists): """ Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example below). The order of the lower and higher values series does not matter. The visualization only works when used in conjunction with ``areaMode=stacked``. Most likely use case is to provide a band within which another metric should move. In such case applying an ``alpha()``, as in the second example, gives best visual results. Example:: &target=areaBetween(service.latency.{min,max})&areaMode=stacked &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked If for instance, you need to build a seriesList, you should use the ``group`` function, like so:: &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max))) """ if len(seriesLists) == 1: [seriesLists] = seriesLists assert len(seriesLists) == 2, ("areaBetween series argument must " "reference *exactly* 2 series") lower, upper = seriesLists if len(lower) == 1: [lower] = lower if len(upper) == 1: [upper] = upper lower.options['stacked'] = True lower.options['invisible'] = True upper.options['stacked'] = True lower.name = upper.name = "areaBetween(%s)" % upper.pathExpression return [lower, upper]
python
def areaBetween(requestContext, *seriesLists): """ Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example below). The order of the lower and higher values series does not matter. The visualization only works when used in conjunction with ``areaMode=stacked``. Most likely use case is to provide a band within which another metric should move. In such case applying an ``alpha()``, as in the second example, gives best visual results. Example:: &target=areaBetween(service.latency.{min,max})&areaMode=stacked &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked If for instance, you need to build a seriesList, you should use the ``group`` function, like so:: &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max))) """ if len(seriesLists) == 1: [seriesLists] = seriesLists assert len(seriesLists) == 2, ("areaBetween series argument must " "reference *exactly* 2 series") lower, upper = seriesLists if len(lower) == 1: [lower] = lower if len(upper) == 1: [upper] = upper lower.options['stacked'] = True lower.options['invisible'] = True upper.options['stacked'] = True lower.name = upper.name = "areaBetween(%s)" % upper.pathExpression return [lower, upper]
[ "def", "areaBetween", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "len", "(", "seriesLists", ")", "==", "1", ":", "[", "seriesLists", "]", "=", "seriesLists", "assert", "len", "(", "seriesLists", ")", "==", "2", ",", "(", "\"areaBetween series argument must \"", "\"reference *exactly* 2 series\"", ")", "lower", ",", "upper", "=", "seriesLists", "if", "len", "(", "lower", ")", "==", "1", ":", "[", "lower", "]", "=", "lower", "if", "len", "(", "upper", ")", "==", "1", ":", "[", "upper", "]", "=", "upper", "lower", ".", "options", "[", "'stacked'", "]", "=", "True", "lower", ".", "options", "[", "'invisible'", "]", "=", "True", "upper", ".", "options", "[", "'stacked'", "]", "=", "True", "lower", ".", "name", "=", "upper", ".", "name", "=", "\"areaBetween(%s)\"", "%", "upper", ".", "pathExpression", "return", "[", "lower", ",", "upper", "]" ]
Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example below). The order of the lower and higher values series does not matter. The visualization only works when used in conjunction with ``areaMode=stacked``. Most likely use case is to provide a band within which another metric should move. In such case applying an ``alpha()``, as in the second example, gives best visual results. Example:: &target=areaBetween(service.latency.{min,max})&areaMode=stacked &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked If for instance, you need to build a seriesList, you should use the ``group`` function, like so:: &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max)))
[ "Draws", "the", "vertical", "area", "in", "between", "the", "two", "series", "in", "seriesList", ".", "Useful", "for", "visualizing", "a", "range", "such", "as", "the", "minimum", "and", "maximum", "latency", "for", "a", "service", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1789-L1828
brutasse/graphite-api
graphite_api/functions.py
aliasSub
def aliasSub(requestContext, seriesList, search, replace): """ Runs series names through a regex search/replace. Example:: &target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1") """ try: seriesList.name = re.sub(search, replace, seriesList.name) except AttributeError: for series in seriesList: series.name = re.sub(search, replace, series.name) return seriesList
python
def aliasSub(requestContext, seriesList, search, replace): """ Runs series names through a regex search/replace. Example:: &target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1") """ try: seriesList.name = re.sub(search, replace, seriesList.name) except AttributeError: for series in seriesList: series.name = re.sub(search, replace, series.name) return seriesList
[ "def", "aliasSub", "(", "requestContext", ",", "seriesList", ",", "search", ",", "replace", ")", ":", "try", ":", "seriesList", ".", "name", "=", "re", ".", "sub", "(", "search", ",", "replace", ",", "seriesList", ".", "name", ")", "except", "AttributeError", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "re", ".", "sub", "(", "search", ",", "replace", ",", "series", ".", "name", ")", "return", "seriesList" ]
Runs series names through a regex search/replace. Example:: &target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
[ "Runs", "series", "names", "through", "a", "regex", "search", "/", "replace", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1831-L1844
brutasse/graphite-api
graphite_api/functions.py
alias
def alias(requestContext, seriesList, newName): """ Takes one metric or a wildcard seriesList and a string in quotes. Prints the string instead of the metric name in the legend. Example:: &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets") """ try: seriesList.name = newName except AttributeError: for series in seriesList: series.name = newName return seriesList
python
def alias(requestContext, seriesList, newName): """ Takes one metric or a wildcard seriesList and a string in quotes. Prints the string instead of the metric name in the legend. Example:: &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets") """ try: seriesList.name = newName except AttributeError: for series in seriesList: series.name = newName return seriesList
[ "def", "alias", "(", "requestContext", ",", "seriesList", ",", "newName", ")", ":", "try", ":", "seriesList", ".", "name", "=", "newName", "except", "AttributeError", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "newName", "return", "seriesList" ]
Takes one metric or a wildcard seriesList and a string in quotes. Prints the string instead of the metric name in the legend. Example:: &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "a", "string", "in", "quotes", ".", "Prints", "the", "string", "instead", "of", "the", "metric", "name", "in", "the", "legend", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1847-L1862
brutasse/graphite-api
graphite_api/functions.py
cactiStyle
def cactiStyle(requestContext, seriesList, system=None, units=None): """ Takes a series list and modifies the aliases to provide column aligned output with Current, Max, and Min values in the style of cacti. Optionally takes a "system" value to apply unit formatting in the same style as the Y-axis, or a "unit" string to append an arbitrary unit suffix. NOTE: column alignment only works with monospace fonts such as terminus. Example:: &target=cactiStyle(ganglia.*.net.bytes_out,"si") &target=cactiStyle(ganglia.*.net.bytes_out,"si","b") """ def fmt(x): if system: if units: return "%.2f %s" % format_units(x, system=system, units=units) else: return "%.2f%s" % format_units(x, system=system) else: if units: return "%.2f %s" % (x, units) else: return "%.2f" % x nameLen = max([0] + [len(series.name) for series in seriesList]) lastLen = max([0] + [len(fmt(int(safeLast(series) or 3))) for series in seriesList]) + 3 maxLen = max([0] + [len(fmt(int(safeMax(series) or 3))) for series in seriesList]) + 3 minLen = max([0] + [len(fmt(int(safeMin(series) or 3))) for series in seriesList]) + 3 for series in seriesList: last = safeLast(series) maximum = safeMax(series) minimum = safeMin(series) if last is None: last = NAN else: last = fmt(float(last)) if maximum is None: maximum = NAN else: maximum = fmt(float(maximum)) if minimum is None: minimum = NAN else: minimum = fmt(float(minimum)) series.name = "%*s Current:%*s Max:%*s Min:%*s " % ( -nameLen, series.name, -lastLen, last, -maxLen, maximum, -minLen, minimum) return seriesList
python
def cactiStyle(requestContext, seriesList, system=None, units=None): """ Takes a series list and modifies the aliases to provide column aligned output with Current, Max, and Min values in the style of cacti. Optionally takes a "system" value to apply unit formatting in the same style as the Y-axis, or a "unit" string to append an arbitrary unit suffix. NOTE: column alignment only works with monospace fonts such as terminus. Example:: &target=cactiStyle(ganglia.*.net.bytes_out,"si") &target=cactiStyle(ganglia.*.net.bytes_out,"si","b") """ def fmt(x): if system: if units: return "%.2f %s" % format_units(x, system=system, units=units) else: return "%.2f%s" % format_units(x, system=system) else: if units: return "%.2f %s" % (x, units) else: return "%.2f" % x nameLen = max([0] + [len(series.name) for series in seriesList]) lastLen = max([0] + [len(fmt(int(safeLast(series) or 3))) for series in seriesList]) + 3 maxLen = max([0] + [len(fmt(int(safeMax(series) or 3))) for series in seriesList]) + 3 minLen = max([0] + [len(fmt(int(safeMin(series) or 3))) for series in seriesList]) + 3 for series in seriesList: last = safeLast(series) maximum = safeMax(series) minimum = safeMin(series) if last is None: last = NAN else: last = fmt(float(last)) if maximum is None: maximum = NAN else: maximum = fmt(float(maximum)) if minimum is None: minimum = NAN else: minimum = fmt(float(minimum)) series.name = "%*s Current:%*s Max:%*s Min:%*s " % ( -nameLen, series.name, -lastLen, last, -maxLen, maximum, -minLen, minimum) return seriesList
[ "def", "cactiStyle", "(", "requestContext", ",", "seriesList", ",", "system", "=", "None", ",", "units", "=", "None", ")", ":", "def", "fmt", "(", "x", ")", ":", "if", "system", ":", "if", "units", ":", "return", "\"%.2f %s\"", "%", "format_units", "(", "x", ",", "system", "=", "system", ",", "units", "=", "units", ")", "else", ":", "return", "\"%.2f%s\"", "%", "format_units", "(", "x", ",", "system", "=", "system", ")", "else", ":", "if", "units", ":", "return", "\"%.2f %s\"", "%", "(", "x", ",", "units", ")", "else", ":", "return", "\"%.2f\"", "%", "x", "nameLen", "=", "max", "(", "[", "0", "]", "+", "[", "len", "(", "series", ".", "name", ")", "for", "series", "in", "seriesList", "]", ")", "lastLen", "=", "max", "(", "[", "0", "]", "+", "[", "len", "(", "fmt", "(", "int", "(", "safeLast", "(", "series", ")", "or", "3", ")", ")", ")", "for", "series", "in", "seriesList", "]", ")", "+", "3", "maxLen", "=", "max", "(", "[", "0", "]", "+", "[", "len", "(", "fmt", "(", "int", "(", "safeMax", "(", "series", ")", "or", "3", ")", ")", ")", "for", "series", "in", "seriesList", "]", ")", "+", "3", "minLen", "=", "max", "(", "[", "0", "]", "+", "[", "len", "(", "fmt", "(", "int", "(", "safeMin", "(", "series", ")", "or", "3", ")", ")", ")", "for", "series", "in", "seriesList", "]", ")", "+", "3", "for", "series", "in", "seriesList", ":", "last", "=", "safeLast", "(", "series", ")", "maximum", "=", "safeMax", "(", "series", ")", "minimum", "=", "safeMin", "(", "series", ")", "if", "last", "is", "None", ":", "last", "=", "NAN", "else", ":", "last", "=", "fmt", "(", "float", "(", "last", ")", ")", "if", "maximum", "is", "None", ":", "maximum", "=", "NAN", "else", ":", "maximum", "=", "fmt", "(", "float", "(", "maximum", ")", ")", "if", "minimum", "is", "None", ":", "minimum", "=", "NAN", "else", ":", "minimum", "=", "fmt", "(", "float", "(", "minimum", ")", ")", "series", ".", "name", "=", "\"%*s Current:%*s Max:%*s Min:%*s \"", "%", "(", "-", "nameLen", ",", "series", ".", "name", ",", "-", "lastLen", ",", "last", ",", "-", "maxLen", ",", "maximum", ",", "-", "minLen", ",", "minimum", ")", "return", "seriesList" ]
Takes a series list and modifies the aliases to provide column aligned output with Current, Max, and Min values in the style of cacti. Optionally takes a "system" value to apply unit formatting in the same style as the Y-axis, or a "unit" string to append an arbitrary unit suffix. NOTE: column alignment only works with monospace fonts such as terminus. Example:: &target=cactiStyle(ganglia.*.net.bytes_out,"si") &target=cactiStyle(ganglia.*.net.bytes_out,"si","b")
[ "Takes", "a", "series", "list", "and", "modifies", "the", "aliases", "to", "provide", "column", "aligned", "output", "with", "Current", "Max", "and", "Min", "values", "in", "the", "style", "of", "cacti", ".", "Optionally", "takes", "a", "system", "value", "to", "apply", "unit", "formatting", "in", "the", "same", "style", "as", "the", "Y", "-", "axis", "or", "a", "unit", "string", "to", "append", "an", "arbitrary", "unit", "suffix", ".", "NOTE", ":", "column", "alignment", "only", "works", "with", "monospace", "fonts", "such", "as", "terminus", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1865-L1918
brutasse/graphite-api
graphite_api/functions.py
_getFirstPathExpression
def _getFirstPathExpression(name): """Returns the first metric path in an expression.""" tokens = grammar.parseString(name) pathExpression = None while pathExpression is None: if tokens.pathExpression: pathExpression = tokens.pathExpression elif tokens.expression: tokens = tokens.expression elif tokens.call: tokens = tokens.call.args[0] else: break return pathExpression
python
def _getFirstPathExpression(name): """Returns the first metric path in an expression.""" tokens = grammar.parseString(name) pathExpression = None while pathExpression is None: if tokens.pathExpression: pathExpression = tokens.pathExpression elif tokens.expression: tokens = tokens.expression elif tokens.call: tokens = tokens.call.args[0] else: break return pathExpression
[ "def", "_getFirstPathExpression", "(", "name", ")", ":", "tokens", "=", "grammar", ".", "parseString", "(", "name", ")", "pathExpression", "=", "None", "while", "pathExpression", "is", "None", ":", "if", "tokens", ".", "pathExpression", ":", "pathExpression", "=", "tokens", ".", "pathExpression", "elif", "tokens", ".", "expression", ":", "tokens", "=", "tokens", ".", "expression", "elif", "tokens", ".", "call", ":", "tokens", "=", "tokens", ".", "call", ".", "args", "[", "0", "]", "else", ":", "break", "return", "pathExpression" ]
Returns the first metric path in an expression.
[ "Returns", "the", "first", "metric", "path", "in", "an", "expression", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1921-L1934
brutasse/graphite-api
graphite_api/functions.py
aliasByNode
def aliasByNode(requestContext, seriesList, *nodes): """ Takes a seriesList and applies an alias derived from one or more "node" portion/s of the target name. Node indices are 0 indexed. Example:: &target=aliasByNode(ganglia.*.cpu.load5,1) """ for series in seriesList: pathExpression = _getFirstPathExpression(series.name) metric_pieces = pathExpression.split('.') series.name = '.'.join(metric_pieces[n] for n in nodes) return seriesList
python
def aliasByNode(requestContext, seriesList, *nodes): """ Takes a seriesList and applies an alias derived from one or more "node" portion/s of the target name. Node indices are 0 indexed. Example:: &target=aliasByNode(ganglia.*.cpu.load5,1) """ for series in seriesList: pathExpression = _getFirstPathExpression(series.name) metric_pieces = pathExpression.split('.') series.name = '.'.join(metric_pieces[n] for n in nodes) return seriesList
[ "def", "aliasByNode", "(", "requestContext", ",", "seriesList", ",", "*", "nodes", ")", ":", "for", "series", "in", "seriesList", ":", "pathExpression", "=", "_getFirstPathExpression", "(", "series", ".", "name", ")", "metric_pieces", "=", "pathExpression", ".", "split", "(", "'.'", ")", "series", ".", "name", "=", "'.'", ".", "join", "(", "metric_pieces", "[", "n", "]", "for", "n", "in", "nodes", ")", "return", "seriesList" ]
Takes a seriesList and applies an alias derived from one or more "node" portion/s of the target name. Node indices are 0 indexed. Example:: &target=aliasByNode(ganglia.*.cpu.load5,1)
[ "Takes", "a", "seriesList", "and", "applies", "an", "alias", "derived", "from", "one", "or", "more", "node", "portion", "/", "s", "of", "the", "target", "name", ".", "Node", "indices", "are", "0", "indexed", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1937-L1951
brutasse/graphite-api
graphite_api/functions.py
legendValue
def legendValue(requestContext, seriesList, *valueTypes): """ Takes one metric or a wildcard seriesList and a string in quotes. Appends a value to the metric name in the legend. Currently one or several of: `last`, `avg`, `total`, `min`, `max`. The last argument can be `si` (default) or `binary`, in that case values will be formatted in the corresponding system. Example:: &target=legendValue(Sales.widgets.largeBlue, 'avg', 'max', 'si') """ valueFuncs = { 'avg': lambda s: safeDiv(safeSum(s), safeLen(s)), 'total': safeSum, 'min': safeMin, 'max': safeMax, 'last': safeLast, } system = None if valueTypes[-1] in ('si', 'binary'): system = valueTypes[-1] valueTypes = valueTypes[:-1] for valueType in valueTypes: valueFunc = valueFuncs.get(valueType, lambda s: '(?)') if system is None: for series in seriesList: series.name += " (%s: %s)" % (valueType, valueFunc(series)) else: for series in seriesList: value = valueFunc(series) formatted = None if value is not None: formatted = "%.2f%s" % format_units(value, system=system) series.name = "%-20s%-5s%-10s" % (series.name, valueType, formatted) return seriesList
python
def legendValue(requestContext, seriesList, *valueTypes): """ Takes one metric or a wildcard seriesList and a string in quotes. Appends a value to the metric name in the legend. Currently one or several of: `last`, `avg`, `total`, `min`, `max`. The last argument can be `si` (default) or `binary`, in that case values will be formatted in the corresponding system. Example:: &target=legendValue(Sales.widgets.largeBlue, 'avg', 'max', 'si') """ valueFuncs = { 'avg': lambda s: safeDiv(safeSum(s), safeLen(s)), 'total': safeSum, 'min': safeMin, 'max': safeMax, 'last': safeLast, } system = None if valueTypes[-1] in ('si', 'binary'): system = valueTypes[-1] valueTypes = valueTypes[:-1] for valueType in valueTypes: valueFunc = valueFuncs.get(valueType, lambda s: '(?)') if system is None: for series in seriesList: series.name += " (%s: %s)" % (valueType, valueFunc(series)) else: for series in seriesList: value = valueFunc(series) formatted = None if value is not None: formatted = "%.2f%s" % format_units(value, system=system) series.name = "%-20s%-5s%-10s" % (series.name, valueType, formatted) return seriesList
[ "def", "legendValue", "(", "requestContext", ",", "seriesList", ",", "*", "valueTypes", ")", ":", "valueFuncs", "=", "{", "'avg'", ":", "lambda", "s", ":", "safeDiv", "(", "safeSum", "(", "s", ")", ",", "safeLen", "(", "s", ")", ")", ",", "'total'", ":", "safeSum", ",", "'min'", ":", "safeMin", ",", "'max'", ":", "safeMax", ",", "'last'", ":", "safeLast", ",", "}", "system", "=", "None", "if", "valueTypes", "[", "-", "1", "]", "in", "(", "'si'", ",", "'binary'", ")", ":", "system", "=", "valueTypes", "[", "-", "1", "]", "valueTypes", "=", "valueTypes", "[", ":", "-", "1", "]", "for", "valueType", "in", "valueTypes", ":", "valueFunc", "=", "valueFuncs", ".", "get", "(", "valueType", ",", "lambda", "s", ":", "'(?)'", ")", "if", "system", "is", "None", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "+=", "\" (%s: %s)\"", "%", "(", "valueType", ",", "valueFunc", "(", "series", ")", ")", "else", ":", "for", "series", "in", "seriesList", ":", "value", "=", "valueFunc", "(", "series", ")", "formatted", "=", "None", "if", "value", "is", "not", "None", ":", "formatted", "=", "\"%.2f%s\"", "%", "format_units", "(", "value", ",", "system", "=", "system", ")", "series", ".", "name", "=", "\"%-20s%-5s%-10s\"", "%", "(", "series", ".", "name", ",", "valueType", ",", "formatted", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList and a string in quotes. Appends a value to the metric name in the legend. Currently one or several of: `last`, `avg`, `total`, `min`, `max`. The last argument can be `si` (default) or `binary`, in that case values will be formatted in the corresponding system. Example:: &target=legendValue(Sales.widgets.largeBlue, 'avg', 'max', 'si')
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "a", "string", "in", "quotes", ".", "Appends", "a", "value", "to", "the", "metric", "name", "in", "the", "legend", ".", "Currently", "one", "or", "several", "of", ":", "last", "avg", "total", "min", "max", ".", "The", "last", "argument", "can", "be", "si", "(", "default", ")", "or", "binary", "in", "that", "case", "values", "will", "be", "formatted", "in", "the", "corresponding", "system", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1966-L2003
brutasse/graphite-api
graphite_api/functions.py
alpha
def alpha(requestContext, seriesList, alpha): """ Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1. """ for series in seriesList: series.options['alpha'] = alpha return seriesList
python
def alpha(requestContext, seriesList, alpha): """ Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1. """ for series in seriesList: series.options['alpha'] = alpha return seriesList
[ "def", "alpha", "(", "requestContext", ",", "seriesList", ",", "alpha", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "options", "[", "'alpha'", "]", "=", "alpha", "return", "seriesList" ]
Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1.
[ "Assigns", "the", "given", "alpha", "transparency", "setting", "to", "the", "series", ".", "Takes", "a", "float", "value", "between", "0", "and", "1", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2006-L2013
brutasse/graphite-api
graphite_api/functions.py
color
def color(requestContext, seriesList, theColor): """ Assigns the given color to the seriesList Example:: &target=color(collectd.hostname.cpu.0.user, 'green') &target=color(collectd.hostname.cpu.0.system, 'ff0000') &target=color(collectd.hostname.cpu.0.idle, 'gray') &target=color(collectd.hostname.cpu.0.idle, '6464ffaa') """ for series in seriesList: series.color = theColor return seriesList
python
def color(requestContext, seriesList, theColor): """ Assigns the given color to the seriesList Example:: &target=color(collectd.hostname.cpu.0.user, 'green') &target=color(collectd.hostname.cpu.0.system, 'ff0000') &target=color(collectd.hostname.cpu.0.idle, 'gray') &target=color(collectd.hostname.cpu.0.idle, '6464ffaa') """ for series in seriesList: series.color = theColor return seriesList
[ "def", "color", "(", "requestContext", ",", "seriesList", ",", "theColor", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "color", "=", "theColor", "return", "seriesList" ]
Assigns the given color to the seriesList Example:: &target=color(collectd.hostname.cpu.0.user, 'green') &target=color(collectd.hostname.cpu.0.system, 'ff0000') &target=color(collectd.hostname.cpu.0.idle, 'gray') &target=color(collectd.hostname.cpu.0.idle, '6464ffaa')
[ "Assigns", "the", "given", "color", "to", "the", "seriesList" ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2016-L2030
brutasse/graphite-api
graphite_api/functions.py
substr
def substr(requestContext, seriesList, start=0, stop=0): """ Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the metric name is a list or array, with each element separated by dots. Prints n - length elements of the array (if only one integer n is passed) or n - m elements of the array (if two integers n and m are passed). The list starts with element 0 and ends with element (length - 1). Example:: &target=substr(carbon.agents.hostname.avgUpdateTime,2,4) The label would be printed as "hostname.avgUpdateTime". """ for series in seriesList: left = series.name.rfind('(') + 1 right = series.name.find(')') if right < 0: right = len(series.name)+1 cleanName = series.name[left:right:].split('.') if int(stop) == 0: series.name = '.'.join(cleanName[int(start)::]) else: series.name = '.'.join(cleanName[int(start):int(stop):]) # substr(func(a.b,'c'),1) becomes b instead of b,'c' series.name = re.sub(',.*$', '', series.name) return seriesList
python
def substr(requestContext, seriesList, start=0, stop=0): """ Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the metric name is a list or array, with each element separated by dots. Prints n - length elements of the array (if only one integer n is passed) or n - m elements of the array (if two integers n and m are passed). The list starts with element 0 and ends with element (length - 1). Example:: &target=substr(carbon.agents.hostname.avgUpdateTime,2,4) The label would be printed as "hostname.avgUpdateTime". """ for series in seriesList: left = series.name.rfind('(') + 1 right = series.name.find(')') if right < 0: right = len(series.name)+1 cleanName = series.name[left:right:].split('.') if int(stop) == 0: series.name = '.'.join(cleanName[int(start)::]) else: series.name = '.'.join(cleanName[int(start):int(stop):]) # substr(func(a.b,'c'),1) becomes b instead of b,'c' series.name = re.sub(',.*$', '', series.name) return seriesList
[ "def", "substr", "(", "requestContext", ",", "seriesList", ",", "start", "=", "0", ",", "stop", "=", "0", ")", ":", "for", "series", "in", "seriesList", ":", "left", "=", "series", ".", "name", ".", "rfind", "(", "'('", ")", "+", "1", "right", "=", "series", ".", "name", ".", "find", "(", "')'", ")", "if", "right", "<", "0", ":", "right", "=", "len", "(", "series", ".", "name", ")", "+", "1", "cleanName", "=", "series", ".", "name", "[", "left", ":", "right", ":", "]", ".", "split", "(", "'.'", ")", "if", "int", "(", "stop", ")", "==", "0", ":", "series", ".", "name", "=", "'.'", ".", "join", "(", "cleanName", "[", "int", "(", "start", ")", ":", ":", "]", ")", "else", ":", "series", ".", "name", "=", "'.'", ".", "join", "(", "cleanName", "[", "int", "(", "start", ")", ":", "int", "(", "stop", ")", ":", "]", ")", "# substr(func(a.b,'c'),1) becomes b instead of b,'c'", "series", ".", "name", "=", "re", ".", "sub", "(", "',.*$'", ",", "''", ",", "series", ".", "name", ")", "return", "seriesList" ]
Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the metric name is a list or array, with each element separated by dots. Prints n - length elements of the array (if only one integer n is passed) or n - m elements of the array (if two integers n and m are passed). The list starts with element 0 and ends with element (length - 1). Example:: &target=substr(carbon.agents.hostname.avgUpdateTime,2,4) The label would be printed as "hostname.avgUpdateTime".
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "1", "or", "2", "integers", ".", "Assume", "that", "the", "metric", "name", "is", "a", "list", "or", "array", "with", "each", "element", "separated", "by", "dots", ".", "Prints", "n", "-", "length", "elements", "of", "the", "array", "(", "if", "only", "one", "integer", "n", "is", "passed", ")", "or", "n", "-", "m", "elements", "of", "the", "array", "(", "if", "two", "integers", "n", "and", "m", "are", "passed", ")", ".", "The", "list", "starts", "with", "element", "0", "and", "ends", "with", "element", "(", "length", "-", "1", ")", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2033-L2062
brutasse/graphite-api
graphite_api/functions.py
logarithm
def logarithm(requestContext, seriesList, base=10): """ Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic format. If base is omitted, the function defaults to base 10. Example:: &target=log(carbon.agents.hostname.avgUpdateTime,2) """ results = [] for series in seriesList: newValues = [] for val in series: if val is None: newValues.append(None) elif val <= 0: newValues.append(None) else: newValues.append(math.log(val, base)) newName = "log(%s, %s)" % (series.name, base) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def logarithm(requestContext, seriesList, base=10): """ Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic format. If base is omitted, the function defaults to base 10. Example:: &target=log(carbon.agents.hostname.avgUpdateTime,2) """ results = [] for series in seriesList: newValues = [] for val in series: if val is None: newValues.append(None) elif val <= 0: newValues.append(None) else: newValues.append(math.log(val, base)) newName = "log(%s, %s)" % (series.name, base) newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
[ "def", "logarithm", "(", "requestContext", ",", "seriesList", ",", "base", "=", "10", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "newValues", "=", "[", "]", "for", "val", "in", "series", ":", "if", "val", "is", "None", ":", "newValues", ".", "append", "(", "None", ")", "elif", "val", "<=", "0", ":", "newValues", ".", "append", "(", "None", ")", "else", ":", "newValues", ".", "append", "(", "math", ".", "log", "(", "val", ",", "base", ")", ")", "newName", "=", "\"log(%s, %s)\"", "%", "(", "series", ".", "name", ",", "base", ")", "newSeries", "=", "TimeSeries", "(", "newName", ",", "series", ".", "start", ",", "series", ".", "end", ",", "series", ".", "step", ",", "newValues", ")", "newSeries", ".", "pathExpression", "=", "newName", "results", ".", "append", "(", "newSeries", ")", "return", "results" ]
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic format. If base is omitted, the function defaults to base 10. Example:: &target=log(carbon.agents.hostname.avgUpdateTime,2)
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "a", "base", "and", "draws", "the", "y", "-", "axis", "in", "logarithmic", "format", ".", "If", "base", "is", "omitted", "the", "function", "defaults", "to", "base", "10", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2065-L2090
brutasse/graphite-api
graphite_api/functions.py
maximumBelow
def maximumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a maximum value below n. Example:: &target=maximumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which always sent less than 1000 packets/min. """ results = [] for series in seriesList: val = safeMax(series) if val is None or val <= n: results.append(series) return results
python
def maximumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a maximum value below n. Example:: &target=maximumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which always sent less than 1000 packets/min. """ results = [] for series in seriesList: val = safeMax(series) if val is None or val <= n: results.append(series) return results
[ "def", "maximumBelow", "(", "requestContext", ",", "seriesList", ",", "n", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "val", "=", "safeMax", "(", "series", ")", "if", "val", "is", "None", "or", "val", "<=", "n", ":", "results", ".", "append", "(", "series", ")", "return", "results" ]
Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a maximum value below n. Example:: &target=maximumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which always sent less than 1000 packets/min.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "a", "constant", "n", ".", "Draws", "only", "the", "metrics", "with", "a", "maximum", "value", "below", "n", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2133-L2150
brutasse/graphite-api
graphite_api/functions.py
minimumBelow
def minimumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a minimum value below n. Example:: &target=minimumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which sent at one point less than 1000 packets/min. """ results = [] for series in seriesList: val = safeMin(series) if val is None or val <= n: results.append(series) return results
python
def minimumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a minimum value below n. Example:: &target=minimumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which sent at one point less than 1000 packets/min. """ results = [] for series in seriesList: val = safeMin(series) if val is None or val <= n: results.append(series) return results
[ "def", "minimumBelow", "(", "requestContext", ",", "seriesList", ",", "n", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "val", "=", "safeMin", "(", "series", ")", "if", "val", "is", "None", "or", "val", "<=", "n", ":", "results", ".", "append", "(", "series", ")", "return", "results" ]
Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a minimum value below n. Example:: &target=minimumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which sent at one point less than 1000 packets/min.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "a", "constant", "n", ".", "Draws", "only", "the", "metrics", "with", "a", "minimum", "value", "below", "n", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2153-L2170
brutasse/graphite-api
graphite_api/functions.py
highestMax
def highestMax(requestContext, seriesList, n=1): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest maximum value in the time period specified. Example:: &target=highestMax(server*.instance*.threads.busy,5) Draws the top 5 servers who have had the most busy threads during the time period specified. """ result_list = sorted(seriesList, key=lambda s: safeMax(s))[-n:] return sorted(result_list, key=lambda s: max(s), reverse=True)
python
def highestMax(requestContext, seriesList, n=1): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest maximum value in the time period specified. Example:: &target=highestMax(server*.instance*.threads.busy,5) Draws the top 5 servers who have had the most busy threads during the time period specified. """ result_list = sorted(seriesList, key=lambda s: safeMax(s))[-n:] return sorted(result_list, key=lambda s: max(s), reverse=True)
[ "def", "highestMax", "(", "requestContext", ",", "seriesList", ",", "n", "=", "1", ")", ":", "result_list", "=", "sorted", "(", "seriesList", ",", "key", "=", "lambda", "s", ":", "safeMax", "(", "s", ")", ")", "[", "-", "n", ":", "]", "return", "sorted", "(", "result_list", ",", "key", "=", "lambda", "s", ":", "max", "(", "s", ")", ",", "reverse", "=", "True", ")" ]
Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest maximum value in the time period specified. Example:: &target=highestMax(server*.instance*.threads.busy,5) Draws the top 5 servers who have had the most busy threads during the time period specified.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "an", "integer", "N", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2189-L2205
brutasse/graphite-api
graphite_api/functions.py
currentAbove
def currentAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.threads.busy,50) Draws the servers with more than 50 busy threads. """ results = [] for series in seriesList: val = safeLast(series) if val is not None and val >= n: results.append(series) return results
python
def currentAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.threads.busy,50) Draws the servers with more than 50 busy threads. """ results = [] for series in seriesList: val = safeLast(series) if val is not None and val >= n: results.append(series) return results
[ "def", "currentAbove", "(", "requestContext", ",", "seriesList", ",", "n", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "val", "=", "safeLast", "(", "series", ")", "if", "val", "is", "not", "None", "and", "val", ">=", "n", ":", "results", ".", "append", "(", "series", ")", "return", "results" ]
Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.threads.busy,50) Draws the servers with more than 50 busy threads.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "an", "integer", "N", ".", "Out", "of", "all", "metrics", "passed", "draws", "only", "the", "metrics", "whose", "value", "is", "above", "N", "at", "the", "end", "of", "the", "time", "period", "specified", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2224-L2242
brutasse/graphite-api
graphite_api/functions.py
averageAbove
def averageAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics with an average value above N for the time period specified. Example:: &target=averageAbove(server*.instance*.threads.busy,25) Draws the servers with average values above 25. """ results = [] for series in seriesList: val = safeAvg(series) if val is not None and val >= n: results.append(series) return results
python
def averageAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics with an average value above N for the time period specified. Example:: &target=averageAbove(server*.instance*.threads.busy,25) Draws the servers with average values above 25. """ results = [] for series in seriesList: val = safeAvg(series) if val is not None and val >= n: results.append(series) return results
[ "def", "averageAbove", "(", "requestContext", ",", "seriesList", ",", "n", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "val", "=", "safeAvg", "(", "series", ")", "if", "val", "is", "not", "None", "and", "val", ">=", "n", ":", "results", ".", "append", "(", "series", ")", "return", "results" ]
Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics with an average value above N for the time period specified. Example:: &target=averageAbove(server*.instance*.threads.busy,25) Draws the servers with average values above 25.
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "followed", "by", "an", "integer", "N", ".", "Out", "of", "all", "metrics", "passed", "draws", "only", "the", "metrics", "with", "an", "average", "value", "above", "N", "for", "the", "time", "period", "specified", "." ]
train
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2298-L2316