repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.get_index
def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
python
def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
[ "def", "get_index", "(", "self", ")", ":", "ifreq", "=", "struct", ".", "pack", "(", "'16si'", ",", "self", ".", "name", ",", "0", ")", "res", "=", "fcntl", ".", "ioctl", "(", "sockfd", ",", "SIOCGIFINDEX", ",", "ifreq", ")", "return", "struct", ".", "unpack", "(", "\"16si\"", ",", "res", ")", "[", "1", "]" ]
Convert an interface name to an index value.
[ "Convert", "an", "interface", "name", "to", "an", "index", "value", "." ]
e3f16978855c6649685f0c43d4c3fcf768427ae5
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L233-L237
train
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.set_pause_param
def set_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control """ # create a struct ethtool_pauseparm # create a struct ifreq with its .ifr_data pointing at the above ecmd = array.array('B', struct.pack('IIII', ETHTOOL_SPAUSEPARAM, bool(autoneg), bool(rx_pause), bool(tx_pause))) buf_addr, _buf_len = ecmd.buffer_info() ifreq = struct.pack('16sP', self.name, buf_addr) fcntl.ioctl(sockfd, SIOCETHTOOL, ifreq)
python
def set_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control """ # create a struct ethtool_pauseparm # create a struct ifreq with its .ifr_data pointing at the above ecmd = array.array('B', struct.pack('IIII', ETHTOOL_SPAUSEPARAM, bool(autoneg), bool(rx_pause), bool(tx_pause))) buf_addr, _buf_len = ecmd.buffer_info() ifreq = struct.pack('16sP', self.name, buf_addr) fcntl.ioctl(sockfd, SIOCETHTOOL, ifreq)
[ "def", "set_pause_param", "(", "self", ",", "autoneg", ",", "rx_pause", ",", "tx_pause", ")", ":", "# create a struct ethtool_pauseparm", "# create a struct ifreq with its .ifr_data pointing at the above", "ecmd", "=", "array", ".", "array", "(", "'B'", ",", "struct", ".", "pack", "(", "'IIII'", ",", "ETHTOOL_SPAUSEPARAM", ",", "bool", "(", "autoneg", ")", ",", "bool", "(", "rx_pause", ")", ",", "bool", "(", "tx_pause", ")", ")", ")", "buf_addr", ",", "_buf_len", "=", "ecmd", ".", "buffer_info", "(", ")", "ifreq", "=", "struct", ".", "pack", "(", "'16sP'", ",", "self", ".", "name", ",", "buf_addr", ")", "fcntl", ".", "ioctl", "(", "sockfd", ",", "SIOCETHTOOL", ",", "ifreq", ")" ]
Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control
[ "Ethernet", "has", "flow", "control!", "The", "inter", "-", "frame", "pause", "can", "be", "adjusted", "by", "auto", "-", "negotiation", "through", "an", "ethernet", "frame", "type", "with", "a", "simple", "two", "-", "field", "payload", "and", "by", "setting", "it", "explicitly", "." ]
e3f16978855c6649685f0c43d4c3fcf768427ae5
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L306-L320
train
viraja1/grammar-check
setup.py
get_version
def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
python
def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "get_version", "(", ")", ":", "with", "io", ".", "open", "(", "'grammar_check/__init__.py'", ",", "encoding", "=", "'utf-8'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "return", "ast", ".", "parse", "(", "line", ")", ".", "body", "[", "0", "]", ".", "value", ".", "s" ]
Return version string.
[ "Return", "version", "string", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L129-L134
train
viraja1/grammar-check
setup.py
split_elements
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
python
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
[ "def", "split_elements", "(", "value", ")", ":", "l", "=", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ".", "split", "(", "','", ")", "]", "if", "len", "(", "l", ")", "==", "1", ":", "l", "=", "value", ".", "split", "(", ")", "return", "l" ]
Split a string with comma or space-separated elements into a list.
[ "Split", "a", "string", "with", "comma", "or", "space", "-", "separated", "elements", "into", "a", "list", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L194-L199
train
viraja1/grammar-check
setup.py
generate_py2k
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst) return dst return None def copy_data(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst) or os.path.getsize(src) != os.path.getsize(dst)): shutil.copy(src, dst) return dst return None copied_py_files = [] test_scripts = [] if not os.path.isdir(py2k_dir): os.makedirs(py2k_dir) packages_root = get_cfg_value(config, 'files', 'packages_root') for name in get_cfg_value(config, 'files', 'packages'): name = name.replace('.', os.path.sep) py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) if not os.path.isdir(py2k_path): os.makedirs(py2k_path) for fn in os.listdir(py3k_path): path = os.path.join(py3k_path, fn) if not os.path.isfile(path): continue if not os.path.splitext(path)[1].lower() == '.py': continue new_path = os.path.join(py2k_path, fn) if copy(path, new_path): copied_py_files.append(new_path) for name in get_cfg_value(config, 'files', 'modules'): name = name.replace('.', os.path.sep) + '.py' py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) dirname = os.path.dirname(py2k_path) if not os.path.isdir(dirname): os.makedirs(dirname) if copy(py3k_path, py2k_path): copied_py_files.append(py2k_path) for name in get_cfg_value(config, 'files', 'scripts'): py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) dirname = os.path.dirname(py2k_path) if not os.path.isdir(dirname): os.makedirs(dirname) if copy(py3k_path, py2k_path): copied_py_files.append(py2k_path) setup_py_path = os.path.abspath(__file__) for pattern in get_cfg_value(config, 'files', 'extra_files'): for path in glob.glob(pattern): if os.path.abspath(path) == setup_py_path: continue py2k_path = os.path.join(py2k_dir, path) py2k_dirname = os.path.dirname(py2k_path) if not os.path.isdir(py2k_dirname): os.makedirs(py2k_dirname) filename = os.path.split(path)[1] ext = os.path.splitext(filename)[1].lower() if ext == '.py': if copy(path, py2k_path): copied_py_files.append(py2k_path) else: copy_data(path, py2k_path) if (os.access(py2k_path, os.X_OK) and re.search(r"\btest\b|_test\b|\btest_", filename)): test_scripts.append(py2k_path) for package, patterns in get_package_data( get_cfg_value(config, 'files', 'package_data')).items(): for pattern in patterns: py3k_pattern = os.path.join(packages_root, package, pattern) for py3k_path in glob.glob(py3k_pattern): py2k_path = os.path.join(py2k_dir, py3k_path) py2k_dirname = os.path.dirname(py2k_path) if not os.path.isdir(py2k_dirname): os.makedirs(py2k_dirname) copy_data(py3k_path, py2k_path) if copied_py_files: copied_py_files.sort() try: run_3to2(copied_py_files) write_py2k_header(copied_py_files) except: shutil.rmtree(py2k_dir) raise if run_tests: for script in test_scripts: subprocess.check_call([script])
python
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst) return dst return None def copy_data(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst) or os.path.getsize(src) != os.path.getsize(dst)): shutil.copy(src, dst) return dst return None copied_py_files = [] test_scripts = [] if not os.path.isdir(py2k_dir): os.makedirs(py2k_dir) packages_root = get_cfg_value(config, 'files', 'packages_root') for name in get_cfg_value(config, 'files', 'packages'): name = name.replace('.', os.path.sep) py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) if not os.path.isdir(py2k_path): os.makedirs(py2k_path) for fn in os.listdir(py3k_path): path = os.path.join(py3k_path, fn) if not os.path.isfile(path): continue if not os.path.splitext(path)[1].lower() == '.py': continue new_path = os.path.join(py2k_path, fn) if copy(path, new_path): copied_py_files.append(new_path) for name in get_cfg_value(config, 'files', 'modules'): name = name.replace('.', os.path.sep) + '.py' py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) dirname = os.path.dirname(py2k_path) if not os.path.isdir(dirname): os.makedirs(dirname) if copy(py3k_path, py2k_path): copied_py_files.append(py2k_path) for name in get_cfg_value(config, 'files', 'scripts'): py3k_path = os.path.join(packages_root, name) py2k_path = os.path.join(py2k_dir, py3k_path) dirname = os.path.dirname(py2k_path) if not os.path.isdir(dirname): os.makedirs(dirname) if copy(py3k_path, py2k_path): copied_py_files.append(py2k_path) setup_py_path = os.path.abspath(__file__) for pattern in get_cfg_value(config, 'files', 'extra_files'): for path in glob.glob(pattern): if os.path.abspath(path) == setup_py_path: continue py2k_path = os.path.join(py2k_dir, path) py2k_dirname = os.path.dirname(py2k_path) if not os.path.isdir(py2k_dirname): os.makedirs(py2k_dirname) filename = os.path.split(path)[1] ext = os.path.splitext(filename)[1].lower() if ext == '.py': if copy(path, py2k_path): copied_py_files.append(py2k_path) else: copy_data(path, py2k_path) if (os.access(py2k_path, os.X_OK) and re.search(r"\btest\b|_test\b|\btest_", filename)): test_scripts.append(py2k_path) for package, patterns in get_package_data( get_cfg_value(config, 'files', 'package_data')).items(): for pattern in patterns: py3k_pattern = os.path.join(packages_root, package, pattern) for py3k_path in glob.glob(py3k_pattern): py2k_path = os.path.join(py2k_dir, py3k_path) py2k_dirname = os.path.dirname(py2k_path) if not os.path.isdir(py2k_dirname): os.makedirs(py2k_dirname) copy_data(py3k_path, py2k_path) if copied_py_files: copied_py_files.sort() try: run_3to2(copied_py_files) write_py2k_header(copied_py_files) except: shutil.rmtree(py2k_dir) raise if run_tests: for script in test_scripts: subprocess.check_call([script])
[ "def", "generate_py2k", "(", "config", ",", "py2k_dir", "=", "PY2K_DIR", ",", "run_tests", "=", "False", ")", ":", "def", "copy", "(", "src", ",", "dst", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "dst", ")", "or", "os", ".", "path", ".", "getmtime", "(", "src", ")", ">", "os", ".", "path", ".", "getmtime", "(", "dst", ")", ")", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "return", "dst", "return", "None", "def", "copy_data", "(", "src", ",", "dst", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "dst", ")", "or", "os", ".", "path", ".", "getmtime", "(", "src", ")", ">", "os", ".", "path", ".", "getmtime", "(", "dst", ")", "or", "os", ".", "path", ".", "getsize", "(", "src", ")", "!=", "os", ".", "path", ".", "getsize", "(", "dst", ")", ")", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "return", "dst", "return", "None", "copied_py_files", "=", "[", "]", "test_scripts", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "py2k_dir", ")", ":", "os", ".", "makedirs", "(", "py2k_dir", ")", "packages_root", "=", "get_cfg_value", "(", "config", ",", "'files'", ",", "'packages_root'", ")", "for", "name", "in", "get_cfg_value", "(", "config", ",", "'files'", ",", "'packages'", ")", ":", "name", "=", "name", ".", "replace", "(", "'.'", ",", "os", ".", "path", ".", "sep", ")", "py3k_path", "=", "os", ".", "path", ".", "join", "(", "packages_root", ",", "name", ")", "py2k_path", "=", "os", ".", "path", ".", "join", "(", "py2k_dir", ",", "py3k_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "py2k_path", ")", ":", "os", ".", "makedirs", "(", "py2k_path", ")", "for", "fn", "in", "os", ".", "listdir", "(", "py3k_path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "py3k_path", ",", "fn", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "splitext", "(", "path", ")", "[", "1", "]", ".", "lower", "(", ")", "==", "'.py'", ":", "continue", "new_path", "=", "os", ".", "path", ".", "join", "(", "py2k_path", ",", "fn", ")", "if", "copy", "(", "path", ",", "new_path", ")", ":", "copied_py_files", ".", "append", "(", "new_path", ")", "for", "name", "in", "get_cfg_value", "(", "config", ",", "'files'", ",", "'modules'", ")", ":", "name", "=", "name", ".", "replace", "(", "'.'", ",", "os", ".", "path", ".", "sep", ")", "+", "'.py'", "py3k_path", "=", "os", ".", "path", ".", "join", "(", "packages_root", ",", "name", ")", "py2k_path", "=", "os", ".", "path", ".", "join", "(", "py2k_dir", ",", "py3k_path", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "py2k_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "if", "copy", "(", "py3k_path", ",", "py2k_path", ")", ":", "copied_py_files", ".", "append", "(", "py2k_path", ")", "for", "name", "in", "get_cfg_value", "(", "config", ",", "'files'", ",", "'scripts'", ")", ":", "py3k_path", "=", "os", ".", "path", ".", "join", "(", "packages_root", ",", "name", ")", "py2k_path", "=", "os", ".", "path", ".", "join", "(", "py2k_dir", ",", "py3k_path", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "py2k_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "if", "copy", "(", "py3k_path", ",", "py2k_path", ")", ":", "copied_py_files", ".", "append", "(", "py2k_path", ")", "setup_py_path", "=", "os", ".", "path", ".", "abspath", "(", "__file__", ")", "for", "pattern", "in", "get_cfg_value", "(", "config", ",", "'files'", ",", "'extra_files'", ")", ":", "for", "path", "in", "glob", ".", "glob", "(", "pattern", ")", ":", "if", "os", ".", "path", ".", "abspath", "(", "path", ")", "==", "setup_py_path", ":", "continue", "py2k_path", "=", "os", ".", "path", ".", "join", "(", "py2k_dir", ",", "path", ")", "py2k_dirname", "=", "os", ".", "path", ".", "dirname", "(", "py2k_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "py2k_dirname", ")", ":", "os", ".", "makedirs", "(", "py2k_dirname", ")", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "ext", "==", "'.py'", ":", "if", "copy", "(", "path", ",", "py2k_path", ")", ":", "copied_py_files", ".", "append", "(", "py2k_path", ")", "else", ":", "copy_data", "(", "path", ",", "py2k_path", ")", "if", "(", "os", ".", "access", "(", "py2k_path", ",", "os", ".", "X_OK", ")", "and", "re", ".", "search", "(", "r\"\\btest\\b|_test\\b|\\btest_\"", ",", "filename", ")", ")", ":", "test_scripts", ".", "append", "(", "py2k_path", ")", "for", "package", ",", "patterns", "in", "get_package_data", "(", "get_cfg_value", "(", "config", ",", "'files'", ",", "'package_data'", ")", ")", ".", "items", "(", ")", ":", "for", "pattern", "in", "patterns", ":", "py3k_pattern", "=", "os", ".", "path", ".", "join", "(", "packages_root", ",", "package", ",", "pattern", ")", "for", "py3k_path", "in", "glob", ".", "glob", "(", "py3k_pattern", ")", ":", "py2k_path", "=", "os", ".", "path", ".", "join", "(", "py2k_dir", ",", "py3k_path", ")", "py2k_dirname", "=", "os", ".", "path", ".", "dirname", "(", "py2k_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "py2k_dirname", ")", ":", "os", ".", "makedirs", "(", "py2k_dirname", ")", "copy_data", "(", "py3k_path", ",", "py2k_path", ")", "if", "copied_py_files", ":", "copied_py_files", ".", "sort", "(", ")", "try", ":", "run_3to2", "(", "copied_py_files", ")", "write_py2k_header", "(", "copied_py_files", ")", "except", ":", "shutil", ".", "rmtree", "(", "py2k_dir", ")", "raise", "if", "run_tests", ":", "for", "script", "in", "test_scripts", ":", "subprocess", ".", "check_call", "(", "[", "script", "]", ")" ]
Generate Python 2 code from Python 3 code.
[ "Generate", "Python", "2", "code", "from", "Python", "3", "code", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L448-L551
train
viraja1/grammar-check
setup.py
default_hook
def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('build') or arg.startswith('bdist') for arg in sys.argv): generate_py2k(config) packages_root = get_cfg_value(config, 'files', 'packages_root') packages_root = os.path.join(PY2K_DIR, packages_root) set_cfg_value(config, 'files', 'packages_root', packages_root)
python
def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('build') or arg.startswith('bdist') for arg in sys.argv): generate_py2k(config) packages_root = get_cfg_value(config, 'files', 'packages_root') packages_root = os.path.join(PY2K_DIR, packages_root) set_cfg_value(config, 'files', 'packages_root', packages_root)
[ "def", "default_hook", "(", "config", ")", ":", "if", "(", "any", "(", "arg", ".", "startswith", "(", "'bdist'", ")", "for", "arg", "in", "sys", ".", "argv", ")", "and", "os", ".", "path", ".", "isdir", "(", "PY2K_DIR", ")", "!=", "IS_PY2K", "and", "os", ".", "path", ".", "isdir", "(", "LIB_DIR", ")", ")", ":", "shutil", ".", "rmtree", "(", "LIB_DIR", ")", "if", "IS_PY2K", "and", "any", "(", "arg", ".", "startswith", "(", "'install'", ")", "or", "arg", ".", "startswith", "(", "'build'", ")", "or", "arg", ".", "startswith", "(", "'bdist'", ")", "for", "arg", "in", "sys", ".", "argv", ")", ":", "generate_py2k", "(", "config", ")", "packages_root", "=", "get_cfg_value", "(", "config", ",", "'files'", ",", "'packages_root'", ")", "packages_root", "=", "os", ".", "path", ".", "join", "(", "PY2K_DIR", ",", "packages_root", ")", "set_cfg_value", "(", "config", ",", "'files'", ",", "'packages_root'", ",", "packages_root", ")" ]
Default setup hook.
[ "Default", "setup", "hook", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L566-L578
train
rlisagor/pynetlinux
pynetlinux/route.py
get_default_if
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass return interf
python
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass return interf
[ "def", "get_default_if", "(", ")", ":", "f", "=", "open", "(", "'/proc/net/route'", ",", "'r'", ")", "for", "line", "in", "f", ":", "words", "=", "line", ".", "split", "(", ")", "dest", "=", "words", "[", "1", "]", "try", ":", "if", "(", "int", "(", "dest", ")", "==", "0", ")", ":", "interf", "=", "words", "[", "0", "]", "break", "except", "ValueError", ":", "pass", "return", "interf" ]
Returns the default interface
[ "Returns", "the", "default", "interface" ]
e3f16978855c6649685f0c43d4c3fcf768427ae5
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L1-L13
train
rlisagor/pynetlinux
pynetlinux/route.py
get_default_gw
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] break except ValueError: pass if not gw_from_route: return None for i in range(8, 1, -2): octet = gw_from_route[i-2:i] octet = int(octet, 16) octet_list.append(str(octet)) gw_ip = ".".join(octet_list) return gw_ip
python
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] break except ValueError: pass if not gw_from_route: return None for i in range(8, 1, -2): octet = gw_from_route[i-2:i] octet = int(octet, 16) octet_list.append(str(octet)) gw_ip = ".".join(octet_list) return gw_ip
[ "def", "get_default_gw", "(", ")", ":", "octet_list", "=", "[", "]", "gw_from_route", "=", "None", "f", "=", "open", "(", "'/proc/net/route'", ",", "'r'", ")", "for", "line", "in", "f", ":", "words", "=", "line", ".", "split", "(", ")", "dest", "=", "words", "[", "1", "]", "try", ":", "if", "(", "int", "(", "dest", ")", "==", "0", ")", ":", "gw_from_route", "=", "words", "[", "2", "]", "break", "except", "ValueError", ":", "pass", "if", "not", "gw_from_route", ":", "return", "None", "for", "i", "in", "range", "(", "8", ",", "1", ",", "-", "2", ")", ":", "octet", "=", "gw_from_route", "[", "i", "-", "2", ":", "i", "]", "octet", "=", "int", "(", "octet", ",", "16", ")", "octet_list", ".", "append", "(", "str", "(", "octet", ")", ")", "gw_ip", "=", "\".\"", ".", "join", "(", "octet_list", ")", "return", "gw_ip" ]
Returns the default gateway
[ "Returns", "the", "default", "gateway" ]
e3f16978855c6649685f0c43d4c3fcf768427ae5
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L15-L40
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
init
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init_types: raise GraphiteSendException( "Invalid init_type '%s', must be one of: %s" % (init_type, ", ".join(validate_init_types))) # Use TCP to send data to the plain text receiver on the graphite server. if init_type in ['plaintext_tcp', 'plaintext', 'plain']: _module_instance = GraphiteClient(*args, **kwargs) # Use TCP to send pickled data to the pickle receiver on the graphite # server. if init_type in ['pickle_tcp', 'pickle']: _module_instance = GraphitePickleClient(*args, **kwargs) return _module_instance
python
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init_types: raise GraphiteSendException( "Invalid init_type '%s', must be one of: %s" % (init_type, ", ".join(validate_init_types))) # Use TCP to send data to the plain text receiver on the graphite server. if init_type in ['plaintext_tcp', 'plaintext', 'plain']: _module_instance = GraphiteClient(*args, **kwargs) # Use TCP to send pickled data to the pickle receiver on the graphite # server. if init_type in ['pickle_tcp', 'pickle']: _module_instance = GraphitePickleClient(*args, **kwargs) return _module_instance
[ "def", "init", "(", "init_type", "=", "'plaintext_tcp'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_module_instance", "reset", "(", ")", "validate_init_types", "=", "[", "'plaintext_tcp'", ",", "'plaintext'", ",", "'pickle_tcp'", ",", "'pickle'", ",", "'plain'", "]", "if", "init_type", "not", "in", "validate_init_types", ":", "raise", "GraphiteSendException", "(", "\"Invalid init_type '%s', must be one of: %s\"", "%", "(", "init_type", ",", "\", \"", ".", "join", "(", "validate_init_types", ")", ")", ")", "# Use TCP to send data to the plain text receiver on the graphite server.", "if", "init_type", "in", "[", "'plaintext_tcp'", ",", "'plaintext'", ",", "'plain'", "]", ":", "_module_instance", "=", "GraphiteClient", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Use TCP to send pickled data to the pickle receiver on the graphite", "# server.", "if", "init_type", "in", "[", "'pickle_tcp'", ",", "'pickle'", "]", ":", "_module_instance", "=", "GraphitePickleClient", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_module_instance" ]
Create the module instance of the GraphiteClient.
[ "Create", "the", "module", "instance", "of", "the", "GraphiteClient", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L526-L550
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
send
def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send(*args, **kwargs) return _module_instance
python
def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send(*args, **kwargs) return _module_instance
[ "def", "send", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_module_instance" ]
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L553-L563
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
send_dict
def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send_dict(*args, **kwargs) return _module_instance
python
def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send_dict(*args, **kwargs) return _module_instance
[ "def", "send_dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send_dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_module_instance" ]
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L566-L575
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
send_list
def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send_list(*args, **kwargs) return _module_instance
python
def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_instance.send_list(*args, **kwargs) return _module_instance
[ "def", "send_list", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send_list", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_module_instance" ]
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L578-L587
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
cli
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='name.of.metric') parser.add_argument('value', metavar='value', type=int, help='value of metric as int') args = parser.parse_args() metric = args.metric value = args.value graphitesend_instance = init() graphitesend_instance.send(metric, value)
python
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='name.of.metric') parser.add_argument('value', metavar='value', type=int, help='value of metric as int') args = parser.parse_args() metric = args.metric value = args.value graphitesend_instance = init() graphitesend_instance.send(metric, value)
[ "def", "cli", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Send data to graphite'", ")", "# Core of the application is to accept a metric and a value.", "parser", ".", "add_argument", "(", "'metric'", ",", "metavar", "=", "'metric'", ",", "type", "=", "str", ",", "help", "=", "'name.of.metric'", ")", "parser", ".", "add_argument", "(", "'value'", ",", "metavar", "=", "'value'", ",", "type", "=", "int", ",", "help", "=", "'value of metric as int'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "metric", "=", "args", ".", "metric", "value", "=", "args", ".", "value", "graphitesend_instance", "=", "init", "(", ")", "graphitesend_instance", ".", "send", "(", "metric", ",", "value", ")" ]
Allow the module to be called from the cli.
[ "Allow", "the", "module", "to", "be", "called", "from", "the", "cli", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L600-L617
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.connect
def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise GraphiteSendException( "Took over %d second(s) to connect to %s" % (self.timeout_in_seconds, self.addr)) except socket.gaierror: raise GraphiteSendException( "No address associated with hostname %s:%s" % self.addr) except Exception as error: raise GraphiteSendException( "unknown exception while connecting to %s - %s" % (self.addr, error) ) return self.socket
python
def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise GraphiteSendException( "Took over %d second(s) to connect to %s" % (self.timeout_in_seconds, self.addr)) except socket.gaierror: raise GraphiteSendException( "No address associated with hostname %s:%s" % self.addr) except Exception as error: raise GraphiteSendException( "unknown exception while connecting to %s - %s" % (self.addr, error) ) return self.socket
[ "def", "connect", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", ")", "self", ".", "socket", ".", "settimeout", "(", "self", ".", "timeout_in_seconds", ")", "try", ":", "self", ".", "socket", ".", "connect", "(", "self", ".", "addr", ")", "except", "socket", ".", "timeout", ":", "raise", "GraphiteSendException", "(", "\"Took over %d second(s) to connect to %s\"", "%", "(", "self", ".", "timeout_in_seconds", ",", "self", ".", "addr", ")", ")", "except", "socket", ".", "gaierror", ":", "raise", "GraphiteSendException", "(", "\"No address associated with hostname %s:%s\"", "%", "self", ".", "addr", ")", "except", "Exception", "as", "error", ":", "raise", "GraphiteSendException", "(", "\"unknown exception while connecting to %s - %s\"", "%", "(", "self", ".", "addr", ",", "error", ")", ")", "return", "self", ".", "socket" ]
Make a TCP connection to the graphite server on port self.port
[ "Make", "a", "TCP", "connection", "to", "the", "graphite", "server", "on", "port", "self", ".", "port" ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L148-L169
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.autoreconnect
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5): """ Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and random delay in range 1..`jitter` (exponential backoff) :param sleep: time to sleep between two attempts to reconnect :type sleep: float or int :param attempt: maximal number of attempts :type attempt: int :param exponential: if set - use exponential backoff logic :type exponential: bool :param jitter: top value of random delay, sec :type jitter: int """ p = 0 while attempt is None or attempt > 0: try: self.reconnect() return True except GraphiteSendException: if exponential: p += 1 time.sleep(pow(sleep, p) + random.randint(1, jitter)) else: time.sleep(sleep) attempt -= 1 return False
python
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5): """ Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and random delay in range 1..`jitter` (exponential backoff) :param sleep: time to sleep between two attempts to reconnect :type sleep: float or int :param attempt: maximal number of attempts :type attempt: int :param exponential: if set - use exponential backoff logic :type exponential: bool :param jitter: top value of random delay, sec :type jitter: int """ p = 0 while attempt is None or attempt > 0: try: self.reconnect() return True except GraphiteSendException: if exponential: p += 1 time.sleep(pow(sleep, p) + random.randint(1, jitter)) else: time.sleep(sleep) attempt -= 1 return False
[ "def", "autoreconnect", "(", "self", ",", "sleep", "=", "1", ",", "attempt", "=", "3", ",", "exponential", "=", "True", ",", "jitter", "=", "5", ")", ":", "p", "=", "0", "while", "attempt", "is", "None", "or", "attempt", ">", "0", ":", "try", ":", "self", ".", "reconnect", "(", ")", "return", "True", "except", "GraphiteSendException", ":", "if", "exponential", ":", "p", "+=", "1", "time", ".", "sleep", "(", "pow", "(", "sleep", ",", "p", ")", "+", "random", ".", "randint", "(", "1", ",", "jitter", ")", ")", "else", ":", "time", ".", "sleep", "(", "sleep", ")", "attempt", "-=", "1", "return", "False" ]
Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and random delay in range 1..`jitter` (exponential backoff) :param sleep: time to sleep between two attempts to reconnect :type sleep: float or int :param attempt: maximal number of attempts :type attempt: int :param exponential: if set - use exponential backoff logic :type exponential: bool :param jitter: top value of random delay, sec :type jitter: int
[ "Tries", "to", "reconnect", "with", "some", "delay", ":" ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L175-L213
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.disconnect
def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket = None # Set the self.socket to None, no matter what. finally: self.socket = None
python
def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket = None # Set the self.socket to None, no matter what. finally: self.socket = None
[ "def", "disconnect", "(", "self", ")", ":", "try", ":", "self", ".", "socket", ".", "shutdown", "(", "1", ")", "# If its currently a socket, set it to None", "except", "AttributeError", ":", "self", ".", "socket", "=", "None", "except", "Exception", ":", "self", ".", "socket", "=", "None", "# Set the self.socket to None, no matter what.", "finally", ":", "self", ".", "socket", "=", "None" ]
Close the TCP connection with the graphite server.
[ "Close", "the", "TCP", "connection", "with", "the", "graphite", "server", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L221-L236
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient._dispatch_send
def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_function = self._send if self._autoreconnect: sending_function = self._send_and_reconnect try: if self.asynchronous and gevent: gevent.spawn(sending_function, message) else: sending_function(message) except Exception as e: self._handle_send_error(e) return "sent {0} long message: {1}".format(len(message), message[:75])
python
def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_function = self._send if self._autoreconnect: sending_function = self._send_and_reconnect try: if self.asynchronous and gevent: gevent.spawn(sending_function, message) else: sending_function(message) except Exception as e: self._handle_send_error(e) return "sent {0} long message: {1}".format(len(message), message[:75])
[ "def", "_dispatch_send", "(", "self", ",", "message", ")", ":", "if", "self", ".", "dryrun", ":", "return", "message", "if", "not", "self", ".", "socket", ":", "raise", "GraphiteSendException", "(", "\"Socket was not created before send\"", ")", "sending_function", "=", "self", ".", "_send", "if", "self", ".", "_autoreconnect", ":", "sending_function", "=", "self", ".", "_send_and_reconnect", "try", ":", "if", "self", ".", "asynchronous", "and", "gevent", ":", "gevent", ".", "spawn", "(", "sending_function", ",", "message", ")", "else", ":", "sending_function", "(", "message", ")", "except", "Exception", "as", "e", ":", "self", ".", "_handle_send_error", "(", "e", ")", "return", "\"sent {0} long message: {1}\"", ".", "format", "(", "len", "(", "message", ")", ",", "message", "[", ":", "75", "]", ")" ]
Dispatch the different steps of sending
[ "Dispatch", "the", "different", "steps", "of", "sending" ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L238-L263
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient._send_and_reconnect
def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid. """ try: self.socket.sendall(message.encode("ascii")) except (AttributeError, socket.error): if not self.autoreconnect(): raise else: self.socket.sendall(message.encode("ascii"))
python
def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid. """ try: self.socket.sendall(message.encode("ascii")) except (AttributeError, socket.error): if not self.autoreconnect(): raise else: self.socket.sendall(message.encode("ascii"))
[ "def", "_send_and_reconnect", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "socket", ".", "sendall", "(", "message", ".", "encode", "(", "\"ascii\"", ")", ")", "except", "(", "AttributeError", ",", "socket", ".", "error", ")", ":", "if", "not", "self", ".", "autoreconnect", "(", ")", ":", "raise", "else", ":", "self", ".", "socket", ".", "sendall", "(", "message", ".", "encode", "(", "\"ascii\"", ")", ")" ]
Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid.
[ "Send", "_message_", "to", "Graphite", "Server", "and", "attempt", "reconnect", "on", "failure", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L292-L307
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.send
def send(self, metric, value, timestamp=None, formatter=None): """ Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send("metric", 54) .. code-block:: python >>> g = init() >>> g.send(metric="metricname", value=73) """ if formatter is None: formatter = self.formatter message = formatter(metric, value, timestamp) message = self. _presend(message) return self._dispatch_send(message)
python
def send(self, metric, value, timestamp=None, formatter=None): """ Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send("metric", 54) .. code-block:: python >>> g = init() >>> g.send(metric="metricname", value=73) """ if formatter is None: formatter = self.formatter message = formatter(metric, value, timestamp) message = self. _presend(message) return self._dispatch_send(message)
[ "def", "send", "(", "self", ",", "metric", ",", "value", ",", "timestamp", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "formatter", "=", "self", ".", "formatter", "message", "=", "formatter", "(", "metric", ",", "value", ",", "timestamp", ")", "message", "=", "self", ".", "_presend", "(", "message", ")", "return", "self", ".", "_dispatch_send", "(", "message", ")" ]
Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send("metric", 54) .. code-block:: python >>> g = init() >>> g.send(metric="metricname", value=73)
[ "Format", "a", "single", "metric", "/", "value", "pair", "and", "send", "it", "to", "the", "graphite", "server", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L316-L345
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.send_dict
def send_dict(self, data, timestamp=None, formatter=None): """ Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send_dict({'metric1': 54, 'metric2': 43, 'metricN': 999}) """ if formatter is None: formatter = self.formatter metric_list = [] for metric, value in data.items(): tmp_message = formatter(metric, value, timestamp) metric_list.append(tmp_message) message = "".join(metric_list) return self._dispatch_send(message)
python
def send_dict(self, data, timestamp=None, formatter=None): """ Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send_dict({'metric1': 54, 'metric2': 43, 'metricN': 999}) """ if formatter is None: formatter = self.formatter metric_list = [] for metric, value in data.items(): tmp_message = formatter(metric, value, timestamp) metric_list.append(tmp_message) message = "".join(metric_list) return self._dispatch_send(message)
[ "def", "send_dict", "(", "self", ",", "data", ",", "timestamp", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "formatter", "=", "self", ".", "formatter", "metric_list", "=", "[", "]", "for", "metric", ",", "value", "in", "data", ".", "items", "(", ")", ":", "tmp_message", "=", "formatter", "(", "metric", ",", "value", ",", "timestamp", ")", "metric_list", ".", "append", "(", "tmp_message", ")", "message", "=", "\"\"", ".", "join", "(", "metric_list", ")", "return", "self", ".", "_dispatch_send", "(", "message", ")" ]
Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default formatter :type prefix: callable .. code-block:: python >>> g = init() >>> g.send_dict({'metric1': 54, 'metric2': 43, 'metricN': 999})
[ "Format", "a", "dict", "of", "metric", "/", "values", "pairs", "and", "send", "them", "all", "to", "the", "graphite", "server", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L347-L375
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.enable_asynchronous
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): return "socket" in monkey.saved return gevent.socket.socket == socket.socket if not is_monkey_patched(): raise Exception("To activate asynchonoucity, please monkey patch" " the socket module with gevent") return True
python
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): return "socket" in monkey.saved return gevent.socket.socket == socket.socket if not is_monkey_patched(): raise Exception("To activate asynchonoucity, please monkey patch" " the socket module with gevent") return True
[ "def", "enable_asynchronous", "(", "self", ")", ":", "def", "is_monkey_patched", "(", ")", ":", "try", ":", "from", "gevent", "import", "monkey", ",", "socket", "except", "ImportError", ":", "return", "False", "if", "hasattr", "(", "monkey", ",", "\"saved\"", ")", ":", "return", "\"socket\"", "in", "monkey", ".", "saved", "return", "gevent", ".", "socket", ".", "socket", "==", "socket", ".", "socket", "if", "not", "is_monkey_patched", "(", ")", ":", "raise", "Exception", "(", "\"To activate asynchonoucity, please monkey patch\"", "\" the socket module with gevent\"", ")", "return", "True" ]
Check if socket have been monkey patched by gevent
[ "Check", "if", "socket", "have", "been", "monkey", "patched", "by", "gevent" ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L425-L440
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphitePickleClient.str2listtuple
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_message += "\n" tpl_list = [] for line in string_message.split('\n'): line = line.strip() if not line: continue path, metric, timestamp = (None, None, None) try: (path, metric, timestamp) = line.split() except ValueError: raise ValueError( "message must contain - metric_name, value and timestamp '%s'" % line) try: timestamp = float(timestamp) except ValueError: raise ValueError("Timestamp must be float or int") tpl_list.append((path, (timestamp, metric))) if len(tpl_list) == 0: raise GraphiteSendException("No messages to send") payload = pickle.dumps(tpl_list) header = struct.pack("!L", len(payload)) message = header + payload return message
python
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_message += "\n" tpl_list = [] for line in string_message.split('\n'): line = line.strip() if not line: continue path, metric, timestamp = (None, None, None) try: (path, metric, timestamp) = line.split() except ValueError: raise ValueError( "message must contain - metric_name, value and timestamp '%s'" % line) try: timestamp = float(timestamp) except ValueError: raise ValueError("Timestamp must be float or int") tpl_list.append((path, (timestamp, metric))) if len(tpl_list) == 0: raise GraphiteSendException("No messages to send") payload = pickle.dumps(tpl_list) header = struct.pack("!L", len(payload)) message = header + payload return message
[ "def", "str2listtuple", "(", "self", ",", "string_message", ")", ":", "if", "type", "(", "string_message", ")", ".", "__name__", "not", "in", "(", "'str'", ",", "'unicode'", ")", ":", "raise", "TypeError", "(", "\"Must provide a string or unicode\"", ")", "if", "not", "string_message", ".", "endswith", "(", "'\\n'", ")", ":", "string_message", "+=", "\"\\n\"", "tpl_list", "=", "[", "]", "for", "line", "in", "string_message", ".", "split", "(", "'\\n'", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "path", ",", "metric", ",", "timestamp", "=", "(", "None", ",", "None", ",", "None", ")", "try", ":", "(", "path", ",", "metric", ",", "timestamp", ")", "=", "line", ".", "split", "(", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"message must contain - metric_name, value and timestamp '%s'\"", "%", "line", ")", "try", ":", "timestamp", "=", "float", "(", "timestamp", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Timestamp must be float or int\"", ")", "tpl_list", ".", "append", "(", "(", "path", ",", "(", "timestamp", ",", "metric", ")", ")", ")", "if", "len", "(", "tpl_list", ")", "==", "0", ":", "raise", "GraphiteSendException", "(", "\"No messages to send\"", ")", "payload", "=", "pickle", ".", "dumps", "(", "tpl_list", ")", "header", "=", "struct", ".", "pack", "(", "\"!L\"", ",", "len", "(", "payload", ")", ")", "message", "=", "header", "+", "payload", "return", "message" ]
Covert a string that is ready to be sent to graphite into a tuple
[ "Covert", "a", "string", "that", "is", "ready", "to", "be", "sent", "to", "graphite", "into", "a", "tuple" ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L455-L490
train
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphitePickleClient._send
def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message) try: self.socket.sendall(message) # Capture missing socket. except socket.gaierror as error: raise GraphiteSendException( "Failed to send data to %s, with error: %s" % (self.addr, error)) # noqa # Capture socket closure before send. except socket.error as error: raise GraphiteSendException( "Socket closed before able to send data to %s, " "with error: %s" % (self.addr, error)) # noqa except Exception as error: raise GraphiteSendException( "Unknown error while trying to send data down socket to %s, " "error: %s" % (self.addr, error)) # noqa return "sent %d long pickled message" % len(message)
python
def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message) try: self.socket.sendall(message) # Capture missing socket. except socket.gaierror as error: raise GraphiteSendException( "Failed to send data to %s, with error: %s" % (self.addr, error)) # noqa # Capture socket closure before send. except socket.error as error: raise GraphiteSendException( "Socket closed before able to send data to %s, " "with error: %s" % (self.addr, error)) # noqa except Exception as error: raise GraphiteSendException( "Unknown error while trying to send data down socket to %s, " "error: %s" % (self.addr, error)) # noqa return "sent %d long pickled message" % len(message)
[ "def", "_send", "(", "self", ",", "message", ")", ":", "# An option to lowercase the entire message", "if", "self", ".", "lowercase_metric_names", ":", "message", "=", "message", ".", "lower", "(", ")", "# convert the message into a pickled payload.", "message", "=", "self", ".", "str2listtuple", "(", "message", ")", "try", ":", "self", ".", "socket", ".", "sendall", "(", "message", ")", "# Capture missing socket.", "except", "socket", ".", "gaierror", "as", "error", ":", "raise", "GraphiteSendException", "(", "\"Failed to send data to %s, with error: %s\"", "%", "(", "self", ".", "addr", ",", "error", ")", ")", "# noqa", "# Capture socket closure before send.", "except", "socket", ".", "error", "as", "error", ":", "raise", "GraphiteSendException", "(", "\"Socket closed before able to send data to %s, \"", "\"with error: %s\"", "%", "(", "self", ".", "addr", ",", "error", ")", ")", "# noqa", "except", "Exception", "as", "error", ":", "raise", "GraphiteSendException", "(", "\"Unknown error while trying to send data down socket to %s, \"", "\"error: %s\"", "%", "(", "self", ".", "addr", ",", "error", ")", ")", "# noqa", "return", "\"sent %d long pickled message\"", "%", "len", "(", "message", ")" ]
Given a message send it to the graphite server.
[ "Given", "a", "message", "send", "it", "to", "the", "graphite", "server", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L492-L523
train
daniellawrence/graphitesend
graphitesend/formatter.py
GraphiteStructuredFormatter.clean_metric_name
def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: metric_name = metric_name.replace(_from, _to) return metric_name
python
def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: metric_name = metric_name.replace(_from, _to) return metric_name
[ "def", "clean_metric_name", "(", "self", ",", "metric_name", ")", ":", "if", "not", "self", ".", "_clean_metric_name", ":", "return", "metric_name", "metric_name", "=", "str", "(", "metric_name", ")", "for", "_from", ",", "_to", "in", "self", ".", "cleaning_replacement_list", ":", "metric_name", "=", "metric_name", ".", "replace", "(", "_from", ",", "_to", ")", "return", "metric_name" ]
Make sure the metric is free of control chars, spaces, tabs, etc.
[ "Make", "sure", "the", "metric", "is", "free", "of", "control", "chars", "spaces", "tabs", "etc", "." ]
02281263e642f9b6e146886d4544e1d7aebd7753
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/formatter.py#L69-L78
train
viraja1/grammar-check
grammar_check/__init__.py
LanguageTool._get_languages
def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() for e in cls._get_root(url, num_tries=1): languages.add(e.get('abbr')) languages.add(e.get('abbrWithVariant')) return languages
python
def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() for e in cls._get_root(url, num_tries=1): languages.add(e.get('abbr')) languages.add(e.get('abbrWithVariant')) return languages
[ "def", "_get_languages", "(", "cls", ")", "->", "set", ":", "if", "not", "cls", ".", "_server_is_alive", "(", ")", ":", "cls", ".", "_start_server_on_free_port", "(", ")", "url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "cls", ".", "_url", ",", "'Languages'", ")", "languages", "=", "set", "(", ")", "for", "e", "in", "cls", ".", "_get_root", "(", "url", ",", "num_tries", "=", "1", ")", ":", "languages", ".", "add", "(", "e", ".", "get", "(", "'abbr'", ")", ")", "languages", ".", "add", "(", "e", ".", "get", "(", "'abbrWithVariant'", ")", ")", "return", "languages" ]
Get supported languages (by querying the server).
[ "Get", "supported", "languages", "(", "by", "querying", "the", "server", ")", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/grammar_check/__init__.py#L277-L286
train
viraja1/grammar-check
grammar_check/__init__.py
LanguageTool._get_attrib
def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tries=1) return root.attrib
python
def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tries=1) return root.attrib
[ "def", "_get_attrib", "(", "cls", ")", ":", "if", "not", "cls", ".", "_server_is_alive", "(", ")", ":", "cls", ".", "_start_server_on_free_port", "(", ")", "params", "=", "{", "'language'", ":", "FAILSAFE_LANGUAGE", ",", "'text'", ":", "''", "}", "data", "=", "urllib", ".", "parse", ".", "urlencode", "(", "params", ")", ".", "encode", "(", ")", "root", "=", "cls", ".", "_get_root", "(", "cls", ".", "_url", ",", "data", ",", "num_tries", "=", "1", ")", "return", "root", ".", "attrib" ]
Get matches element attributes.
[ "Get", "matches", "element", "attributes", "." ]
103bf27119b85b4ef26c8f8d4089b6c882cabe5c
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/grammar_check/__init__.py#L289-L296
train
nephila/djangocms-page-meta
djangocms_page_meta/admin.py
get_form
def get_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty. """ language = get_language_from_request(request, obj) form = _BASE_PAGEADMIN__GET_FORM(self, request, obj, **kwargs) if not obj or not obj.get_meta_description(language=language): form.base_fields.pop('meta_description', None) return form
python
def get_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty. """ language = get_language_from_request(request, obj) form = _BASE_PAGEADMIN__GET_FORM(self, request, obj, **kwargs) if not obj or not obj.get_meta_description(language=language): form.base_fields.pop('meta_description', None) return form
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "language", "=", "get_language_from_request", "(", "request", ",", "obj", ")", "form", "=", "_BASE_PAGEADMIN__GET_FORM", "(", "self", ",", "request", ",", "obj", ",", "*", "*", "kwargs", ")", "if", "not", "obj", "or", "not", "obj", ".", "get_meta_description", "(", "language", "=", "language", ")", ":", "form", ".", "base_fields", ".", "pop", "(", "'meta_description'", ",", "None", ")", "return", "form" ]
Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty.
[ "Patched", "method", "for", "PageAdmin", ".", "get_form", "." ]
a38efe3fe3a717d9ad91bfc6aacab90989cd04a4
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/admin.py#L91-L106
train
nephila/djangocms-page-meta
djangocms_page_meta/utils.py
get_cache_key
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, site_id)
python
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, site_id)
[ "def", "get_cache_key", "(", "page", ",", "language", ")", ":", "from", "cms", ".", "cache", "import", "_get_cache_key", "try", ":", "site_id", "=", "page", ".", "node", ".", "site_id", "except", "AttributeError", ":", "# CMS_3_4", "site_id", "=", "page", ".", "site_id", "return", "_get_cache_key", "(", "'page_meta'", ",", "page", ",", "language", ",", "site_id", ")" ]
Create the cache key for the current page and language
[ "Create", "the", "cache", "key", "for", "the", "current", "page", "and", "language" ]
a38efe3fe3a717d9ad91bfc6aacab90989cd04a4
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/utils.py#L10-L19
train
nephila/djangocms-page-meta
djangocms_page_meta/utils.py
get_page_meta
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from .models import PageMeta, TitleMeta try: meta_key = get_cache_key(page, language) except AttributeError: return None gplus_server = 'https://plus.google.com' meta = cache.get(meta_key) if not meta: meta = Meta() title = page.get_title_obj(language) meta.extra_custom_props = [] meta.title = page.get_page_title(language) if not meta.title: meta.title = page.get_title(language) if title.meta_description: meta.description = title.meta_description.strip() try: titlemeta = title.titlemeta if titlemeta.description: meta.description = titlemeta.description.strip() if titlemeta.keywords: meta.keywords = titlemeta.keywords.strip().split(',') meta.locale = titlemeta.locale meta.og_description = titlemeta.og_description.strip() if not meta.og_description: meta.og_description = meta.description meta.twitter_description = titlemeta.twitter_description.strip() if not meta.twitter_description: meta.twitter_description = meta.description meta.gplus_description = titlemeta.gplus_description.strip() if not meta.gplus_description: meta.gplus_description = meta.description if titlemeta.image: meta.image = title.titlemeta.image.canonical_url or title.titlemeta.image.url for item in titlemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except (TitleMeta.DoesNotExist, AttributeError): # Skipping title-level metas if meta.description: meta.og_description = meta.description meta.twitter_description = meta.description meta.gplus_description = meta.description defaults = { 'object_type': meta_settings.FB_TYPE, 'og_type': meta_settings.FB_TYPE, 'og_app_id': meta_settings.FB_APPID, 'fb_pages': meta_settings.FB_PAGES, 'og_profile_id': meta_settings.FB_PROFILE_ID, 'og_publisher': meta_settings.FB_PUBLISHER, 'og_author_url': meta_settings.FB_AUTHOR_URL, 'twitter_type': meta_settings.TWITTER_TYPE, 'twitter_site': meta_settings.TWITTER_SITE, 'twitter_author': meta_settings.TWITTER_AUTHOR, 'gplus_type': meta_settings.GPLUS_TYPE, 'gplus_author': meta_settings.GPLUS_AUTHOR, } try: pagemeta = page.pagemeta meta.object_type = pagemeta.og_type meta.og_type = pagemeta.og_type meta.og_app_id = pagemeta.og_app_id meta.fb_pages = pagemeta.fb_pages meta.og_profile_id = pagemeta.og_author_fbid meta.twitter_type = pagemeta.twitter_type meta.twitter_site = pagemeta.twitter_site meta.twitter_author = pagemeta.twitter_author meta.gplus_type = pagemeta.gplus_type meta.gplus_author = pagemeta.gplus_author if meta.og_type == 'article': meta.og_publisher = pagemeta.og_publisher meta.og_author_url = pagemeta.og_author_url try: from djangocms_page_tags.utils import get_title_tags, get_page_tags tags = list(get_title_tags(page, language)) tags += list(get_page_tags(page)) meta.tag = ','.join([tag.name for tag in tags]) except ImportError: # djangocms-page-tags not available pass if not meta.image and pagemeta.image: meta.image = pagemeta.image.canonical_url or pagemeta.image.url for item in pagemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except PageMeta.DoesNotExist: pass if meta.gplus_author and not meta.gplus_author.startswith('http'): if not meta.gplus_author.startswith('/'): meta.gplus_author = '{0}/{1}'.format(gplus_server, meta.gplus_author) else: meta.gplus_author = '{0}{1}'.format(gplus_server, meta.gplus_author) if page.publication_date: meta.published_time = page.publication_date.isoformat() if page.changed_date: meta.modified_time = page.changed_date.isoformat() if page.publication_end_date: meta.expiration_time = page.publication_end_date.isoformat() for attr, val in defaults.items(): if not getattr(meta, attr, '') and val: setattr(meta, attr, val) meta.url = page.get_absolute_url(language) return meta
python
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from .models import PageMeta, TitleMeta try: meta_key = get_cache_key(page, language) except AttributeError: return None gplus_server = 'https://plus.google.com' meta = cache.get(meta_key) if not meta: meta = Meta() title = page.get_title_obj(language) meta.extra_custom_props = [] meta.title = page.get_page_title(language) if not meta.title: meta.title = page.get_title(language) if title.meta_description: meta.description = title.meta_description.strip() try: titlemeta = title.titlemeta if titlemeta.description: meta.description = titlemeta.description.strip() if titlemeta.keywords: meta.keywords = titlemeta.keywords.strip().split(',') meta.locale = titlemeta.locale meta.og_description = titlemeta.og_description.strip() if not meta.og_description: meta.og_description = meta.description meta.twitter_description = titlemeta.twitter_description.strip() if not meta.twitter_description: meta.twitter_description = meta.description meta.gplus_description = titlemeta.gplus_description.strip() if not meta.gplus_description: meta.gplus_description = meta.description if titlemeta.image: meta.image = title.titlemeta.image.canonical_url or title.titlemeta.image.url for item in titlemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except (TitleMeta.DoesNotExist, AttributeError): # Skipping title-level metas if meta.description: meta.og_description = meta.description meta.twitter_description = meta.description meta.gplus_description = meta.description defaults = { 'object_type': meta_settings.FB_TYPE, 'og_type': meta_settings.FB_TYPE, 'og_app_id': meta_settings.FB_APPID, 'fb_pages': meta_settings.FB_PAGES, 'og_profile_id': meta_settings.FB_PROFILE_ID, 'og_publisher': meta_settings.FB_PUBLISHER, 'og_author_url': meta_settings.FB_AUTHOR_URL, 'twitter_type': meta_settings.TWITTER_TYPE, 'twitter_site': meta_settings.TWITTER_SITE, 'twitter_author': meta_settings.TWITTER_AUTHOR, 'gplus_type': meta_settings.GPLUS_TYPE, 'gplus_author': meta_settings.GPLUS_AUTHOR, } try: pagemeta = page.pagemeta meta.object_type = pagemeta.og_type meta.og_type = pagemeta.og_type meta.og_app_id = pagemeta.og_app_id meta.fb_pages = pagemeta.fb_pages meta.og_profile_id = pagemeta.og_author_fbid meta.twitter_type = pagemeta.twitter_type meta.twitter_site = pagemeta.twitter_site meta.twitter_author = pagemeta.twitter_author meta.gplus_type = pagemeta.gplus_type meta.gplus_author = pagemeta.gplus_author if meta.og_type == 'article': meta.og_publisher = pagemeta.og_publisher meta.og_author_url = pagemeta.og_author_url try: from djangocms_page_tags.utils import get_title_tags, get_page_tags tags = list(get_title_tags(page, language)) tags += list(get_page_tags(page)) meta.tag = ','.join([tag.name for tag in tags]) except ImportError: # djangocms-page-tags not available pass if not meta.image and pagemeta.image: meta.image = pagemeta.image.canonical_url or pagemeta.image.url for item in pagemeta.extra.all(): attribute = item.attribute if not attribute: attribute = item.DEFAULT_ATTRIBUTE meta.extra_custom_props.append((attribute, item.name, item.value)) except PageMeta.DoesNotExist: pass if meta.gplus_author and not meta.gplus_author.startswith('http'): if not meta.gplus_author.startswith('/'): meta.gplus_author = '{0}/{1}'.format(gplus_server, meta.gplus_author) else: meta.gplus_author = '{0}{1}'.format(gplus_server, meta.gplus_author) if page.publication_date: meta.published_time = page.publication_date.isoformat() if page.changed_date: meta.modified_time = page.changed_date.isoformat() if page.publication_end_date: meta.expiration_time = page.publication_end_date.isoformat() for attr, val in defaults.items(): if not getattr(meta, attr, '') and val: setattr(meta, attr, val) meta.url = page.get_absolute_url(language) return meta
[ "def", "get_page_meta", "(", "page", ",", "language", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "from", "meta", ".", "views", "import", "Meta", "from", ".", "models", "import", "PageMeta", ",", "TitleMeta", "try", ":", "meta_key", "=", "get_cache_key", "(", "page", ",", "language", ")", "except", "AttributeError", ":", "return", "None", "gplus_server", "=", "'https://plus.google.com'", "meta", "=", "cache", ".", "get", "(", "meta_key", ")", "if", "not", "meta", ":", "meta", "=", "Meta", "(", ")", "title", "=", "page", ".", "get_title_obj", "(", "language", ")", "meta", ".", "extra_custom_props", "=", "[", "]", "meta", ".", "title", "=", "page", ".", "get_page_title", "(", "language", ")", "if", "not", "meta", ".", "title", ":", "meta", ".", "title", "=", "page", ".", "get_title", "(", "language", ")", "if", "title", ".", "meta_description", ":", "meta", ".", "description", "=", "title", ".", "meta_description", ".", "strip", "(", ")", "try", ":", "titlemeta", "=", "title", ".", "titlemeta", "if", "titlemeta", ".", "description", ":", "meta", ".", "description", "=", "titlemeta", ".", "description", ".", "strip", "(", ")", "if", "titlemeta", ".", "keywords", ":", "meta", ".", "keywords", "=", "titlemeta", ".", "keywords", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "meta", ".", "locale", "=", "titlemeta", ".", "locale", "meta", ".", "og_description", "=", "titlemeta", ".", "og_description", ".", "strip", "(", ")", "if", "not", "meta", ".", "og_description", ":", "meta", ".", "og_description", "=", "meta", ".", "description", "meta", ".", "twitter_description", "=", "titlemeta", ".", "twitter_description", ".", "strip", "(", ")", "if", "not", "meta", ".", "twitter_description", ":", "meta", ".", "twitter_description", "=", "meta", ".", "description", "meta", ".", "gplus_description", "=", "titlemeta", ".", "gplus_description", ".", "strip", "(", ")", "if", "not", "meta", ".", "gplus_description", ":", "meta", ".", "gplus_description", "=", "meta", ".", "description", "if", "titlemeta", ".", "image", ":", "meta", ".", "image", "=", "title", ".", "titlemeta", ".", "image", ".", "canonical_url", "or", "title", ".", "titlemeta", ".", "image", ".", "url", "for", "item", "in", "titlemeta", ".", "extra", ".", "all", "(", ")", ":", "attribute", "=", "item", ".", "attribute", "if", "not", "attribute", ":", "attribute", "=", "item", ".", "DEFAULT_ATTRIBUTE", "meta", ".", "extra_custom_props", ".", "append", "(", "(", "attribute", ",", "item", ".", "name", ",", "item", ".", "value", ")", ")", "except", "(", "TitleMeta", ".", "DoesNotExist", ",", "AttributeError", ")", ":", "# Skipping title-level metas", "if", "meta", ".", "description", ":", "meta", ".", "og_description", "=", "meta", ".", "description", "meta", ".", "twitter_description", "=", "meta", ".", "description", "meta", ".", "gplus_description", "=", "meta", ".", "description", "defaults", "=", "{", "'object_type'", ":", "meta_settings", ".", "FB_TYPE", ",", "'og_type'", ":", "meta_settings", ".", "FB_TYPE", ",", "'og_app_id'", ":", "meta_settings", ".", "FB_APPID", ",", "'fb_pages'", ":", "meta_settings", ".", "FB_PAGES", ",", "'og_profile_id'", ":", "meta_settings", ".", "FB_PROFILE_ID", ",", "'og_publisher'", ":", "meta_settings", ".", "FB_PUBLISHER", ",", "'og_author_url'", ":", "meta_settings", ".", "FB_AUTHOR_URL", ",", "'twitter_type'", ":", "meta_settings", ".", "TWITTER_TYPE", ",", "'twitter_site'", ":", "meta_settings", ".", "TWITTER_SITE", ",", "'twitter_author'", ":", "meta_settings", ".", "TWITTER_AUTHOR", ",", "'gplus_type'", ":", "meta_settings", ".", "GPLUS_TYPE", ",", "'gplus_author'", ":", "meta_settings", ".", "GPLUS_AUTHOR", ",", "}", "try", ":", "pagemeta", "=", "page", ".", "pagemeta", "meta", ".", "object_type", "=", "pagemeta", ".", "og_type", "meta", ".", "og_type", "=", "pagemeta", ".", "og_type", "meta", ".", "og_app_id", "=", "pagemeta", ".", "og_app_id", "meta", ".", "fb_pages", "=", "pagemeta", ".", "fb_pages", "meta", ".", "og_profile_id", "=", "pagemeta", ".", "og_author_fbid", "meta", ".", "twitter_type", "=", "pagemeta", ".", "twitter_type", "meta", ".", "twitter_site", "=", "pagemeta", ".", "twitter_site", "meta", ".", "twitter_author", "=", "pagemeta", ".", "twitter_author", "meta", ".", "gplus_type", "=", "pagemeta", ".", "gplus_type", "meta", ".", "gplus_author", "=", "pagemeta", ".", "gplus_author", "if", "meta", ".", "og_type", "==", "'article'", ":", "meta", ".", "og_publisher", "=", "pagemeta", ".", "og_publisher", "meta", ".", "og_author_url", "=", "pagemeta", ".", "og_author_url", "try", ":", "from", "djangocms_page_tags", ".", "utils", "import", "get_title_tags", ",", "get_page_tags", "tags", "=", "list", "(", "get_title_tags", "(", "page", ",", "language", ")", ")", "tags", "+=", "list", "(", "get_page_tags", "(", "page", ")", ")", "meta", ".", "tag", "=", "','", ".", "join", "(", "[", "tag", ".", "name", "for", "tag", "in", "tags", "]", ")", "except", "ImportError", ":", "# djangocms-page-tags not available", "pass", "if", "not", "meta", ".", "image", "and", "pagemeta", ".", "image", ":", "meta", ".", "image", "=", "pagemeta", ".", "image", ".", "canonical_url", "or", "pagemeta", ".", "image", ".", "url", "for", "item", "in", "pagemeta", ".", "extra", ".", "all", "(", ")", ":", "attribute", "=", "item", ".", "attribute", "if", "not", "attribute", ":", "attribute", "=", "item", ".", "DEFAULT_ATTRIBUTE", "meta", ".", "extra_custom_props", ".", "append", "(", "(", "attribute", ",", "item", ".", "name", ",", "item", ".", "value", ")", ")", "except", "PageMeta", ".", "DoesNotExist", ":", "pass", "if", "meta", ".", "gplus_author", "and", "not", "meta", ".", "gplus_author", ".", "startswith", "(", "'http'", ")", ":", "if", "not", "meta", ".", "gplus_author", ".", "startswith", "(", "'/'", ")", ":", "meta", ".", "gplus_author", "=", "'{0}/{1}'", ".", "format", "(", "gplus_server", ",", "meta", ".", "gplus_author", ")", "else", ":", "meta", ".", "gplus_author", "=", "'{0}{1}'", ".", "format", "(", "gplus_server", ",", "meta", ".", "gplus_author", ")", "if", "page", ".", "publication_date", ":", "meta", ".", "published_time", "=", "page", ".", "publication_date", ".", "isoformat", "(", ")", "if", "page", ".", "changed_date", ":", "meta", ".", "modified_time", "=", "page", ".", "changed_date", ".", "isoformat", "(", ")", "if", "page", ".", "publication_end_date", ":", "meta", ".", "expiration_time", "=", "page", ".", "publication_end_date", ".", "isoformat", "(", ")", "for", "attr", ",", "val", "in", "defaults", ".", "items", "(", ")", ":", "if", "not", "getattr", "(", "meta", ",", "attr", ",", "''", ")", "and", "val", ":", "setattr", "(", "meta", ",", "attr", ",", "val", ")", "meta", ".", "url", "=", "page", ".", "get_absolute_url", "(", "language", ")", "return", "meta" ]
Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object
[ "Retrieves", "all", "the", "meta", "information", "for", "the", "page", "in", "the", "given", "language" ]
a38efe3fe3a717d9ad91bfc6aacab90989cd04a4
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/utils.py#L22-L143
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.begin
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False. """ # Assume we're using platform's default I2C bus if none is specified. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C # Require repeated start conditions for I2C register reads. Unfortunately # the MPR121 is very sensitive and requires repeated starts to read all # the registers. I2C.require_repeated_start() # Save a reference to the I2C device instance for later communication. self._device = i2c.get_i2c_device(address, **kwargs) return self._reset()
python
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False. """ # Assume we're using platform's default I2C bus if none is specified. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C # Require repeated start conditions for I2C register reads. Unfortunately # the MPR121 is very sensitive and requires repeated starts to read all # the registers. I2C.require_repeated_start() # Save a reference to the I2C device instance for later communication. self._device = i2c.get_i2c_device(address, **kwargs) return self._reset()
[ "def", "begin", "(", "self", ",", "address", "=", "MPR121_I2CADDR_DEFAULT", ",", "i2c", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Assume we're using platform's default I2C bus if none is specified.", "if", "i2c", "is", "None", ":", "import", "Adafruit_GPIO", ".", "I2C", "as", "I2C", "i2c", "=", "I2C", "# Require repeated start conditions for I2C register reads. Unfortunately", "# the MPR121 is very sensitive and requires repeated starts to read all", "# the registers.", "I2C", ".", "require_repeated_start", "(", ")", "# Save a reference to the I2C device instance for later communication.", "self", ".", "_device", "=", "i2c", ".", "get_i2c_device", "(", "address", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_reset", "(", ")" ]
Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 was established, otherwise returns False.
[ "Initialize", "communication", "with", "the", "MPR121", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L73-L93
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.set_thresholds
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' assert release >= 0 and release <= 255, 'release must be between 0-255 (inclusive)' # Set the touch and release register value for all the inputs. for i in range(12): self._i2c_retry(self._device.write8, MPR121_TOUCHTH_0 + 2*i, touch) self._i2c_retry(self._device.write8, MPR121_RELEASETH_0 + 2*i, release)
python
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' assert release >= 0 and release <= 255, 'release must be between 0-255 (inclusive)' # Set the touch and release register value for all the inputs. for i in range(12): self._i2c_retry(self._device.write8, MPR121_TOUCHTH_0 + 2*i, touch) self._i2c_retry(self._device.write8, MPR121_RELEASETH_0 + 2*i, release)
[ "def", "set_thresholds", "(", "self", ",", "touch", ",", "release", ")", ":", "assert", "touch", ">=", "0", "and", "touch", "<=", "255", ",", "'touch must be between 0-255 (inclusive)'", "assert", "release", ">=", "0", "and", "release", "<=", "255", ",", "'release must be between 0-255 (inclusive)'", "# Set the touch and release register value for all the inputs.", "for", "i", "in", "range", "(", "12", ")", ":", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "write8", ",", "MPR121_TOUCHTH_0", "+", "2", "*", "i", ",", "touch", ")", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "write8", ",", "MPR121_RELEASETH_0", "+", "2", "*", "i", ",", "release", ")" ]
Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive).
[ "Set", "the", "touch", "and", "release", "threshold", "for", "all", "inputs", "to", "the", "provided", "values", ".", "Both", "touch", "and", "release", "should", "be", "a", "value", "between", "0", "to", "255", "(", "inclusive", ")", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L148-L158
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.filtered_data
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
python
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
[ "def", "filtered_data", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "return", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU16LE", ",", "MPR121_FILTDATA_0L", "+", "pin", "*", "2", ")" ]
Return filtered data register value for the provided pin (0-11). Useful for debugging.
[ "Return", "filtered", "data", "register", "value", "for", "the", "provided", "pin", "(", "0", "-", "11", ")", ".", "Useful", "for", "debugging", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L160-L165
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.baseline_data
def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl << 2
python
def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl << 2
[ "def", "baseline_data", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "bl", "=", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU8", ",", "MPR121_BASELINE_0", "+", "pin", ")", "return", "bl", "<<", "2" ]
Return baseline data register value for the provided pin (0-11). Useful for debugging.
[ "Return", "baseline", "data", "register", "value", "for", "the", "provided", "pin", "(", "0", "-", "11", ")", ".", "Useful", "for", "debugging", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L167-L173
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.touched
def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
python
def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
[ "def", "touched", "(", "self", ")", ":", "t", "=", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU16LE", ",", "MPR121_TOUCHSTATUS_L", ")", "return", "t", "&", "0x0FFF" ]
Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched.
[ "Return", "touch", "state", "of", "all", "pins", "as", "a", "12", "-", "bit", "value", "where", "each", "bit", "represents", "a", "pin", "with", "a", "value", "of", "1", "being", "touched", "and", "0", "not", "being", "touched", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L175-L180
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.is_touched
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
python
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
[ "def", "is_touched", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "t", "=", "self", ".", "touched", "(", ")", "return", "(", "t", "&", "(", "1", "<<", "pin", ")", ")", ">", "0" ]
Return True if the specified pin is being touched, otherwise returns False.
[ "Return", "True", "if", "the", "specified", "pin", "is", "being", "touched", "otherwise", "returns", "False", "." ]
86360b80186617e0056d5bd5279bda000978d92c
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L182-L188
train
vertical-knowledge/ripozo-sqlalchemy
profiling/profile.py
profileit
def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.disable() stats = pstats.Stats(prof) try: stats.sort_stats('cumtime').print_stats() except KeyError: pass # breaks in python 2.6 return retval return wrapper
python
def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.disable() stats = pstats.Stats(prof) try: stats.sort_stats('cumtime').print_stats() except KeyError: pass # breaks in python 2.6 return retval return wrapper
[ "def", "profileit", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "datafn", "=", "func", ".", "__name__", "+", "\".profile\"", "# Name the data file sensibly", "prof", "=", "cProfile", ".", "Profile", "(", ")", "prof", ".", "enable", "(", ")", "retval", "=", "prof", ".", "runcall", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "prof", ".", "disable", "(", ")", "stats", "=", "pstats", ".", "Stats", "(", "prof", ")", "try", ":", "stats", ".", "sort_stats", "(", "'cumtime'", ")", ".", "print_stats", "(", ")", "except", "KeyError", ":", "pass", "# breaks in python 2.6", "return", "retval", "return", "wrapper" ]
Decorator straight up stolen from stackoverflow
[ "Decorator", "straight", "up", "stolen", "from", "stackoverflow" ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/profiling/profile.py#L29-L46
train
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_ip_range
def filter_ip_range(ip_range): """Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: string :returns: a function that filters by the provided IP range. :rtype: function """ def filter_func(log_line): ip = log_line.get_ip() if ip: return ip.startswith(ip_range) return filter_func
python
def filter_ip_range(ip_range): """Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: string :returns: a function that filters by the provided IP range. :rtype: function """ def filter_func(log_line): ip = log_line.get_ip() if ip: return ip.startswith(ip_range) return filter_func
[ "def", "filter_ip_range", "(", "ip_range", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "ip", "=", "log_line", ".", "get_ip", "(", ")", "if", "ip", ":", "return", "ip", ".", "startswith", "(", "ip_range", ")", "return", "filter_func" ]
Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: string :returns: a function that filters by the provided IP range. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "IP", "range", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L22-L39
train
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_slow_requests
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :rtype: function """ def filter_func(log_line): slowness_int = int(slowness) return slowness_int <= log_line.time_wait_response return filter_func
python
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :rtype: function """ def filter_func(log_line): slowness_int = int(slowness) return slowness_int <= log_line.time_wait_response return filter_func
[ "def", "filter_slow_requests", "(", "slowness", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "slowness_int", "=", "int", "(", "slowness", ")", "return", "slowness_int", "<=", "log_line", ".", "time_wait_response", "return", "filter_func" ]
Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "response", "time", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L71-L85
train
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_wait_on_queues
def filter_wait_on_queues(max_waiting): """Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted. :type max_waiting: string :returns: a function that filters by HAProxy queueing time. :rtype: function """ def filter_func(log_line): waiting = int(max_waiting) return waiting >= log_line.time_wait_queues return filter_func
python
def filter_wait_on_queues(max_waiting): """Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted. :type max_waiting: string :returns: a function that filters by HAProxy queueing time. :rtype: function """ def filter_func(log_line): waiting = int(max_waiting) return waiting >= log_line.time_wait_queues return filter_func
[ "def", "filter_wait_on_queues", "(", "max_waiting", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "waiting", "=", "int", "(", "max_waiting", ")", "return", "waiting", ">=", "log_line", ".", "time_wait_queues", "return", "filter_func" ]
Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted. :type max_waiting: string :returns: a function that filters by HAProxy queueing time. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "queueing", "time", "in", "HAProxy", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L88-L103
train
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_time_frame
def filter_time_frame(start, delta): """Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument on --help for its format) to limit the amount of time log lines will be considered. :type delta: string :returns: a function that filters by the time a request is made. :rtype: function """ start_value = start delta_value = delta end_value = None if start_value is not '': start_value = _date_str_to_datetime(start_value) if delta_value is not '': delta_value = _delta_str_to_timedelta(delta_value) if start_value is not '' and delta_value is not '': end_value = start_value + delta_value def filter_func(log_line): if start_value is '': return True elif start_value > log_line.accept_date: return False if end_value is None: return True elif end_value < log_line.accept_date: return False return True return filter_func
python
def filter_time_frame(start, delta): """Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument on --help for its format) to limit the amount of time log lines will be considered. :type delta: string :returns: a function that filters by the time a request is made. :rtype: function """ start_value = start delta_value = delta end_value = None if start_value is not '': start_value = _date_str_to_datetime(start_value) if delta_value is not '': delta_value = _delta_str_to_timedelta(delta_value) if start_value is not '' and delta_value is not '': end_value = start_value + delta_value def filter_func(log_line): if start_value is '': return True elif start_value > log_line.accept_date: return False if end_value is None: return True elif end_value < log_line.accept_date: return False return True return filter_func
[ "def", "filter_time_frame", "(", "start", ",", "delta", ")", ":", "start_value", "=", "start", "delta_value", "=", "delta", "end_value", "=", "None", "if", "start_value", "is", "not", "''", ":", "start_value", "=", "_date_str_to_datetime", "(", "start_value", ")", "if", "delta_value", "is", "not", "''", ":", "delta_value", "=", "_delta_str_to_timedelta", "(", "delta_value", ")", "if", "start_value", "is", "not", "''", "and", "delta_value", "is", "not", "''", ":", "end_value", "=", "start_value", "+", "delta_value", "def", "filter_func", "(", "log_line", ")", ":", "if", "start_value", "is", "''", ":", "return", "True", "elif", "start_value", ">", "log_line", ".", "accept_date", ":", "return", "False", "if", "end_value", "is", "None", ":", "return", "True", "elif", "end_value", "<", "log_line", ".", "accept_date", ":", "return", "False", "return", "True", "return", "filter_func" ]
Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument on --help for its format) to limit the amount of time log lines will be considered. :type delta: string :returns: a function that filters by the time a request is made. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "connection", "time", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L106-L144
train
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_response_size
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function """ if size.startswith('+'): size_value = int(size[1:]) else: size_value = int(size) def filter_func(log_line): bytes_read = log_line.bytes_read if bytes_read.startswith('+'): bytes_read = int(bytes_read[1:]) else: bytes_read = int(bytes_read) return bytes_read >= size_value return filter_func
python
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function """ if size.startswith('+'): size_value = int(size[1:]) else: size_value = int(size) def filter_func(log_line): bytes_read = log_line.bytes_read if bytes_read.startswith('+'): bytes_read = int(bytes_read[1:]) else: bytes_read = int(bytes_read) return bytes_read >= size_value return filter_func
[ "def", "filter_response_size", "(", "size", ")", ":", "if", "size", ".", "startswith", "(", "'+'", ")", ":", "size_value", "=", "int", "(", "size", "[", "1", ":", "]", ")", "else", ":", "size_value", "=", "int", "(", "size", ")", "def", "filter_func", "(", "log_line", ")", ":", "bytes_read", "=", "log_line", ".", "bytes_read", "if", "bytes_read", ".", "startswith", "(", "'+'", ")", ":", "bytes_read", "=", "int", "(", "bytes_read", "[", "1", ":", "]", ")", "else", ":", "bytes_read", "=", "int", "(", "bytes_read", ")", "return", "bytes_read", ">=", "size_value", "return", "filter_func" ]
Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "the", "response", "size", "(", "in", "bytes", ")", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L238-L262
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
_get_fields_for_model
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manager: prop = getattr(model, name) if isinstance(prop.property, RelationshipProperty): for pk in prop.property.mapper.primary_key: fields.append('{0}.{1}'.format(name, pk.name)) else: fields.append(name) return tuple(fields)
python
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manager: prop = getattr(model, name) if isinstance(prop.property, RelationshipProperty): for pk in prop.property.mapper.primary_key: fields.append('{0}.{1}'.format(name, pk.name)) else: fields.append(name) return tuple(fields)
[ "def", "_get_fields_for_model", "(", "model", ")", ":", "fields", "=", "[", "]", "for", "name", "in", "model", ".", "_sa_class_manager", ":", "prop", "=", "getattr", "(", "model", ",", "name", ")", "if", "isinstance", "(", "prop", ".", "property", ",", "RelationshipProperty", ")", ":", "for", "pk", "in", "prop", ".", "property", ".", "mapper", ".", "primary_key", ":", "fields", ".", "append", "(", "'{0}.{1}'", ".", "format", "(", "name", ",", "pk", ".", "name", ")", ")", "else", ":", "fields", ".", "append", "(", "name", ")", "return", "tuple", "(", "fields", ")" ]
Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple
[ "Gets", "all", "of", "the", "fields", "on", "the", "model", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L16-L33
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
_get_relationships
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple """ relationships = [] for name, relationship in inspect(model).relationships.items(): class_ = relationship.mapper.class_ if relationship.uselist: rel = ListRelationship(name, relation=class_.__name__) else: rel = Relationship(name, relation=class_.__name__) relationships.append(rel) return tuple(relationships)
python
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple """ relationships = [] for name, relationship in inspect(model).relationships.items(): class_ = relationship.mapper.class_ if relationship.uselist: rel = ListRelationship(name, relation=class_.__name__) else: rel = Relationship(name, relation=class_.__name__) relationships.append(rel) return tuple(relationships)
[ "def", "_get_relationships", "(", "model", ")", ":", "relationships", "=", "[", "]", "for", "name", ",", "relationship", "in", "inspect", "(", "model", ")", ".", "relationships", ".", "items", "(", ")", ":", "class_", "=", "relationship", ".", "mapper", ".", "class_", "if", "relationship", ".", "uselist", ":", "rel", "=", "ListRelationship", "(", "name", ",", "relation", "=", "class_", ".", "__name__", ")", "else", ":", "rel", "=", "Relationship", "(", "name", ",", "relation", "=", "class_", ".", "__name__", ")", "relationships", ".", "append", "(", "rel", ")", "return", "tuple", "(", "relationships", ")" ]
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple
[ "Gets", "the", "necessary", "relationships", "for", "the", "resource", "by", "inspecting", "the", "sqlalchemy", "model", "for", "relationships", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L48-L66
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
create_resource
def create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields=None, list_fields=None, append_slash=False): """ Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be inspected to create a Resource and Manager from. By default, all of it's fields will be exposed, although this can be overridden using the fields attribute. :param tuple resource_bases: A tuple of ResourceBase subclasses. Defaults to the restmixins.CRUDL class only. However if you only wanted Update and Delete you could pass in ```(restmixins.Update, restmixins.Delete)``` which would cause the resource to inherit from those two. Additionally, you could create your own mixins and pass them in as the resource_bases :param tuple relationships: extra relationships to pass into the ResourceBase constructor. If auto_relationships is set to True, then they will be appended to these relationships. :param tuple links: Extra links to pass into the ResourceBase as the class _links attribute. Defaults to an empty tuple. :param tuple preprocessors: Preprocessors for the resource class attribute. :param tuple postprocessors: Postprocessors for the resource class attribute. :param ripozo_sqlalchemy.SessionHandler|ripozo_sqlalchemy.ScopedSessionHandler session_handler: A session handler to use when instantiating an instance of the Manager class created from the model. This is responsible for getting and handling sessions in both normal cases and exceptions. :param tuple fields: The fields to expose on the api. Defaults to all of the fields on the model. :param bool auto_relationships: If True, then the SQLAlchemy Model will be inspected for relationships and they will be automatically appended to the relationships on the resource class attribute. :param list create_fields: A list of the fields that are valid when creating a resource. By default this will be the fields without any primary keys included :param list update_fields: A list of the fields that are valid when updating a resource. By default this will be the fields without any primary keys included :param list list_fields: A list of the fields that will be returned when the list endpoint is requested. Defaults to the fields attribute. :param bool append_slash: A flag to forcibly append slashes to the end of urls. :return: A ResourceBase subclass and AlchemyManager subclass :rtype: ResourceMetaClass """ relationships = relationships or tuple() if auto_relationships: relationships += _get_relationships(model) links = links or tuple() preprocessors = preprocessors or tuple() postprocessors = postprocessors or tuple() pks = pks or _get_pks(model) fields = fields or _get_fields_for_model(model) list_fields = list_fields or fields create_fields = create_fields or [x for x in fields if x not in set(pks)] update_fields = update_fields or [x for x in fields if x not in set(pks)] manager_cls_attrs = dict(paginate_by=paginate_by, fields=fields, model=model, list_fields=list_fields, create_fields=create_fields, update_fields=update_fields) manager_class = type(str(model.__name__), (AlchemyManager,), manager_cls_attrs) manager = manager_class(session_handler) resource_cls_attrs = dict(preprocessors=preprocessors, postprocessors=postprocessors, _relationships=relationships, _links=links, pks=pks, manager=manager, append_slash=append_slash) res_class = ResourceMetaClass(str(model.__name__), resource_bases, resource_cls_attrs) return res_class
python
def create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields=None, list_fields=None, append_slash=False): """ Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be inspected to create a Resource and Manager from. By default, all of it's fields will be exposed, although this can be overridden using the fields attribute. :param tuple resource_bases: A tuple of ResourceBase subclasses. Defaults to the restmixins.CRUDL class only. However if you only wanted Update and Delete you could pass in ```(restmixins.Update, restmixins.Delete)``` which would cause the resource to inherit from those two. Additionally, you could create your own mixins and pass them in as the resource_bases :param tuple relationships: extra relationships to pass into the ResourceBase constructor. If auto_relationships is set to True, then they will be appended to these relationships. :param tuple links: Extra links to pass into the ResourceBase as the class _links attribute. Defaults to an empty tuple. :param tuple preprocessors: Preprocessors for the resource class attribute. :param tuple postprocessors: Postprocessors for the resource class attribute. :param ripozo_sqlalchemy.SessionHandler|ripozo_sqlalchemy.ScopedSessionHandler session_handler: A session handler to use when instantiating an instance of the Manager class created from the model. This is responsible for getting and handling sessions in both normal cases and exceptions. :param tuple fields: The fields to expose on the api. Defaults to all of the fields on the model. :param bool auto_relationships: If True, then the SQLAlchemy Model will be inspected for relationships and they will be automatically appended to the relationships on the resource class attribute. :param list create_fields: A list of the fields that are valid when creating a resource. By default this will be the fields without any primary keys included :param list update_fields: A list of the fields that are valid when updating a resource. By default this will be the fields without any primary keys included :param list list_fields: A list of the fields that will be returned when the list endpoint is requested. Defaults to the fields attribute. :param bool append_slash: A flag to forcibly append slashes to the end of urls. :return: A ResourceBase subclass and AlchemyManager subclass :rtype: ResourceMetaClass """ relationships = relationships or tuple() if auto_relationships: relationships += _get_relationships(model) links = links or tuple() preprocessors = preprocessors or tuple() postprocessors = postprocessors or tuple() pks = pks or _get_pks(model) fields = fields or _get_fields_for_model(model) list_fields = list_fields or fields create_fields = create_fields or [x for x in fields if x not in set(pks)] update_fields = update_fields or [x for x in fields if x not in set(pks)] manager_cls_attrs = dict(paginate_by=paginate_by, fields=fields, model=model, list_fields=list_fields, create_fields=create_fields, update_fields=update_fields) manager_class = type(str(model.__name__), (AlchemyManager,), manager_cls_attrs) manager = manager_class(session_handler) resource_cls_attrs = dict(preprocessors=preprocessors, postprocessors=postprocessors, _relationships=relationships, _links=links, pks=pks, manager=manager, append_slash=append_slash) res_class = ResourceMetaClass(str(model.__name__), resource_bases, resource_cls_attrs) return res_class
[ "def", "create_resource", "(", "model", ",", "session_handler", ",", "resource_bases", "=", "(", "CRUDL", ",", ")", ",", "relationships", "=", "None", ",", "links", "=", "None", ",", "preprocessors", "=", "None", ",", "postprocessors", "=", "None", ",", "fields", "=", "None", ",", "paginate_by", "=", "100", ",", "auto_relationships", "=", "True", ",", "pks", "=", "None", ",", "create_fields", "=", "None", ",", "update_fields", "=", "None", ",", "list_fields", "=", "None", ",", "append_slash", "=", "False", ")", ":", "relationships", "=", "relationships", "or", "tuple", "(", ")", "if", "auto_relationships", ":", "relationships", "+=", "_get_relationships", "(", "model", ")", "links", "=", "links", "or", "tuple", "(", ")", "preprocessors", "=", "preprocessors", "or", "tuple", "(", ")", "postprocessors", "=", "postprocessors", "or", "tuple", "(", ")", "pks", "=", "pks", "or", "_get_pks", "(", "model", ")", "fields", "=", "fields", "or", "_get_fields_for_model", "(", "model", ")", "list_fields", "=", "list_fields", "or", "fields", "create_fields", "=", "create_fields", "or", "[", "x", "for", "x", "in", "fields", "if", "x", "not", "in", "set", "(", "pks", ")", "]", "update_fields", "=", "update_fields", "or", "[", "x", "for", "x", "in", "fields", "if", "x", "not", "in", "set", "(", "pks", ")", "]", "manager_cls_attrs", "=", "dict", "(", "paginate_by", "=", "paginate_by", ",", "fields", "=", "fields", ",", "model", "=", "model", ",", "list_fields", "=", "list_fields", ",", "create_fields", "=", "create_fields", ",", "update_fields", "=", "update_fields", ")", "manager_class", "=", "type", "(", "str", "(", "model", ".", "__name__", ")", ",", "(", "AlchemyManager", ",", ")", ",", "manager_cls_attrs", ")", "manager", "=", "manager_class", "(", "session_handler", ")", "resource_cls_attrs", "=", "dict", "(", "preprocessors", "=", "preprocessors", ",", "postprocessors", "=", "postprocessors", ",", "_relationships", "=", "relationships", ",", "_links", "=", "links", ",", "pks", "=", "pks", ",", "manager", "=", "manager", ",", "append_slash", "=", "append_slash", ")", "res_class", "=", "ResourceMetaClass", "(", "str", "(", "model", ".", "__name__", ")", ",", "resource_bases", ",", "resource_cls_attrs", ")", "return", "res_class" ]
Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be inspected to create a Resource and Manager from. By default, all of it's fields will be exposed, although this can be overridden using the fields attribute. :param tuple resource_bases: A tuple of ResourceBase subclasses. Defaults to the restmixins.CRUDL class only. However if you only wanted Update and Delete you could pass in ```(restmixins.Update, restmixins.Delete)``` which would cause the resource to inherit from those two. Additionally, you could create your own mixins and pass them in as the resource_bases :param tuple relationships: extra relationships to pass into the ResourceBase constructor. If auto_relationships is set to True, then they will be appended to these relationships. :param tuple links: Extra links to pass into the ResourceBase as the class _links attribute. Defaults to an empty tuple. :param tuple preprocessors: Preprocessors for the resource class attribute. :param tuple postprocessors: Postprocessors for the resource class attribute. :param ripozo_sqlalchemy.SessionHandler|ripozo_sqlalchemy.ScopedSessionHandler session_handler: A session handler to use when instantiating an instance of the Manager class created from the model. This is responsible for getting and handling sessions in both normal cases and exceptions. :param tuple fields: The fields to expose on the api. Defaults to all of the fields on the model. :param bool auto_relationships: If True, then the SQLAlchemy Model will be inspected for relationships and they will be automatically appended to the relationships on the resource class attribute. :param list create_fields: A list of the fields that are valid when creating a resource. By default this will be the fields without any primary keys included :param list update_fields: A list of the fields that are valid when updating a resource. By default this will be the fields without any primary keys included :param list list_fields: A list of the fields that will be returned when the list endpoint is requested. Defaults to the fields attribute. :param bool append_slash: A flag to forcibly append slashes to the end of urls. :return: A ResourceBase subclass and AlchemyManager subclass :rtype: ResourceMetaClass
[ "Creates", "a", "ResourceBase", "subclass", "by", "inspecting", "a", "SQLAlchemy", "Model", ".", "This", "is", "somewhat", "more", "restrictive", "than", "explicitly", "creating", "managers", "and", "resources", ".", "However", "if", "you", "only", "need", "any", "of", "the", "basic", "CRUD", "+", "L", "operations" ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L69-L145
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._is_pickle_valid
def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): return False else: file_mtime = os.path.getmtime(self.logfile) pickle_mtime = os.path.getmtime(self._pickle_file) if file_mtime > pickle_mtime: return False return True
python
def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): return False else: file_mtime = os.path.getmtime(self.logfile) pickle_mtime = os.path.getmtime(self._pickle_file) if file_mtime > pickle_mtime: return False return True
[ "def", "_is_pickle_valid", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_pickle_file", ")", ":", "return", "False", "else", ":", "file_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "logfile", ")", "pickle_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "_pickle_file", ")", "if", "file_mtime", ">", "pickle_mtime", ":", "return", "False", "return", "True" ]
Logic to decide if the file should be processed or just needs to be loaded from its pickle data.
[ "Logic", "to", "decide", "if", "the", "file", "should", "be", "processed", "or", "just", "needs", "to", "be", "loaded", "from", "its", "pickle", "data", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L44-L55
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._load
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
python
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
[ "def", "_load", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_pickle_file", ",", "'rb'", ")", "as", "source", ":", "pickler", "=", "pickle", ".", "Unpickler", "(", "source", ")", "for", "attribute", "in", "self", ".", "_pickle_attributes", ":", "pickle_data", "=", "pickler", ".", "load", "(", ")", "setattr", "(", "self", ",", "attribute", ",", "pickle_data", ")" ]
Load data from a pickle file.
[ "Load", "data", "from", "a", "pickle", "file", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L57-L64
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._save
def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. """ with open(self._pickle_file, 'wb') as source: pickler = pickle.Pickler(source, pickle.HIGHEST_PROTOCOL) for attribute in self._pickle_attributes: attr = getattr(self, attribute, None) pickler.dump(attr)
python
def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. """ with open(self._pickle_file, 'wb') as source: pickler = pickle.Pickler(source, pickle.HIGHEST_PROTOCOL) for attribute in self._pickle_attributes: attr = getattr(self, attribute, None) pickler.dump(attr)
[ "def", "_save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_pickle_file", ",", "'wb'", ")", "as", "source", ":", "pickler", "=", "pickle", ".", "Pickler", "(", "source", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "for", "attribute", "in", "self", ".", "_pickle_attributes", ":", "attr", "=", "getattr", "(", "self", ",", "attribute", ",", "None", ")", "pickler", ".", "dump", "(", "attr", ")" ]
Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time.
[ "Save", "the", "attributes", "defined", "on", "_pickle_attributes", "in", "a", "pickle", "file", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L66-L77
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.parse_data
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) if parsed_line.valid: self._valid_lines.append(parsed_line) else: self._invalid_lines.append(stripped_line) self.total_lines = len(self._valid_lines) + len(self._invalid_lines)
python
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) if parsed_line.valid: self._valid_lines.append(parsed_line) else: self._invalid_lines.append(stripped_line) self.total_lines = len(self._valid_lines) + len(self._invalid_lines)
[ "def", "parse_data", "(", "self", ",", "logfile", ")", ":", "for", "line", "in", "logfile", ":", "stripped_line", "=", "line", ".", "strip", "(", ")", "parsed_line", "=", "Line", "(", "stripped_line", ")", "if", "parsed_line", ".", "valid", ":", "self", ".", "_valid_lines", ".", "append", "(", "parsed_line", ")", "else", ":", "self", ".", "_invalid_lines", ".", "append", "(", "stripped_line", ")", "self", ".", "total_lines", "=", "len", "(", "self", ".", "_valid_lines", ")", "+", "len", "(", "self", ".", "_invalid_lines", ")" ]
Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str
[ "Parse", "data", "from", "data", "stream", "and", "replace", "object", "lines", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L79-L94
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.filter
def filter(self, filter_func, reverse=False): """Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further processed with commands (top paths, http status counter...). :param filter_func: [required] Filter method, see filters.py for all available filters. :type filter_func: function :param reverse: negate the filter (so accept all log lines that return ``False``). :type reverse: boolean :returns: a new instance of Log containing only log lines that passed the filter function. :rtype: :class:`Log` """ new_log_file = Log() new_log_file.logfile = self.logfile new_log_file.total_lines = 0 new_log_file._valid_lines = [] new_log_file._invalid_lines = self._invalid_lines[:] # add the reverse conditional outside the loop to keep the loop as # straightforward as possible if not reverse: for i in self._valid_lines: if filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) else: for i in self._valid_lines: if not filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) return new_log_file
python
def filter(self, filter_func, reverse=False): """Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further processed with commands (top paths, http status counter...). :param filter_func: [required] Filter method, see filters.py for all available filters. :type filter_func: function :param reverse: negate the filter (so accept all log lines that return ``False``). :type reverse: boolean :returns: a new instance of Log containing only log lines that passed the filter function. :rtype: :class:`Log` """ new_log_file = Log() new_log_file.logfile = self.logfile new_log_file.total_lines = 0 new_log_file._valid_lines = [] new_log_file._invalid_lines = self._invalid_lines[:] # add the reverse conditional outside the loop to keep the loop as # straightforward as possible if not reverse: for i in self._valid_lines: if filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) else: for i in self._valid_lines: if not filter_func(i): new_log_file.total_lines += 1 new_log_file._valid_lines.append(i) return new_log_file
[ "def", "filter", "(", "self", ",", "filter_func", ",", "reverse", "=", "False", ")", ":", "new_log_file", "=", "Log", "(", ")", "new_log_file", ".", "logfile", "=", "self", ".", "logfile", "new_log_file", ".", "total_lines", "=", "0", "new_log_file", ".", "_valid_lines", "=", "[", "]", "new_log_file", ".", "_invalid_lines", "=", "self", ".", "_invalid_lines", "[", ":", "]", "# add the reverse conditional outside the loop to keep the loop as", "# straightforward as possible", "if", "not", "reverse", ":", "for", "i", "in", "self", ".", "_valid_lines", ":", "if", "filter_func", "(", "i", ")", ":", "new_log_file", ".", "total_lines", "+=", "1", "new_log_file", ".", "_valid_lines", ".", "append", "(", "i", ")", "else", ":", "for", "i", "in", "self", ".", "_valid_lines", ":", "if", "not", "filter_func", "(", "i", ")", ":", "new_log_file", ".", "total_lines", "+=", "1", "new_log_file", ".", "_valid_lines", ".", "append", "(", "i", ")", "return", "new_log_file" ]
Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further processed with commands (top paths, http status counter...). :param filter_func: [required] Filter method, see filters.py for all available filters. :type filter_func: function :param reverse: negate the filter (so accept all log lines that return ``False``). :type reverse: boolean :returns: a new instance of Log containing only log lines that passed the filter function. :rtype: :class:`Log`
[ "Filter", "current", "log", "lines", "by", "a", "given", "filter", "function", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L96-L136
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.commands
def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
python
def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
[ "def", "commands", "(", "cls", ")", ":", "cmds", "=", "[", "cmd", "[", "4", ":", "]", "for", "cmd", "in", "dir", "(", "cls", ")", "if", "cmd", ".", "startswith", "(", "'cmd_'", ")", "]", "return", "cmds" ]
Returns a list of all methods that start with ``cmd_``.
[ "Returns", "a", "list", "of", "all", "methods", "that", "start", "with", "cmd_", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L139-L142
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_http_methods
def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: methods[line.http_request_method] += 1 return methods
python
def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: methods[line.http_request_method] += 1 return methods
[ "def", "cmd_http_methods", "(", "self", ")", ":", "methods", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "methods", "[", "line", ".", "http_request_method", "]", "+=", "1", "return", "methods" ]
Reports a breakdown of how many requests have been made per HTTP method (GET, POST...).
[ "Reports", "a", "breakdown", "of", "how", "many", "requests", "have", "been", "made", "per", "HTTP", "method", "(", "GET", "POST", "...", ")", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L152-L159
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_ip_counter
def cmd_ip_counter(self): """Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """ ip_counter = defaultdict(int) for line in self._valid_lines: ip = line.get_ip() if ip is not None: ip_counter[ip] += 1 return ip_counter
python
def cmd_ip_counter(self): """Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """ ip_counter = defaultdict(int) for line in self._valid_lines: ip = line.get_ip() if ip is not None: ip_counter[ip] += 1 return ip_counter
[ "def", "cmd_ip_counter", "(", "self", ")", ":", "ip_counter", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "ip", "=", "line", ".", "get_ip", "(", ")", "if", "ip", "is", "not", "None", ":", "ip_counter", "[", "ip", "]", "+=", "1", "return", "ip_counter" ]
Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured.
[ "Reports", "a", "breakdown", "of", "how", "many", "requests", "have", "been", "made", "per", "IP", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L161-L174
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_status_codes_counter
def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 return status_codes
python
def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 return status_codes
[ "def", "cmd_status_codes_counter", "(", "self", ")", ":", "status_codes", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "status_codes", "[", "line", ".", "status_code", "]", "+=", "1", "return", "status_codes" ]
Generate statistics about HTTP status codes. 404, 500 and so on.
[ "Generate", "statistics", "about", "HTTP", "status", "codes", ".", "404", "500", "and", "so", "on", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L188-L194
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_request_path_counter
def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
python
def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
[ "def", "cmd_request_path_counter", "(", "self", ")", ":", "paths", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "paths", "[", "line", ".", "http_request_path", "]", "+=", "1", "return", "paths" ]
Generate statistics about HTTP requests' path.
[ "Generate", "statistics", "about", "HTTP", "requests", "path", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L196-L201
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_slow_requests
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. """ slow_requests = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response > 1000 ] return slow_requests
python
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. """ slow_requests = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response > 1000 ] return slow_requests
[ "def", "cmd_slow_requests", "(", "self", ")", ":", "slow_requests", "=", "[", "line", ".", "time_wait_response", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_response", ">", "1000", "]", "return", "slow_requests" ]
List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally.
[ "List", "all", "requests", "that", "took", "a", "certain", "amount", "of", "time", "to", "be", "processed", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L215-L229
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_average_response_time
def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >= 0 ] divisor = float(len(average)) if divisor > 0: return sum(average) / float(len(average)) return 0
python
def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >= 0 ] divisor = float(len(average)) if divisor > 0: return sum(average) / float(len(average)) return 0
[ "def", "cmd_average_response_time", "(", "self", ")", ":", "average", "=", "[", "line", ".", "time_wait_response", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_response", ">=", "0", "]", "divisor", "=", "float", "(", "len", "(", "average", ")", ")", "if", "divisor", ">", "0", ":", "return", "sum", "(", "average", ")", "/", "float", "(", "len", "(", "average", ")", ")", "return", "0" ]
Returns the average response time of all, non aborted, requests.
[ "Returns", "the", "average", "response", "time", "of", "all", "non", "aborted", "requests", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L231-L242
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_average_waiting_time
def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ] divisor = float(len(average)) if divisor > 0: return sum(average) / float(len(average)) return 0
python
def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ] divisor = float(len(average)) if divisor > 0: return sum(average) / float(len(average)) return 0
[ "def", "cmd_average_waiting_time", "(", "self", ")", ":", "average", "=", "[", "line", ".", "time_wait_queues", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_queues", ">=", "0", "]", "divisor", "=", "float", "(", "len", "(", "average", ")", ")", "if", "divisor", ">", "0", ":", "return", "sum", "(", "average", ")", "/", "float", "(", "len", "(", "average", ")", ")", "return", "0" ]
Returns the average queue time of all, non aborted, requests.
[ "Returns", "the", "average", "queue", "time", "of", "all", "non", "aborted", "requests", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L244-L255
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_server_load
def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines: servers[line.server_name] += 1 return servers
python
def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines: servers[line.server_name] += 1 return servers
[ "def", "cmd_server_load", "(", "self", ")", ":", "servers", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "servers", "[", "line", ".", "server_name", "]", "+=", "1", "return", "servers" ]
Generate statistics regarding how many requests were processed by each downstream server.
[ "Generate", "statistics", "regarding", "how", "many", "requests", "were", "processed", "by", "each", "downstream", "server", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L268-L275
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_queue_peaks
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently set to 1. """ threshold = 1 peaks = [] current_peak = 0 current_queue = 0 current_span = 0 first_on_queue = None for line in self._valid_lines: current_queue = line.queue_backend if current_queue > 0: current_span += 1 if first_on_queue is None: first_on_queue = line.accept_date if current_queue == 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) current_peak = 0 current_span = 0 first_on_queue = None if current_queue > current_peak: current_peak = current_queue # case of a series that does not end if current_queue > 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) return peaks
python
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently set to 1. """ threshold = 1 peaks = [] current_peak = 0 current_queue = 0 current_span = 0 first_on_queue = None for line in self._valid_lines: current_queue = line.queue_backend if current_queue > 0: current_span += 1 if first_on_queue is None: first_on_queue = line.accept_date if current_queue == 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) current_peak = 0 current_span = 0 first_on_queue = None if current_queue > current_peak: current_peak = current_queue # case of a series that does not end if current_queue > 0 and current_peak > threshold: data = { 'peak': current_peak, 'span': current_span, 'first': first_on_queue, 'last': line.accept_date, } peaks.append(data) return peaks
[ "def", "cmd_queue_peaks", "(", "self", ")", ":", "threshold", "=", "1", "peaks", "=", "[", "]", "current_peak", "=", "0", "current_queue", "=", "0", "current_span", "=", "0", "first_on_queue", "=", "None", "for", "line", "in", "self", ".", "_valid_lines", ":", "current_queue", "=", "line", ".", "queue_backend", "if", "current_queue", ">", "0", ":", "current_span", "+=", "1", "if", "first_on_queue", "is", "None", ":", "first_on_queue", "=", "line", ".", "accept_date", "if", "current_queue", "==", "0", "and", "current_peak", ">", "threshold", ":", "data", "=", "{", "'peak'", ":", "current_peak", ",", "'span'", ":", "current_span", ",", "'first'", ":", "first_on_queue", ",", "'last'", ":", "line", ".", "accept_date", ",", "}", "peaks", ".", "append", "(", "data", ")", "current_peak", "=", "0", "current_span", "=", "0", "first_on_queue", "=", "None", "if", "current_queue", ">", "current_peak", ":", "current_peak", "=", "current_queue", "# case of a series that does not end", "if", "current_queue", ">", "0", "and", "current_peak", ">", "threshold", ":", "data", "=", "{", "'peak'", ":", "current_peak", ",", "'span'", ":", "current_span", ",", "'first'", ":", "first_on_queue", ",", "'last'", ":", "line", ".", "accept_date", ",", "}", "peaks", ".", "append", "(", "data", ")", "return", "peaks" ]
Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently set to 1.
[ "Generate", "a", "list", "of", "the", "requests", "peaks", "on", "the", "queue", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L277-L330
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_connection_type
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable. """ https = 0 non_https = 0 for line in self._valid_lines: if line.is_https(): https += 1 else: non_https += 1 return https, non_https
python
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable. """ https = 0 non_https = 0 for line in self._valid_lines: if line.is_https(): https += 1 else: non_https += 1 return https, non_https
[ "def", "cmd_connection_type", "(", "self", ")", ":", "https", "=", "0", "non_https", "=", "0", "for", "line", "in", "self", ".", "_valid_lines", ":", "if", "line", ".", "is_https", "(", ")", ":", "https", "+=", "1", "else", ":", "non_https", "+=", "1", "return", "https", ",", "non_https" ]
Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable.
[ "Generates", "statistics", "on", "how", "many", "requests", "are", "made", "via", "HTTP", "and", "how", "many", "are", "made", "via", "SSL", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L332-L350
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_requests_per_minute
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: return current_minute = self._valid_lines[0].accept_date current_minute_counter = 0 requests = [] one_minute = timedelta(minutes=1) def format_and_append(append_to, date, counter): seconds_and_micro = timedelta( seconds=date.second, microseconds=date.microsecond, ) minute_formatted = date - seconds_and_micro append_to.append((minute_formatted, counter)) # note that _valid_lines is kept sorted by date for line in self._valid_lines: line_date = line.accept_date if line_date - current_minute < one_minute and \ line_date.minute == current_minute.minute: current_minute_counter += 1 else: format_and_append( requests, current_minute, current_minute_counter, ) current_minute_counter = 1 current_minute = line_date if current_minute_counter > 0: format_and_append( requests, current_minute, current_minute_counter, ) return requests
python
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: return current_minute = self._valid_lines[0].accept_date current_minute_counter = 0 requests = [] one_minute = timedelta(minutes=1) def format_and_append(append_to, date, counter): seconds_and_micro = timedelta( seconds=date.second, microseconds=date.microsecond, ) minute_formatted = date - seconds_and_micro append_to.append((minute_formatted, counter)) # note that _valid_lines is kept sorted by date for line in self._valid_lines: line_date = line.accept_date if line_date - current_minute < one_minute and \ line_date.minute == current_minute.minute: current_minute_counter += 1 else: format_and_append( requests, current_minute, current_minute_counter, ) current_minute_counter = 1 current_minute = line_date if current_minute_counter > 0: format_and_append( requests, current_minute, current_minute_counter, ) return requests
[ "def", "cmd_requests_per_minute", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_valid_lines", ")", "==", "0", ":", "return", "current_minute", "=", "self", ".", "_valid_lines", "[", "0", "]", ".", "accept_date", "current_minute_counter", "=", "0", "requests", "=", "[", "]", "one_minute", "=", "timedelta", "(", "minutes", "=", "1", ")", "def", "format_and_append", "(", "append_to", ",", "date", ",", "counter", ")", ":", "seconds_and_micro", "=", "timedelta", "(", "seconds", "=", "date", ".", "second", ",", "microseconds", "=", "date", ".", "microsecond", ",", ")", "minute_formatted", "=", "date", "-", "seconds_and_micro", "append_to", ".", "append", "(", "(", "minute_formatted", ",", "counter", ")", ")", "# note that _valid_lines is kept sorted by date", "for", "line", "in", "self", ".", "_valid_lines", ":", "line_date", "=", "line", ".", "accept_date", "if", "line_date", "-", "current_minute", "<", "one_minute", "and", "line_date", ".", "minute", "==", "current_minute", ".", "minute", ":", "current_minute_counter", "+=", "1", "else", ":", "format_and_append", "(", "requests", ",", "current_minute", ",", "current_minute_counter", ",", ")", "current_minute_counter", "=", "1", "current_minute", "=", "line_date", "if", "current_minute_counter", ">", "0", ":", "format_and_append", "(", "requests", ",", "current_minute", ",", "current_minute_counter", ",", ")", "return", "requests" ]
Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise.
[ "Generates", "statistics", "on", "how", "many", "requests", "were", "made", "per", "minute", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L352-L398
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_print
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
python
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
[ "def", "cmd_print", "(", "self", ")", ":", "if", "not", "self", ".", "_valid_lines", ":", "return", "''", "return", "'\\n'", ".", "join", "(", "[", "line", ".", "raw_line", "for", "line", "in", "self", ".", "_valid_lines", "]", ")", "+", "'\\n'" ]
Returns the raw lines to be printed.
[ "Returns", "the", "raw", "lines", "to", "be", "printed", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L400-L404
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._sort_lines
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server. """ self._valid_lines = sorted( self._valid_lines, key=lambda line: line.accept_date, )
python
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server. """ self._valid_lines = sorted( self._valid_lines, key=lambda line: line.accept_date, )
[ "def", "_sort_lines", "(", "self", ")", ":", "self", ".", "_valid_lines", "=", "sorted", "(", "self", ".", "_valid_lines", ",", "key", "=", "lambda", "line", ":", "line", ".", "accept_date", ",", ")" ]
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server.
[ "Haproxy", "writes", "its", "logs", "after", "having", "gathered", "all", "information", "related", "to", "each", "specific", "connection", ".", "A", "simple", "request", "can", "be", "really", "quick", "but", "others", "can", "be", "really", "slow", "thus", "even", "if", "one", "connection", "is", "logged", "later", "it", "could", "have", "been", "accepted", "before", "others", "that", "are", "already", "processed", "and", "logged", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L406-L419
train
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._sort_and_trim
def _sort_and_trim(data, reverse=False): """Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally. """ threshold = 10 data_list = data.items() data_list = sorted( data_list, key=lambda data_info: data_info[1], reverse=reverse, ) return data_list[:threshold]
python
def _sort_and_trim(data, reverse=False): """Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally. """ threshold = 10 data_list = data.items() data_list = sorted( data_list, key=lambda data_info: data_info[1], reverse=reverse, ) return data_list[:threshold]
[ "def", "_sort_and_trim", "(", "data", ",", "reverse", "=", "False", ")", ":", "threshold", "=", "10", "data_list", "=", "data", ".", "items", "(", ")", "data_list", "=", "sorted", "(", "data_list", ",", "key", "=", "lambda", "data_info", ":", "data_info", "[", "1", "]", ",", "reverse", "=", "reverse", ",", ")", "return", "data_list", "[", ":", "threshold", "]" ]
Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally.
[ "Sorts", "a", "dictionary", "with", "at", "least", "two", "fields", "on", "each", "of", "them", "sorting", "by", "the", "second", "element", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L422-L437
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
db_access_point
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args, **kwargs): """ Wrapper responsible for handling sessions """ session = self.session_handler.get_session() try: resp = func(self, session, *args, **kwargs) except Exception as exc: self.session_handler.handle_session(session, exc=exc) raise exc else: self.session_handler.handle_session(session) return resp return wrapper
python
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args, **kwargs): """ Wrapper responsible for handling sessions """ session = self.session_handler.get_session() try: resp = func(self, session, *args, **kwargs) except Exception as exc: self.session_handler.handle_session(session, exc=exc) raise exc else: self.session_handler.handle_session(session) return resp return wrapper
[ "def", "db_access_point", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrapper responsible for handling\n sessions\n \"\"\"", "session", "=", "self", ".", "session_handler", ".", "get_session", "(", ")", "try", ":", "resp", "=", "func", "(", "self", ",", "session", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "exc", ":", "self", ".", "session_handler", ".", "handle_session", "(", "session", ",", "exc", "=", "exc", ")", "raise", "exc", "else", ":", "self", ".", "session_handler", ".", "handle_session", "(", "session", ")", "return", "resp", "return", "wrapper" ]
Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database.
[ "Wraps", "a", "function", "that", "actually", "accesses", "the", "database", ".", "It", "injects", "a", "session", "into", "the", "method", "and", "attempts", "to", "handle", "it", "after", "the", "function", "has", "run", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L42-L65
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._get_field_python_type
def _get_field_python_type(model, name): """ Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype: type """ try: return getattr(model, name).property.columns[0].type.python_type except AttributeError: # It's a relationship parts = name.split('.') model = getattr(model, parts.pop(0)).comparator.mapper.class_ return AlchemyManager._get_field_python_type(model, '.'.join(parts)) except NotImplementedError: # This is for pickle type columns. return object
python
def _get_field_python_type(model, name): """ Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype: type """ try: return getattr(model, name).property.columns[0].type.python_type except AttributeError: # It's a relationship parts = name.split('.') model = getattr(model, parts.pop(0)).comparator.mapper.class_ return AlchemyManager._get_field_python_type(model, '.'.join(parts)) except NotImplementedError: # This is for pickle type columns. return object
[ "def", "_get_field_python_type", "(", "model", ",", "name", ")", ":", "try", ":", "return", "getattr", "(", "model", ",", "name", ")", ".", "property", ".", "columns", "[", "0", "]", ".", "type", ".", "python_type", "except", "AttributeError", ":", "# It's a relationship", "parts", "=", "name", ".", "split", "(", "'.'", ")", "model", "=", "getattr", "(", "model", ",", "parts", ".", "pop", "(", "0", ")", ")", ".", "comparator", ".", "mapper", ".", "class_", "return", "AlchemyManager", ".", "_get_field_python_type", "(", "model", ",", "'.'", ".", "join", "(", "parts", ")", ")", "except", "NotImplementedError", ":", "# This is for pickle type columns.", "return", "object" ]
Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype: type
[ "Gets", "the", "python", "type", "for", "the", "attribute", "on", "the", "model", "with", "the", "name", "provided", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L90-L109
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.get_field_type
def get_field_type(cls, name): """ Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a string input into the appropriate format. :rtype: ripozo.viewsets.fields.base.BaseField """ python_type = cls._get_field_python_type(cls.model, name) if python_type in _COLUMN_FIELD_MAP: field_class = _COLUMN_FIELD_MAP[python_type] return field_class(name) return BaseField(name)
python
def get_field_type(cls, name): """ Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a string input into the appropriate format. :rtype: ripozo.viewsets.fields.base.BaseField """ python_type = cls._get_field_python_type(cls.model, name) if python_type in _COLUMN_FIELD_MAP: field_class = _COLUMN_FIELD_MAP[python_type] return field_class(name) return BaseField(name)
[ "def", "get_field_type", "(", "cls", ",", "name", ")", ":", "python_type", "=", "cls", ".", "_get_field_python_type", "(", "cls", ".", "model", ",", "name", ")", "if", "python_type", "in", "_COLUMN_FIELD_MAP", ":", "field_class", "=", "_COLUMN_FIELD_MAP", "[", "python_type", "]", "return", "field_class", "(", "name", ")", "return", "BaseField", "(", "name", ")" ]
Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a string input into the appropriate format. :rtype: ripozo.viewsets.fields.base.BaseField
[ "Takes", "a", "field", "name", "and", "gets", "an", "appropriate", "BaseField", "instance", "for", "that", "column", ".", "It", "inspects", "the", "Model", "that", "is", "set", "on", "the", "manager", "to", "determine", "what", "the", "BaseField", "subclass", "should", "be", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L112-L127
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.create
def create(self, session, values, *args, **kwargs): """ Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will use those fields. Otherwise, it will use the fields defined in cls.fields :param Session session: The sqlalchemy session :return: The serialized model. It will use the self.fields attribute for this. :rtype: dict """ model = self.model() model = self._set_values_on_model(model, values, fields=self.create_fields) session.add(model) session.commit() return self.serialize_model(model)
python
def create(self, session, values, *args, **kwargs): """ Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will use those fields. Otherwise, it will use the fields defined in cls.fields :param Session session: The sqlalchemy session :return: The serialized model. It will use the self.fields attribute for this. :rtype: dict """ model = self.model() model = self._set_values_on_model(model, values, fields=self.create_fields) session.add(model) session.commit() return self.serialize_model(model)
[ "def", "create", "(", "self", ",", "session", ",", "values", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "model", "(", ")", "model", "=", "self", ".", "_set_values_on_model", "(", "model", ",", "values", ",", "fields", "=", "self", ".", "create_fields", ")", "session", ".", "add", "(", "model", ")", "session", ".", "commit", "(", ")", "return", "self", ".", "serialize_model", "(", "model", ")" ]
Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will use those fields. Otherwise, it will use the fields defined in cls.fields :param Session session: The sqlalchemy session :return: The serialized model. It will use the self.fields attribute for this. :rtype: dict
[ "Creates", "a", "new", "instance", "of", "the", "self", ".", "model", "and", "persists", "it", "to", "the", "database", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L130-L150
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.retrieve
def retrieve(self, session, lookup_keys, *args, **kwargs): """ Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) return self.serialize_model(model)
python
def retrieve(self, session, lookup_keys, *args, **kwargs): """ Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) return self.serialize_model(model)
[ "def", "retrieve", "(", "self", ",", "session", ",", "lookup_keys", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "return", "self", ".", "serialize_model", "(", "model", ")" ]
Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException
[ "Retrieves", "a", "model", "using", "the", "lookup", "keys", "provided", ".", "Only", "one", "model", "should", "be", "returned", "by", "the", "lookup_keys", "or", "else", "the", "manager", "will", "fail", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L153-L169
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.retrieve_list
def retrieve_list(self, session, filters, *args, **kwargs): """ Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation of the models and the dictionary of meta data :rtype: list, dict """ query = self.queryset(session) translator = IntegerField('tmp') pagination_count = translator.translate( filters.pop(self.pagination_count_query_arg, self.paginate_by) ) pagination_pk = translator.translate( filters.pop(self.pagination_pk_query_arg, 1) ) pagination_pk -= 1 # logic works zero based. Pagination shouldn't be though query = query.filter_by(**filters) if pagination_pk: query = query.offset(pagination_pk * pagination_count) if pagination_count: query = query.limit(pagination_count + 1) count = query.count() next_link = None previous_link = None if count > pagination_count: next_link = {self.pagination_pk_query_arg: pagination_pk + 2, self.pagination_count_query_arg: pagination_count} if pagination_pk > 0: previous_link = {self.pagination_pk_query_arg: pagination_pk, self.pagination_count_query_arg: pagination_count} field_dict = self.dot_field_list_to_dict(self.list_fields) props = self.serialize_model(query[:pagination_count], field_dict=field_dict) meta = dict(links=dict(next=next_link, previous=previous_link)) return props, meta
python
def retrieve_list(self, session, filters, *args, **kwargs): """ Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation of the models and the dictionary of meta data :rtype: list, dict """ query = self.queryset(session) translator = IntegerField('tmp') pagination_count = translator.translate( filters.pop(self.pagination_count_query_arg, self.paginate_by) ) pagination_pk = translator.translate( filters.pop(self.pagination_pk_query_arg, 1) ) pagination_pk -= 1 # logic works zero based. Pagination shouldn't be though query = query.filter_by(**filters) if pagination_pk: query = query.offset(pagination_pk * pagination_count) if pagination_count: query = query.limit(pagination_count + 1) count = query.count() next_link = None previous_link = None if count > pagination_count: next_link = {self.pagination_pk_query_arg: pagination_pk + 2, self.pagination_count_query_arg: pagination_count} if pagination_pk > 0: previous_link = {self.pagination_pk_query_arg: pagination_pk, self.pagination_count_query_arg: pagination_count} field_dict = self.dot_field_list_to_dict(self.list_fields) props = self.serialize_model(query[:pagination_count], field_dict=field_dict) meta = dict(links=dict(next=next_link, previous=previous_link)) return props, meta
[ "def", "retrieve_list", "(", "self", ",", "session", ",", "filters", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "queryset", "(", "session", ")", "translator", "=", "IntegerField", "(", "'tmp'", ")", "pagination_count", "=", "translator", ".", "translate", "(", "filters", ".", "pop", "(", "self", ".", "pagination_count_query_arg", ",", "self", ".", "paginate_by", ")", ")", "pagination_pk", "=", "translator", ".", "translate", "(", "filters", ".", "pop", "(", "self", ".", "pagination_pk_query_arg", ",", "1", ")", ")", "pagination_pk", "-=", "1", "# logic works zero based. Pagination shouldn't be though", "query", "=", "query", ".", "filter_by", "(", "*", "*", "filters", ")", "if", "pagination_pk", ":", "query", "=", "query", ".", "offset", "(", "pagination_pk", "*", "pagination_count", ")", "if", "pagination_count", ":", "query", "=", "query", ".", "limit", "(", "pagination_count", "+", "1", ")", "count", "=", "query", ".", "count", "(", ")", "next_link", "=", "None", "previous_link", "=", "None", "if", "count", ">", "pagination_count", ":", "next_link", "=", "{", "self", ".", "pagination_pk_query_arg", ":", "pagination_pk", "+", "2", ",", "self", ".", "pagination_count_query_arg", ":", "pagination_count", "}", "if", "pagination_pk", ">", "0", ":", "previous_link", "=", "{", "self", ".", "pagination_pk_query_arg", ":", "pagination_pk", ",", "self", ".", "pagination_count_query_arg", ":", "pagination_count", "}", "field_dict", "=", "self", ".", "dot_field_list_to_dict", "(", "self", ".", "list_fields", ")", "props", "=", "self", ".", "serialize_model", "(", "query", "[", ":", "pagination_count", "]", ",", "field_dict", "=", "field_dict", ")", "meta", "=", "dict", "(", "links", "=", "dict", "(", "next", "=", "next_link", ",", "previous", "=", "previous_link", ")", ")", "return", "props", ",", "meta" ]
Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation of the models and the dictionary of meta data :rtype: list, dict
[ "Retrieves", "a", "list", "of", "the", "model", "for", "this", "manager", ".", "It", "is", "restricted", "by", "the", "filters", "provided", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L172-L214
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.update
def update(self, session, lookup_keys, updates, *args, **kwargs): """ Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to update them to. :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) model = self._set_values_on_model(model, updates, fields=self.update_fields) session.commit() return self.serialize_model(model)
python
def update(self, session, lookup_keys, updates, *args, **kwargs): """ Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to update them to. :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) model = self._set_values_on_model(model, updates, fields=self.update_fields) session.commit() return self.serialize_model(model)
[ "def", "update", "(", "self", ",", "session", ",", "lookup_keys", ",", "updates", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "model", "=", "self", ".", "_set_values_on_model", "(", "model", ",", "updates", ",", "fields", "=", "self", ".", "update_fields", ")", "session", ".", "commit", "(", ")", "return", "self", ".", "serialize_model", "(", "model", ")" ]
Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to update them to. :return: The dictionary of keys and values for the retrieved model. The only values returned will be those specified by fields attrbute on the class :rtype: dict :raises: NotFoundException
[ "Updates", "the", "model", "with", "the", "specified", "lookup_keys", "and", "returns", "the", "dictified", "object", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L217-L236
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.delete
def delete(self, session, lookup_keys, *args, **kwargs): """ Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) session.delete(model) session.commit() return {}
python
def delete(self, session, lookup_keys, *args, **kwargs): """ Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException """ model = self._get_model(lookup_keys, session) session.delete(model) session.commit() return {}
[ "def", "delete", "(", "self", ",", "session", ",", "lookup_keys", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "session", ".", "delete", "(", "model", ")", "session", ".", "commit", "(", ")", "return", "{", "}" ]
Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException
[ "Deletes", "the", "model", "found", "using", "the", "lookup_keys" ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L239-L253
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.serialize_model
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict """ response = self._serialize_model_helper(model, field_dict=field_dict) return make_json_safe(response)
python
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict """ response = self._serialize_model_helper(model, field_dict=field_dict) return make_json_safe(response)
[ "def", "serialize_model", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "response", "=", "self", ".", "_serialize_model_helper", "(", "model", ",", "field_dict", "=", "field_dict", ")", "return", "make_json_safe", "(", "response", ")" ]
Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict
[ "Takes", "a", "model", "and", "serializes", "the", "fields", "provided", "into", "a", "dictionary", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L264-L275
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._serialize_model_helper
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query): model = model.all() if isinstance(model, (list, set)): return [self.serialize_model(m, field_dict=field_dict) for m in model] model_dict = {} for name, sub in six.iteritems(field_dict): value = getattr(model, name) if sub: value = self.serialize_model(value, field_dict=sub) model_dict[name] = value return model_dict
python
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query): model = model.all() if isinstance(model, (list, set)): return [self.serialize_model(m, field_dict=field_dict) for m in model] model_dict = {} for name, sub in six.iteritems(field_dict): value = getattr(model, name) if sub: value = self.serialize_model(value, field_dict=sub) model_dict[name] = value return model_dict
[ "def", "_serialize_model_helper", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "field_dict", "=", "field_dict", "or", "self", ".", "dot_field_list_to_dict", "(", ")", "if", "model", "is", "None", ":", "return", "None", "if", "isinstance", "(", "model", ",", "Query", ")", ":", "model", "=", "model", ".", "all", "(", ")", "if", "isinstance", "(", "model", ",", "(", "list", ",", "set", ")", ")", ":", "return", "[", "self", ".", "serialize_model", "(", "m", ",", "field_dict", "=", "field_dict", ")", "for", "m", "in", "model", "]", "model_dict", "=", "{", "}", "for", "name", ",", "sub", "in", "six", ".", "iteritems", "(", "field_dict", ")", ":", "value", "=", "getattr", "(", "model", ",", "name", ")", "if", "sub", ":", "value", "=", "self", ".", "serialize_model", "(", "value", ",", "field_dict", "=", "sub", ")", "model_dict", "[", "name", "]", "=", "value", "return", "model_dict" ]
A recursive function for serializing a model into a json ready format.
[ "A", "recursive", "function", "for", "serializing", "a", "model", "into", "a", "json", "ready", "format", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L277-L298
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._get_model
def _get_model(self, lookup_keys, session): """ Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance. """ try: return self.queryset(session).filter_by(**lookup_keys).one() except NoResultFound: raise NotFoundException('No model of type {0} was found using ' 'lookup_keys {1}'.format(self.model.__name__, lookup_keys))
python
def _get_model(self, lookup_keys, session): """ Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance. """ try: return self.queryset(session).filter_by(**lookup_keys).one() except NoResultFound: raise NotFoundException('No model of type {0} was found using ' 'lookup_keys {1}'.format(self.model.__name__, lookup_keys))
[ "def", "_get_model", "(", "self", ",", "lookup_keys", ",", "session", ")", ":", "try", ":", "return", "self", ".", "queryset", "(", "session", ")", ".", "filter_by", "(", "*", "*", "lookup_keys", ")", ".", "one", "(", ")", "except", "NoResultFound", ":", "raise", "NotFoundException", "(", "'No model of type {0} was found using '", "'lookup_keys {1}'", ".", "format", "(", "self", ".", "model", ".", "__name__", ",", "lookup_keys", ")", ")" ]
Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance.
[ "Gets", "the", "sqlalchemy", "Model", "instance", "associated", "with", "the", "lookup", "keys", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L300-L314
train
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._set_values_on_model
def _set_values_on_model(self, model, values, fields=None): """ Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :return: The model with the updated :rtype: Model """ fields = fields or self.fields for name, val in six.iteritems(values): if name not in fields: continue setattr(model, name, val) return model
python
def _set_values_on_model(self, model, values, fields=None): """ Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :return: The model with the updated :rtype: Model """ fields = fields or self.fields for name, val in six.iteritems(values): if name not in fields: continue setattr(model, name, val) return model
[ "def", "_set_values_on_model", "(", "self", ",", "model", ",", "values", ",", "fields", "=", "None", ")", ":", "fields", "=", "fields", "or", "self", ".", "fields", "for", "name", ",", "val", "in", "six", ".", "iteritems", "(", "values", ")", ":", "if", "name", "not", "in", "fields", ":", "continue", "setattr", "(", "model", ",", "name", ",", "val", ")", "return", "model" ]
Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :return: The model with the updated :rtype: Model
[ "Updates", "the", "values", "with", "the", "specified", "values", "." ]
4bcc57ec6db1b39b84b50553bb264e4950ce4ec2
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L316-L333
train
gforcada/haproxy_log_analysis
haproxy/main.py
print_commands
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if description: description = re.sub(r'\n\s+', ' ', description) description = description.strip() print('{0}: {1}\n'.format(cmd.__name__, description))
python
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if description: description = re.sub(r'\n\s+', ' ', description) description = description.strip() print('{0}: {1}\n'.format(cmd.__name__, description))
[ "def", "print_commands", "(", ")", ":", "dummy_log_file", "=", "Log", "(", ")", "commands", "=", "Log", ".", "commands", "(", ")", "commands", ".", "sort", "(", ")", "for", "cmd", "in", "commands", ":", "cmd", "=", "getattr", "(", "dummy_log_file", ",", "'cmd_{0}'", ".", "format", "(", "cmd", ")", ")", "description", "=", "cmd", ".", "__doc__", "if", "description", ":", "description", "=", "re", ".", "sub", "(", "r'\\n\\s+'", ",", "' '", ",", "description", ")", "description", "=", "description", ".", "strip", "(", ")", "print", "(", "'{0}: {1}\\n'", ".", "format", "(", "cmd", ".", "__name__", ",", "description", ")", ")" ]
Prints all commands available from Log with their description.
[ "Prints", "all", "commands", "available", "from", "Log", "with", "their", "description", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/main.py#L191-L206
train
gforcada/haproxy_log_analysis
haproxy/main.py
print_filters
def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: description = re.sub(r'\n\s+', ' ', description) description.strip() print('{0}: {1}\n'.format(filter_name, description))
python
def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: description = re.sub(r'\n\s+', ' ', description) description.strip() print('{0}: {1}\n'.format(filter_name, description))
[ "def", "print_filters", "(", ")", ":", "for", "filter_name", "in", "VALID_FILTERS", ":", "filter_func", "=", "getattr", "(", "filters", ",", "'filter_{0}'", ".", "format", "(", "filter_name", ")", ")", "description", "=", "filter_func", ".", "__doc__", "if", "description", ":", "description", "=", "re", ".", "sub", "(", "r'\\n\\s+'", ",", "' '", ",", "description", ")", "description", ".", "strip", "(", ")", "print", "(", "'{0}: {1}\\n'", ".", "format", "(", "filter_name", ",", "description", ")", ")" ]
Prints all filters available with their description.
[ "Prints", "all", "filters", "available", "with", "their", "description", "." ]
a899895359bd4df6f35e279ad75c32c5afcfe916
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/main.py#L209-L218
train
Kentzo/Power
power/common.py
PowerManagementBase.add_observer
def add_observer(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class """ if not isinstance(observer, PowerManagementObserver): raise TypeError("observer MUST conform to power.PowerManagementObserver") self._weak_observers.append(weakref.ref(observer))
python
def add_observer(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class """ if not isinstance(observer, PowerManagementObserver): raise TypeError("observer MUST conform to power.PowerManagementObserver") self._weak_observers.append(weakref.ref(observer))
[ "def", "add_observer", "(", "self", ",", "observer", ")", ":", "if", "not", "isinstance", "(", "observer", ",", "PowerManagementObserver", ")", ":", "raise", "TypeError", "(", "\"observer MUST conform to power.PowerManagementObserver\"", ")", "self", ".", "_weak_observers", ".", "append", "(", "weakref", ".", "ref", "(", "observer", ")", ")" ]
Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class
[ "Adds", "weak", "ref", "to", "an", "observer", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/common.py#L115-L124
train
Kentzo/Power
power/common.py
PowerManagementBase.remove_all_observers
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
python
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
[ "def", "remove_all_observers", "(", "self", ")", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "self", ".", "remove_observer", "(", "observer", ")" ]
Removes all registered observers.
[ "Removes", "all", "registered", "observers", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/common.py#L135-L142
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.startThread
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
python
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
[ "def", "startThread", "(", "self", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "return", "self", ".", "_thread", "=", "NSThread", ".", "alloc", "(", ")", ".", "initWithTarget_selector_object_", "(", "self", ",", "'runPowerNotificationsThread'", ",", "None", ")", "self", ".", "_thread", ".", "start", "(", ")" ]
Spawns new NSThread to handle notifications.
[ "Spawns", "new", "NSThread", "to", "handle", "notifications", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L177-L182
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.stopThread
def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
python
def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
[ "def", "stopThread", "(", "self", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "self", ".", "performSelector_onThread_withObject_waitUntilDone_", "(", "'stopPowerNotificationsThread'", ",", "self", ".", "_thread", ",", "None", ",", "objc", ".", "YES", ")", "self", ".", "_thread", "=", "None" ]
Stops spawned NSThread.
[ "Stops", "spawned", "NSThread", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L184-L188
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.runPowerNotificationsThread
def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): with self._lock: for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop().getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) del pool
python
def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): with self._lock: for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop().getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) del pool
[ "def", "runPowerNotificationsThread", "(", "self", ")", ":", "pool", "=", "NSAutoreleasePool", ".", "alloc", "(", ")", ".", "init", "(", ")", "@", "objc", ".", "callbackFor", "(", "IOPSNotificationCreateRunLoopSource", ")", "def", "on_power_source_notification", "(", "context", ")", ":", "with", "self", ".", "_lock", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "observer", ".", "on_power_source_notification", "(", ")", "self", ".", "_source", "=", "IOPSNotificationCreateRunLoopSource", "(", "on_power_source_notification", ",", "None", ")", "CFRunLoopAddSource", "(", "NSRunLoop", ".", "currentRunLoop", "(", ")", ".", "getCFRunLoop", "(", ")", ",", "self", ".", "_source", ",", "kCFRunLoopDefaultMode", ")", "while", "not", "NSThread", ".", "currentThread", "(", ")", ".", "isCancelled", "(", ")", ":", "NSRunLoop", ".", "currentRunLoop", "(", ")", ".", "runMode_beforeDate_", "(", "NSDefaultRunLoopMode", ",", "NSDate", ".", "distantFuture", "(", ")", ")", "del", "pool" ]
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.
[ "Main", "method", "of", "the", "spawned", "NSThread", ".", "Registers", "run", "loop", "source", "and", "runs", "current", "NSRunLoop", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L190-L206
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.stopPowerNotificationsThread
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
python
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
[ "def", "stopPowerNotificationsThread", "(", "self", ")", ":", "assert", "NSThread", ".", "currentThread", "(", ")", "==", "self", ".", "_thread", "CFRunLoopSourceInvalidate", "(", "self", ".", "_source", ")", "self", ".", "_source", "=", "None", "NSThread", ".", "currentThread", "(", ")", ".", "cancel", "(", ")" ]
Removes the only source from NSRunLoop and cancels thread.
[ "Removes", "the", "only", "source", "from", "NSRunLoop", "and", "cancels", "thread", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L209-L215
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.addObserver
def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1: self.startThread()
python
def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1: self.startThread()
[ "def", "addObserver", "(", "self", ",", "observer", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_weak_observers", ".", "append", "(", "weakref", ".", "ref", "(", "observer", ")", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "1", ":", "self", ".", "startThread", "(", ")" ]
Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification()
[ "Adds", "weak", "ref", "to", "an", "observer", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L217-L226
train
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.removeObserver
def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
python
def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
[ "def", "removeObserver", "(", "self", ",", "observer", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_weak_observers", ".", "remove", "(", "weakref", ".", "ref", "(", "observer", ")", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "0", ":", "self", ".", "stopThread", "(", ")" ]
Removes an observer. @param observer: Previously added observer
[ "Removes", "an", "observer", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L228-L237
train
Kentzo/Power
power/darwin.py
PowerManagement.on_power_source_notification
def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) observer.on_time_remaining_change(self)
python
def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) observer.on_time_remaining_change(self)
[ "def", "on_power_source_notification", "(", "self", ")", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "observer", ".", "on_power_sources_change", "(", "self", ")", "observer", ".", "on_time_remaining_change", "(", "self", ")" ]
Called in response to IOPSNotificationCreateRunLoopSource() event.
[ "Called", "in", "response", "to", "IOPSNotificationCreateRunLoopSource", "()", "event", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L250-L258
train
Kentzo/Power
power/darwin.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """ if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+ estimate = float(IOPSGetTimeRemainingEstimate()) if estimate == -1.0: return common.TIME_REMAINING_UNKNOWN elif estimate == -2.0: return common.TIME_REMAINING_UNLIMITED else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn("IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """ if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+ estimate = float(IOPSGetTimeRemainingEstimate()) if estimate == -1.0: return common.TIME_REMAINING_UNKNOWN elif estimate == -2.0: return common.TIME_REMAINING_UNLIMITED else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn("IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "if", "IOPSGetTimeRemainingEstimate", "is", "not", "None", ":", "# Mac OS X 10.7+", "estimate", "=", "float", "(", "IOPSGetTimeRemainingEstimate", "(", ")", ")", "if", "estimate", "==", "-", "1.0", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "elif", "estimate", "==", "-", "2.0", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "else", ":", "return", "estimate", "/", "60.0", "else", ":", "# Mac OS X 10.6", "warnings", ".", "warn", "(", "\"IOPSGetTimeRemainingEstimate is not preset\"", ",", "RuntimeWarning", ")", "blob", "=", "IOPSCopyPowerSourcesInfo", "(", ")", "type", "=", "IOPSGetProvidingPowerSourceType", "(", "blob", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "else", ":", "estimate", "=", "0.0", "for", "source", "in", "IOPSCopyPowerSourcesList", "(", "blob", ")", ":", "description", "=", "IOPSGetPowerSourceDescription", "(", "blob", ",", "source", ")", "if", "kIOPSIsPresentKey", "in", "description", "and", "description", "[", "kIOPSIsPresentKey", "]", "and", "kIOPSTimeToEmptyKey", "in", "description", "and", "description", "[", "kIOPSTimeToEmptyKey", "]", ">", "0.0", ":", "estimate", "+=", "float", "(", "description", "[", "kIOPSTimeToEmptyKey", "]", ")", "if", "estimate", ">", "0.0", ":", "return", "float", "(", "estimate", ")", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate.
[ "In", "Mac", "OS", "X", "10", ".", "7", "+", "Uses", "IOPSGetTimeRemainingEstimate", "to", "get", "time", "remaining", "estimate", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L276-L310
train
Kentzo/Power
power/darwin.py
PowerManagement.add_observer
def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop: PowerManagement.notifications_observer.addObserver(self) else: @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode)
python
def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop: PowerManagement.notifications_observer.addObserver(self) else: @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode)
[ "def", "add_observer", "(", "self", ",", "observer", ")", ":", "super", "(", "PowerManagement", ",", "self", ")", ".", "add_observer", "(", "observer", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "1", ":", "if", "not", "self", ".", "_cf_run_loop", ":", "PowerManagement", ".", "notifications_observer", ".", "addObserver", "(", "self", ")", "else", ":", "@", "objc", ".", "callbackFor", "(", "IOPSNotificationCreateRunLoopSource", ")", "def", "on_power_sources_change", "(", "context", ")", ":", "self", ".", "on_power_source_notification", "(", ")", "self", ".", "_source", "=", "IOPSNotificationCreateRunLoopSource", "(", "on_power_sources_change", ",", "None", ")", "CFRunLoopAddSource", "(", "self", ".", "_cf_run_loop", ",", "self", ".", "_source", ",", "kCFRunLoopDefaultMode", ")" ]
Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__
[ "Spawns", "thread", "or", "adds", "IOPSNotificationCreateRunLoopSource", "directly", "to", "provided", "cf_run_loop" ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L312-L327
train
Kentzo/Power
power/darwin.py
PowerManagement.remove_observer
def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver(self) else: CFRunLoopSourceInvalidate(self._source) self._source = None
python
def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver(self) else: CFRunLoopSourceInvalidate(self._source) self._source = None
[ "def", "remove_observer", "(", "self", ",", "observer", ")", ":", "super", "(", "PowerManagement", ",", "self", ")", ".", "remove_observer", "(", "observer", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "0", ":", "if", "not", "self", ".", "_cf_run_loop", ":", "PowerManagement", ".", "notifications_observer", ".", "removeObserver", "(", "self", ")", "else", ":", "CFRunLoopSourceInvalidate", "(", "self", ".", "_source", ")", "self", ".", "_source", "=", "None" ]
Stops thread and invalidates source.
[ "Stops", "thread", "and", "invalidates", "source", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L329-L339
train
Kentzo/Power
power/win32.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() return POWER_TYPE_MAP[power_status.ACLineStatus]
python
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() return POWER_TYPE_MAP[power_status.ACLineStatus]
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "return", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]" ]
Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures.
[ "Returns", "GetSystemPowerStatus", "()", ".", "ACLineStatus" ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L45-L54
train
Kentzo/Power
power/win32.py
PowerManagement.get_low_battery_warning_level
def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE else: if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600: return common.LOW_BATTERY_WARNING_FINAL elif power_status.BatteryLifePercent <= 22: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE
python
def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE else: if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600: return common.LOW_BATTERY_WARNING_FINAL elif power_status.BatteryLifePercent <= 22: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE
[ "def", "get_low_battery_warning_level", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "if", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "else", ":", "if", "power_status", ".", "BatteryLifeTime", "!=", "-", "1", "and", "power_status", ".", "BatteryLifeTime", "<=", "600", ":", "return", "common", ".", "LOW_BATTERY_WARNING_FINAL", "elif", "power_status", ".", "BatteryLifePercent", "<=", "22", ":", "return", "common", ".", "LOW_BATTERY_WARNING_EARLY", "else", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE" ]
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures.
[ "Returns", "warning", "according", "to", "GetSystemPowerStatus", "()", ".", "BatteryLifeTime", "/", "BatteryLifePercent" ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L56-L74
train
Kentzo/Power
power/win32.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED elif power_status.BatteryLifeTime == -1: return common.TIME_REMAINING_UNKNOWN else: return float(power_status.BatteryLifeTime) / 60.0
python
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED elif power_status.BatteryLifeTime == -1: return common.TIME_REMAINING_UNKNOWN else: return float(power_status.BatteryLifeTime) / 60.0
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "if", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "power_status", ".", "BatteryLifeTime", "==", "-", "1", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "float", "(", "power_status", ".", "BatteryLifeTime", ")", "/", "60.0" ]
Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime
[ "Returns", "time", "remaining", "estimate", "according", "to", "GetSystemPowerStatus", "()", ".", "BatteryLifeTime" ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L76-L89
train
Kentzo/Power
power/freebsd.py
PowerManagement.power_source_type
def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return common.POWER_TYPE_AC if supply == 1: return common.POWER_TYPE_AC elif supply == 0: return common.POWER_TYPE_BATTERY else: raise RuntimeError("Unknown power source type!")
python
def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return common.POWER_TYPE_AC if supply == 1: return common.POWER_TYPE_AC elif supply == 0: return common.POWER_TYPE_BATTERY else: raise RuntimeError("Unknown power source type!")
[ "def", "power_source_type", "(", ")", ":", "try", ":", "supply", "=", "int", "(", "subprocess", ".", "check_output", "(", "[", "\"sysctl\"", ",", "\"-n\"", ",", "\"hw.acpi.acline\"", "]", ")", ")", "except", ":", "return", "common", ".", "POWER_TYPE_AC", "if", "supply", "==", "1", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "supply", "==", "0", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "raise", "RuntimeError", "(", "\"Unknown power source type!\"", ")" ]
FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported
[ "FreeBSD", "use", "sysctl", "hw", ".", "acpi", ".", "acline", "to", "tell", "if", "Mains", "(", "1", ")", "is", "used", "or", "Battery", "(", "0", ")", ".", "Beware", "that", "on", "a", "Desktop", "machines", "this", "hw", ".", "acpi", ".", "acline", "oid", "may", "not", "exist", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L13-L30
train
Kentzo/Power
power/freebsd.py
PowerManagement.get_battery_state
def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now
python
def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now
[ "def", "get_battery_state", "(", ")", ":", "energy_now", "=", "float", "(", "100.0", ")", "power_now", "=", "float", "(", "100.0", ")", "energy_full", "=", "float", "(", "100.0", ")", "return", "energy_full", ",", "energy_now", ",", "power_now" ]
TODO @return: Tuple (energy_full, energy_now, power_now)
[ "TODO" ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L64-L72
train
Kentzo/Power
power/freebsd.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") return common.POWER_TYPE_AC
python
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") return common.POWER_TYPE_AC
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", ")", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "return", "common", ".", "POWER_TYPE_AC" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", ".", "If", "there", "is", "a", "discharging", "battery", "returns", "POWER_TYPE_BATTERY", ".", "Since", "the", "order", "of", "supplies", "is", "arbitrary", "whatever", "found", "first", "is", "returned", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L75-L91
train
Kentzo/Power
power/freebsd.py
PowerManagement.get_low_battery_warning_level
def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE
python
def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE
[ "def", "get_low_battery_warning_level", "(", "self", ")", ":", "all_energy_full", "=", "[", "]", "all_energy_now", "=", "[", "]", "all_power_now", "=", "[", "]", "try", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", ")", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", ")", "all_energy_full", ".", "append", "(", "energy_full", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read system power information!\"", ",", "category", "=", "RuntimeWarning", ")", "try", ":", "total_percentage", "=", "sum", "(", "all_energy_full", ")", "/", "sum", "(", "all_energy_now", ")", "total_time", "=", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "if", "total_time", "<=", "10.0", ":", "return", "common", ".", "LOW_BATTERY_WARNING_FINAL", "elif", "total_percentage", "<=", "22.0", ":", "return", "common", ".", "LOW_BATTERY_WARNING_EARLY", "else", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate low battery level: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "LOW_BATTERY_WARNING_NONE" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", "returns", "LOW_BATTERY_WARNING_NONE", ".", "Otherwise", "determines", "total", "percentage", "and", "time", "remaining", "across", "all", "attached", "batteries", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L94-L130
train
Kentzo/Power
power/freebsd.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "all_energy_now", "=", "[", "]", "all_power_now", "=", "[", "]", "try", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read system power information!\"", ",", "category", "=", "RuntimeWarning", ")", "if", "len", "(", "all_energy_now", ")", ">", "0", ":", "try", ":", "return", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate time remaining estimate: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
[ "Looks", "through", "all", "power", "sources", "and", "returns", "total", "time", "remaining", "estimate", "or", "TIME_REMAINING_UNLIMITED", "if", "ac", "power", "supply", "is", "online", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L133-L162
train
Kentzo/Power
power/linux.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) return common.POWER_TYPE_AC
python
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) return common.POWER_TYPE_AC
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "for", "supply", "in", "os", ".", "listdir", "(", "POWER_SUPPLY_PATH", ")", ":", "supply_path", "=", "os", ".", "path", ".", "join", "(", "POWER_SUPPLY_PATH", ",", "supply", ")", "try", ":", "type", "=", "self", ".", "power_source_type", "(", "supply_path", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read properties of {0}: {1}\"", ".", "format", "(", "supply_path", ",", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "POWER_TYPE_AC" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", ".", "If", "there", "is", "a", "discharging", "battery", "returns", "POWER_TYPE_BATTERY", ".", "Since", "the", "order", "of", "supplies", "is", "arbitrary", "whatever", "found", "first", "is", "returned", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/linux.py#L88-L110
train
Kentzo/Power
power/linux.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_now.append(energy_now) all_power_now.append(power_now) elif self.is_battery_present(supply_path) and not self.is_battery_discharging(supply_path): energy_now = self.get_battery_state(supply_path)[1] all_energy_not_discharging.append(energy_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])\ + sum(all_energy_not_discharging) / (sum(all_power_now) / len(all_power_now)) * 60.0 except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_now.append(energy_now) all_power_now.append(power_now) elif self.is_battery_present(supply_path) and not self.is_battery_discharging(supply_path): energy_now = self.get_battery_state(supply_path)[1] all_energy_not_discharging.append(energy_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])\ + sum(all_energy_not_discharging) / (sum(all_power_now) / len(all_power_now)) * 60.0 except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "all_energy_now", "=", "[", "]", "all_energy_not_discharging", "=", "[", "]", "all_power_now", "=", "[", "]", "for", "supply", "in", "os", ".", "listdir", "(", "POWER_SUPPLY_PATH", ")", ":", "supply_path", "=", "os", ".", "path", ".", "join", "(", "POWER_SUPPLY_PATH", ",", "supply", ")", "try", ":", "type", "=", "self", ".", "power_source_type", "(", "supply_path", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", "supply_path", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "elif", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "not", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "energy_now", "=", "self", ".", "get_battery_state", "(", "supply_path", ")", "[", "1", "]", "all_energy_not_discharging", ".", "append", "(", "energy_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read properties of {0}: {1}\"", ".", "format", "(", "supply_path", ",", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "if", "len", "(", "all_energy_now", ")", ">", "0", ":", "try", ":", "return", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "+", "sum", "(", "all_energy_not_discharging", ")", "/", "(", "sum", "(", "all_power_now", ")", "/", "len", "(", "all_power_now", ")", ")", "*", "60.0", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate time remaining estimate: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
[ "Looks", "through", "all", "power", "sources", "and", "returns", "total", "time", "remaining", "estimate", "or", "TIME_REMAINING_UNLIMITED", "if", "ac", "power", "supply", "is", "online", "." ]
2c99b156546225e448f7030681af3df5cd345e4b
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/linux.py#L152-L188
train