repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
sashahart/vex
vex/options.py
get_options
python
def get_options(argv): arg_parser = make_arg_parser() options, unknown = arg_parser.parse_known_args(argv) if unknown: arg_parser.print_help() raise exceptions.UnknownArguments( "unknown args: {0!r}".format(unknown)) options.print_help = arg_parser.print_help return optio...
Called to parse the given list as command-line arguments. :returns: an options object as returned by argparse.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/options.py#L94-L107
[ "def make_arg_parser():\n \"\"\"Return a standard ArgumentParser object.\n \"\"\"\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter,\n usage=\"vex [OPTIONS] VIRTUALENV_NAME COMMAND_TO_RUN ...\",\n )\n\n make = parser.add_argument_group(title='To make a ...
import argparse from vex import exceptions def make_arg_parser(): """Return a standard ArgumentParser object. """ parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, usage="vex [OPTIONS] VIRTUALENV_NAME COMMAND_TO_RUN ...", ) make = parser.add_argument...
sashahart/vex
vex/main.py
get_vexrc
python
def get_vexrc(options, environ): # Complain if user specified nonexistent file with --config. # But we don't want to complain just because ~/.vexrc doesn't exist. if options.config and not os.path.exists(options.config): raise exceptions.InvalidVexrc("nonexistent config: {0!r}".format(options.config...
Get a representation of the contents of the config file. :returns: a Vexrc instance.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L15-L27
[ "def from_file(cls, path, environ):\n \"\"\"Make a Vexrc instance from given file in given environ.\n \"\"\"\n instance = cls()\n instance.read(path, environ)\n return instance\n" ]
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/main.py
get_cwd
python
def get_cwd(options): if not options.cwd: return None if not os.path.exists(options.cwd): raise exceptions.InvalidCwd( "can't --cwd to invalid path {0!r}".format(options.cwd)) return options.cwd
Discover what directory the command should run in.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L30-L38
null
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/main.py
get_virtualenv_path
python
def get_virtualenv_path(ve_base, ve_name): if not ve_base: raise exceptions.NoVirtualenvsDirectory( "could not figure out a virtualenvs directory. " "make sure $HOME is set, or $WORKON_HOME," " or set virtualenvs=something in your .vexrc") # Using this requires get_v...
Check a virtualenv path, raising exceptions to explain problems.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L53-L88
null
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/main.py
get_command
python
def get_command(options, vexrc, environ): command = options.rest if not command: command = vexrc.get_shell(environ) if command and command[0].startswith('--'): raise exceptions.InvalidCommand( "don't put flags like '%s' after the virtualenv name." % command[0]) if...
Get a command to run. :returns: a list of strings representing a command to be passed to Popen.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L91-L106
[ "def get_shell(self, environ):\n \"\"\"Find a command to run.\n \"\"\"\n command = self.headings[self.default_heading].get('shell')\n if not command and os.name != 'nt':\n command = environ.get('SHELL', '')\n command = shlex.split(command) if command else None\n return command\n" ]
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/main.py
_main
python
def _main(environ, argv): options = get_options(argv) if options.version: return handle_version() vexrc = get_vexrc(options, environ) # Handle --shell-config as soon as its arguments are available. if options.shell_to_configure: return handle_shell_config(options.shell_to_configure, ...
Logic for main(), with less direct system interaction. Routines called here raise InvalidArgument with messages that should be delivered on stderr, to be caught by main.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L130-L182
[ "def run(command, env, cwd):\n \"\"\"Run the given command.\n \"\"\"\n assert command\n if cwd:\n assert os.path.exists(cwd)\n if platform.system() == \"Windows\":\n exe = distutils.spawn.find_executable(command[0], path=env['PATH'])\n if exe:\n command[0] = exe\n _...
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/main.py
main
python
def main(): argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n') else: raise sys.exit(returncode)
The main command-line entry point, with system interactions.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L185-L197
[ "def _main(environ, argv):\n \"\"\"Logic for main(), with less direct system interaction.\n\n Routines called here raise InvalidArgument with messages that\n should be delivered on stderr, to be caught by main.\n \"\"\"\n options = get_options(argv)\n if options.version:\n return handle_ver...
"""Main command-line entry-point and any code tightly coupled to it. """ import sys import os from vex import config from vex.options import get_options from vex.run import get_environ, run from vex.shell_config import handle_shell_config from vex.make import handle_make from vex.remove import handle_remove from vex im...
sashahart/vex
vex/shell_config.py
scary_path
python
def scary_path(path): if not path: return True assert isinstance(path, bytes) return not NOT_SCARY.match(path)
Whitelist the WORKON_HOME strings we're willing to substitute in to strings that we provide for user's shell to evaluate. If it smells at all bad, return True.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L22-L31
null
""" This is not needed to use vex. It just lets us provide a convenient mechanism for people with popular shells to set up autocompletion. """ import os import sys import re from vex import exceptions try: FileNotFoundError except NameError: FileNotFoundError = IOError # (OSError, IOError) NOT_SCARY = r...
sashahart/vex
vex/shell_config.py
shell_config_for
python
def shell_config_for(shell, vexrc, environ): here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, 'shell_configs', shell) try: with open(path, 'rb') as inp: data = inp.read() except FileNotFoundError as error: if error.errno != 2: raise ...
return completion config for the named shell.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L34-L49
[ "def scary_path(path):\n \"\"\"Whitelist the WORKON_HOME strings we're willing to substitute in\n to strings that we provide for user's shell to evaluate.\n\n If it smells at all bad, return True.\n \"\"\"\n if not path:\n return True\n assert isinstance(path, bytes)\n return not NOT_SCA...
""" This is not needed to use vex. It just lets us provide a convenient mechanism for people with popular shells to set up autocompletion. """ import os import sys import re from vex import exceptions try: FileNotFoundError except NameError: FileNotFoundError = IOError # (OSError, IOError) NOT_SCARY = r...
sashahart/vex
vex/shell_config.py
handle_shell_config
python
def handle_shell_config(shell, vexrc, environ): from vex import shell_config data = shell_config.shell_config_for(shell, vexrc, environ) if not data: raise exceptions.OtherShell("unknown shell: {0!r}".format(shell)) if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(data) else...
Carry out the logic of the --shell-config option.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L52-L63
[ "def shell_config_for(shell, vexrc, environ):\n \"\"\"return completion config for the named shell.\n \"\"\"\n here = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(here, 'shell_configs', shell)\n try:\n with open(path, 'rb') as inp:\n data = inp.read()\n except...
""" This is not needed to use vex. It just lets us provide a convenient mechanism for people with popular shells to set up autocompletion. """ import os import sys import re from vex import exceptions try: FileNotFoundError except NameError: FileNotFoundError = IOError # (OSError, IOError) NOT_SCARY = r...
sashahart/vex
vex/run.py
get_environ
python
def get_environ(environ, defaults, ve_path): # Copy the parent environment, add in defaults from .vexrc. env = environ.copy() env.update(defaults) # Leaving in existing PYTHONHOME can cause some errors if 'PYTHONHOME' in env: del env['PYTHONHOME'] # Now we have to adjust PATH to find s...
Make an environment to run with.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/run.py#L10-L64
null
"""Run subprocess. """ import os import platform import subprocess import distutils.spawn from vex import exceptions def run(command, env, cwd): """Run the given command. """ assert command if cwd: assert os.path.exists(cwd) if platform.system() == "Windows": exe = distutils.spawn...
sashahart/vex
vex/run.py
run
python
def run(command, env, cwd): assert command if cwd: assert os.path.exists(cwd) if platform.system() == "Windows": exe = distutils.spawn.find_executable(command[0], path=env['PATH']) if exe: command[0] = exe _, command_name = os.path.split(command[0]) if (command_na...
Run the given command.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/run.py#L67-L88
null
"""Run subprocess. """ import os import platform import subprocess import distutils.spawn from vex import exceptions def get_environ(environ, defaults, ve_path): """Make an environment to run with. """ # Copy the parent environment, add in defaults from .vexrc. env = environ.copy() env.update(defa...
sashahart/vex
vex/config.py
extract_key_value
python
def extract_key_value(line, environ): segments = line.split("=", 1) if len(segments) < 2: return None key, value = segments # foo passes through as-is (with spaces stripped) # '{foo}' passes through literally # "{foo}" substitutes from environ's foo value = value.strip() if value...
Return key, value from given line if present, else return None.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L129-L147
null
"""Config file processing (.vexrc). """ import os import sys import re import shlex import platform from collections import OrderedDict _IDENTIFIER_PATTERN = '[a-zA-Z][_a-zA-Z0-9]*' _SQUOTE_RE = re.compile(r"'([^']*)'\Z") # NO squotes inside _DQUOTE_RE = re.compile(r'"([^"]*)"\Z') # NO dquotes inside _HEADING_RE = r...
sashahart/vex
vex/config.py
parse_vexrc
python
def parse_vexrc(inp, environ): heading = None errors = [] with inp: for line_number, line in enumerate(inp): line = line.decode("utf-8") if not line.strip(): continue extracted_heading = extract_heading(line) if extracted_heading is not...
Iterator yielding key/value pairs from given stream. yields tuples of heading, key, value.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L150-L175
[ "def extract_heading(line):\n \"\"\"Return heading in given line or None if it's not a heading.\n \"\"\"\n match = _HEADING_RE.match(line)\n if match:\n return match.group(1)\n return None\n", "def extract_key_value(line, environ):\n \"\"\"Return key, value from given line if present, els...
"""Config file processing (.vexrc). """ import os import sys import re import shlex import platform from collections import OrderedDict _IDENTIFIER_PATTERN = '[a-zA-Z][_a-zA-Z0-9]*' _SQUOTE_RE = re.compile(r"'([^']*)'\Z") # NO squotes inside _DQUOTE_RE = re.compile(r'"([^"]*)"\Z') # NO dquotes inside _HEADING_RE = r...
sashahart/vex
vex/config.py
Vexrc.from_file
python
def from_file(cls, path, environ): instance = cls() instance.read(path, environ) return instance
Make a Vexrc instance from given file in given environ.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L54-L59
[ "def read(self, path, environ):\n \"\"\"Read data from file into this vexrc instance.\n \"\"\"\n try:\n inp = open(path, 'rb')\n except FileNotFoundError as error:\n if error.errno != 2:\n raise\n return None\n parsing = parse_vexrc(inp, environ)\n for heading, key,...
class Vexrc(object): """Parsed representation of a .vexrc config file. """ default_heading = "root" default_encoding = "utf-8" def __init__(self): self.encoding = self.default_encoding self.headings = OrderedDict() self.headings[self.default_heading] = OrderedDict() ...
sashahart/vex
vex/config.py
Vexrc.read
python
def read(self, path, environ): try: inp = open(path, 'rb') except FileNotFoundError as error: if error.errno != 2: raise return None parsing = parse_vexrc(inp, environ) for heading, key, value in parsing: heading = self.defa...
Read data from file into this vexrc instance.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L61-L76
[ "def parse_vexrc(inp, environ):\n \"\"\"Iterator yielding key/value pairs from given stream.\n\n yields tuples of heading, key, value.\n \"\"\"\n heading = None\n errors = []\n with inp:\n for line_number, line in enumerate(inp):\n line = line.decode(\"utf-8\")\n if no...
class Vexrc(object): """Parsed representation of a .vexrc config file. """ default_heading = "root" default_encoding = "utf-8" def __init__(self): self.encoding = self.default_encoding self.headings = OrderedDict() self.headings[self.default_heading] = OrderedDict() ...
sashahart/vex
vex/config.py
Vexrc.get_ve_base
python
def get_ve_base(self, environ): # set ve_base to a path we can look for virtualenvs: # 1. .vexrc # 2. WORKON_HOME (as defined for virtualenvwrapper's benefit) # 3. $HOME/.virtualenvs # (unless we got --path, then we don't need it) ve_base_value = self.headings[self.defaul...
Find a directory to look for virtualenvs in.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L78-L108
null
class Vexrc(object): """Parsed representation of a .vexrc config file. """ default_heading = "root" default_encoding = "utf-8" def __init__(self): self.encoding = self.default_encoding self.headings = OrderedDict() self.headings[self.default_heading] = OrderedDict() ...
sashahart/vex
vex/config.py
Vexrc.get_shell
python
def get_shell(self, environ): command = self.headings[self.default_heading].get('shell') if not command and os.name != 'nt': command = environ.get('SHELL', '') command = shlex.split(command) if command else None return command
Find a command to run.
train
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L110-L117
null
class Vexrc(object): """Parsed representation of a .vexrc config file. """ default_heading = "root" default_encoding = "utf-8" def __init__(self): self.encoding = self.default_encoding self.headings = OrderedDict() self.headings[self.default_heading] = OrderedDict() ...
sensu-plugins/sensu-plugin-python
sensu_plugin/plugin.py
SensuPlugin.output
python
def output(self, args): ''' Print the output message. ''' print("SensuPlugin: {}".format(' '.join(str(a) for a in args)))
Print the output message.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/plugin.py#L51-L55
null
class SensuPlugin(object): ''' Base class used by both checks and metrics plugins. ''' def __init__(self, autorun=True): self.plugin_info = { 'check_name': None, 'message': None, 'status': None } # create a method for each of the exit codes ...
sensu-plugins/sensu-plugin-python
sensu_plugin/plugin.py
SensuPlugin.__make_dynamic
python
def __make_dynamic(self, method): ''' Create a method for each of the exit codes. ''' def dynamic(*args): self.plugin_info['status'] = method if not args: args = None self.output(args) sys.exit(getattr(self.exit_code, method...
Create a method for each of the exit codes.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/plugin.py#L57-L71
null
class SensuPlugin(object): ''' Base class used by both checks and metrics plugins. ''' def __init__(self, autorun=True): self.plugin_info = { 'check_name': None, 'message': None, 'status': None } # create a method for each of the exit codes ...
sensu-plugins/sensu-plugin-python
sensu_plugin/plugin.py
SensuPlugin.__exitfunction
python
def __exitfunction(self): ''' Method called by exit hook, ensures that both an exit code and output is supplied, also catches errors. ''' if self._hook.exit_code is None and self._hook.exception is None: print("Check did not exit! You should call an exit code method."...
Method called by exit hook, ensures that both an exit code and output is supplied, also catches errors.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/plugin.py#L79-L92
null
class SensuPlugin(object): ''' Base class used by both checks and metrics plugins. ''' def __init__(self, autorun=True): self.plugin_info = { 'check_name': None, 'message': None, 'status': None } # create a method for each of the exit codes ...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.run
python
def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin into a global event object stdin = self.read_stdin() self.event = self.read_event(stdin) # Prepare global settings self.settings = get_s...
Set up the event object, global settings and command line arguments.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L31-L65
[ "def get_settings():\n '''\n Get all currently loaded settings.\n '''\n settings = {}\n for config_file in config_files():\n config_contents = load_config(config_file)\n if config_contents is not None:\n settings = deep_merge(settings, config_contents)\n return settings\n"...
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def read_stdin(self): ''' Read data piped from stdin. ''' try: return sys.stdin.read() except Except...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.read_event
python
def read_event(self, check_result): ''' Convert the piped check result (json) into a global 'event' dict ''' try: event = json.loads(check_result) event['occurrences'] = event.get('occurrences', 1) event['check'] = event.get('check', {}) ev...
Convert the piped check result (json) into a global 'event' dict
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L76-L87
null
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.filter
python
def filter(self): ''' Filters exit the proccess if the event should not be handled. Filtering events is deprecated and will be removed in a future release. ''' if self.deprecated_filtering_enabled(): print('warning: event filtering in sensu-plugin is deprecated,' + ...
Filters exit the proccess if the event should not be handled. Filtering events is deprecated and will be removed in a future release.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L95-L111
[ "def deprecated_filtering_enabled(self):\n '''\n Evaluates whether the event should be processed by any of the\n filter methods in this library. Defaults to true,\n i.e. deprecated filters are run by default.\n\n returns bool\n '''\n return self.event['check'].get('enable_deprecated_filtering',...
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.bail
python
def bail(self, msg): ''' Gracefully terminate with message ''' client_name = self.event['client'].get('name', 'error:no-client-name') check_name = self.event['check'].get('name', 'error:no-check-name') print('{}: {}/{}'.format(msg, client_name, check_name)) sys.ex...
Gracefully terminate with message
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L135-L142
null
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.get_api_settings
python
def get_api_settings(self): ''' Return a dict of API settings derived first from ENV['SENSU_API_URL'] if set, then Sensu config `api` scope if configured, and finally falling back to to ipv4 localhost address on default API port. return dict ''' sensu_api_url = ...
Return a dict of API settings derived first from ENV['SENSU_API_URL'] if set, then Sensu config `api` scope if configured, and finally falling back to to ipv4 localhost address on default API port. return dict
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L144-L169
null
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.api_request
python
def api_request(self, method, path): ''' Query Sensu api for information. ''' if not hasattr(self, 'api_settings'): ValueError('api.json settings not found') if method.lower() == 'get': _request = requests.get elif method.lower() == 'post': ...
Query Sensu api for information.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L172-L191
null
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.event_exists
python
def event_exists(self, client, check): ''' Query Sensu API for event. ''' return self.api_request( 'get', 'events/{}/{}'.format(client, check) ).status_code == 200
Query Sensu API for event.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L199-L206
[ "def api_request(self, method, path):\n '''\n Query Sensu api for information.\n '''\n if not hasattr(self, 'api_settings'):\n ValueError('api.json settings not found')\n\n if method.lower() == 'get':\n _request = requests.get\n elif method.lower() == 'post':\n _request = requ...
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.filter_silenced
python
def filter_silenced(self): ''' Determine whether a check is silenced and shouldn't handle. ''' stashes = [ ('client', '/silence/{}'.format(self.event['client']['name'])), ('check', '/silence/{}/{}'.format( self.event['client']['name'], ...
Determine whether a check is silenced and shouldn't handle.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L216-L229
[ "def stash_exists(self, path):\n '''\n Query Sensu API for stash data.\n '''\n return self.api_request('get', '/stash' + path).status_code == 200\n" ]
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.filter_dependencies
python
def filter_dependencies(self): ''' Determine whether a check has dependencies. ''' dependencies = self.event['check'].get('dependencies', None) if dependencies is None or not isinstance(dependencies, list): return for dependency in self.event['check']['depende...
Determine whether a check has dependencies.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L231-L250
[ "def event_exists(self, client, check):\n '''\n Query Sensu API for event.\n '''\n return self.api_request(\n 'get',\n 'events/{}/{}'.format(client, check)\n ).status_code == 200\n" ]
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/handler.py
SensuHandler.filter_repeated
python
def filter_repeated(self): ''' Determine whether a check is repeating. ''' defaults = { 'occurrences': 1, 'interval': 30, 'refresh': 1800 } # Override defaults with anything defined in the settings if isinstance(self.settings['...
Determine whether a check is repeating.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L252-L285
[ "def bail(self, msg):\n '''\n Gracefully terminate with message\n '''\n client_name = self.event['client'].get('name', 'error:no-client-name')\n check_name = self.event['check'].get('name', 'error:no-check-name')\n print('{}: {}/{}'.format(msg, client_name, check_name))\n sys.exit(0)\n" ]
class SensuHandler(object): ''' Base class for Sensu Handlers. ''' def __init__(self, autorun=True): if autorun: self.run() def run(self): ''' Set up the event object, global settings and command line arguments. ''' # Parse the stdin in...
sensu-plugins/sensu-plugin-python
sensu_plugin/utils.py
config_files
python
def config_files(): ''' Get list of currently used config files. ''' sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE') sensu_config_files = os.environ.get('SENSU_CONFIG_FILES') sensu_v1_config = '/etc/sensu/config.json' sensu_v1_confd = '/etc/sensu/conf.d' if sensu_loaded_t...
Get list of currently used config files.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/utils.py#L10-L34
null
''' Utilities for loading config files, etc. ''' import os import json from copy import deepcopy def get_settings(): ''' Get all currently loaded settings. ''' settings = {} for config_file in config_files(): config_contents = load_config(config_file) if config_contents is not No...
sensu-plugins/sensu-plugin-python
sensu_plugin/utils.py
get_settings
python
def get_settings(): ''' Get all currently loaded settings. ''' settings = {} for config_file in config_files(): config_contents = load_config(config_file) if config_contents is not None: settings = deep_merge(settings, config_contents) return settings
Get all currently loaded settings.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/utils.py#L37-L46
[ "def config_files():\n '''\n Get list of currently used config files.\n '''\n sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE')\n sensu_config_files = os.environ.get('SENSU_CONFIG_FILES')\n sensu_v1_config = '/etc/sensu/config.json'\n sensu_v1_confd = '/etc/sensu/conf.d'\n if s...
''' Utilities for loading config files, etc. ''' import os import json from copy import deepcopy def config_files(): ''' Get list of currently used config files. ''' sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE') sensu_config_files = os.environ.get('SENSU_CONFIG_FILES') sensu...
sensu-plugins/sensu-plugin-python
sensu_plugin/utils.py
load_config
python
def load_config(filename): ''' Read contents of config file. ''' try: with open(filename, 'r') as config_file: return json.loads(config_file.read()) except IOError: pass
Read contents of config file.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/utils.py#L49-L57
null
''' Utilities for loading config files, etc. ''' import os import json from copy import deepcopy def config_files(): ''' Get list of currently used config files. ''' sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE') sensu_config_files = os.environ.get('SENSU_CONFIG_FILES') sensu...
sensu-plugins/sensu-plugin-python
sensu_plugin/utils.py
deep_merge
python
def deep_merge(dict_one, dict_two): ''' Deep merge two dicts. ''' merged = dict_one.copy() for key, value in dict_two.items(): # value is equivalent to dict_two[key] if (key in dict_one and isinstance(dict_one[key], dict) and isinstance(value, dict)): ...
Deep merge two dicts.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/utils.py#L60-L77
[ "def deep_merge(dict_one, dict_two):\n '''\n Deep merge two dicts.\n '''\n merged = dict_one.copy()\n for key, value in dict_two.items():\n # value is equivalent to dict_two[key]\n if (key in dict_one and\n isinstance(dict_one[key], dict) and\n isinstance(v...
''' Utilities for loading config files, etc. ''' import os import json from copy import deepcopy def config_files(): ''' Get list of currently used config files. ''' sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE') sensu_config_files = os.environ.get('SENSU_CONFIG_FILES') sensu...
sensu-plugins/sensu-plugin-python
sensu_plugin/utils.py
map_v2_event_into_v1
python
def map_v2_event_into_v1(event): ''' Helper method to convert Sensu 2.x event into Sensu 1.x event. ''' # return the event if it has already been mapped if "v2_event_mapped_into_v1" in event: return event # Trigger mapping code if enity exists and client does not if not bool(event....
Helper method to convert Sensu 2.x event into Sensu 1.x event.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/utils.py#L80-L139
null
''' Utilities for loading config files, etc. ''' import os import json from copy import deepcopy def config_files(): ''' Get list of currently used config files. ''' sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE') sensu_config_files = os.environ.get('SENSU_CONFIG_FILES') sensu...
sensu-plugins/sensu-plugin-python
sensu_plugin/check.py
SensuPluginCheck.check_name
python
def check_name(self, name=None): ''' Checks the plugin name and sets it accordingly. Uses name if specified, class name if not set. ''' if name: self.plugin_info['check_name'] = name if self.plugin_info['check_name'] is not None: return self.plugi...
Checks the plugin name and sets it accordingly. Uses name if specified, class name if not set.
train
https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/check.py#L11-L22
null
class SensuPluginCheck(SensuPlugin): ''' Class that inherits from SensuPlugin. ''' def message(self, *m): self.plugin_info['message'] = m def output(self, args): msg = '' if args is None or (args[0] is None and len(args) == 1): args = self.plugin_info['message'...
aio-libs/aiomcache
aiomcache/pool.py
MemcachePool.clear
python
def clear(self): while not self._pool.empty(): conn = yield from self._pool.get() self._do_close(conn)
Clear pool connections.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L23-L27
null
class MemcachePool: def __init__(self, host, port, *, minsize, maxsize, loop=None): loop = loop if loop is not None else asyncio.get_event_loop() self._host = host self._port = port self._minsize = minsize self._maxsize = maxsize self._loop = loop self._pool ...
aio-libs/aiomcache
aiomcache/pool.py
MemcachePool.acquire
python
def acquire(self): while self.size() == 0 or self.size() < self._minsize: _conn = yield from self._create_new_conn() if _conn is None: break self._pool.put_nowait(_conn) conn = None while not conn: _conn = yield from self._pool.get...
Acquire connection from the pool, or spawn new one if pool maxsize permits. :return: ``tuple`` (reader, writer)
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L34-L56
[ "def size(self):\n return self._pool.qsize() + len(self._in_use)\n" ]
class MemcachePool: def __init__(self, host, port, *, minsize, maxsize, loop=None): loop = loop if loop is not None else asyncio.get_event_loop() self._host = host self._port = port self._minsize = minsize self._maxsize = maxsize self._loop = loop self._pool ...
aio-libs/aiomcache
aiomcache/pool.py
MemcachePool.release
python
def release(self, conn): self._in_use.remove(conn) if conn.reader.at_eof() or conn.reader.exception(): self._do_close(conn) else: self._pool.put_nowait(conn)
Releases connection back to the pool. :param conn: ``namedtuple`` (reader, writer)
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L58-L67
[ "def _do_close(self, conn):\n conn.reader.feed_eof()\n conn.writer.close()\n" ]
class MemcachePool: def __init__(self, host, port, *, minsize, maxsize, loop=None): loop = loop if loop is not None else asyncio.get_event_loop() self._host = host self._port = port self._minsize = minsize self._maxsize = maxsize self._loop = loop self._pool ...
aio-libs/aiomcache
aiomcache/client.py
Client.delete
python
def delete(self, conn, key): assert self._validate_key(key) command = b'delete ' + key + b'\r\n' response = yield from self._execute_simple_command(conn, command) if response not in (const.DELETED, const.NOT_FOUND): raise ClientException('Memcached delete failed', response)...
Deletes a key/value pair from the server. :param key: is the key to delete. :return: True if case values was deleted or False to indicate that the item with this key was not found.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L125-L139
[ "def _validate_key(self, key):\n if not isinstance(key, bytes): # avoid bugs subtle and otherwise\n raise ValidationException('key must be bytes', key)\n\n m = self._valid_key_re.match(key)\n if m:\n # in python re, $ matches either end of line or right before\n # \\n at end of line. ...
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.get
python
def get(self, conn, key, default=None): values, _ = yield from self._multi_get(conn, key) return values.get(key, default)
Gets a single value from the server. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, is the data for this specified key.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L142-L150
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.gets
python
def gets(self, conn, key, default=None): values, cas_tokens = yield from self._multi_get( conn, key, with_cas=True) return values.get(key, default), cas_tokens.get(key)
Gets a single value from the server together with the cas token. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, ``bytes tuple with the value and the cas
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L153-L162
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.multi_get
python
def multi_get(self, conn, *keys): values, _ = yield from self._multi_get(conn, *keys) return tuple(values.get(key) for key in keys)
Takes a list of keys and returns a list of values. :param keys: ``list`` keys for the item being fetched. :return: ``list`` of values for the specified keys. :raises:``ValidationException``, ``ClientException``, and socket errors
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L165-L174
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.stats
python
def stats(self, conn, args=None): # req - stats [additional args]\r\n # resp - STAT <name> <value>\r\n (one per result) # END\r\n if args is None: args = b'' conn.writer.write(b''.join((b'stats ', args, b'\r\n'))) result = {} resp = yield fr...
Runs a stats command on the server.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L177-L204
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.set
python
def set(self, conn, key, value, exptime=0): flags = 0 # TODO: fix when exception removed resp = yield from self._storage_command( conn, b'set', key, value, flags, exptime) return resp
Sets a key to a value on the server with an optional exptime (0 means don't auto-expire) :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int``, is expiration time. If it's 0, the item never expires. :return: ``bool...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L240-L253
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.cas
python
def cas(self, conn, key, value, cas_token, exptime=0): flags = 0 # TODO: fix when exception removed resp = yield from self._storage_command( conn, b'cas', key, value, flags, exptime, cas=cas_token) return resp
Sets a key to a value on the server with an optional exptime (0 means don't auto-expire) only if value hasn't change from first retrieval :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int``, is expiration time. If it's 0...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L256-L272
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.add
python
def add(self, conn, key, value, exptime=0): flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'add', key, value, flags, exptime))
Store this data, but only if the server *doesn't* already hold data for this key. :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, Tru...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L275-L287
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.replace
python
def replace(self, conn, key, value, exptime=0): flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'replace', key, value, flags, exptime))
Store this data, but only if the server *does* already hold data for this key. :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True i...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L290-L302
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.append
python
def append(self, conn, key, value, exptime=0): flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'append', key, value, flags, exptime))
Add data to an existing key after existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L305-L316
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.prepend
python
def prepend(self, conn, key, value, exptime=0): flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'prepend', key, value, flags, exptime))
Add data to an existing key before existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L319-L330
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.incr
python
def incr(self, conn, key, increment=1): assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'incr', key, increment) return resp
Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param increment: ``int``, is the amount by ...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L343-L359
[ "def _validate_key(self, key):\n if not isinstance(key, bytes): # avoid bugs subtle and otherwise\n raise ValidationException('key must be bytes', key)\n\n m = self._valid_key_re.match(key)\n if m:\n # in python re, $ matches either end of line or right before\n # \\n at end of line. ...
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.decr
python
def decr(self, conn, key, decrement=1): assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'decr', key, decrement) return resp
Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by ...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L362-L378
[ "def _validate_key(self, key):\n if not isinstance(key, bytes): # avoid bugs subtle and otherwise\n raise ValidationException('key must be bytes', key)\n\n m = self._valid_key_re.match(key)\n if m:\n # in python re, $ matches either end of line or right before\n # \\n at end of line. ...
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.touch
python
def touch(self, conn, key, exptime): assert self._validate_key(key) _cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')]) cmd = _cmd + b'\r\n' resp = yield from self._execute_simple_command(conn, cmd) if resp not in (const.TOUCHED, const.NOT_FOUND): raise C...
The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time. :return: ``bool``, True in case of succ...
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L381-L397
[ "def _validate_key(self, key):\n if not isinstance(key, bytes): # avoid bugs subtle and otherwise\n raise ValidationException('key must be bytes', key)\n\n m = self._valid_key_re.match(key)\n if m:\n # in python re, $ matches either end of line or right before\n # \\n at end of line. ...
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.version
python
def version(self, conn): command = b'version\r\n' response = yield from self._execute_simple_command( conn, command) if not response.startswith(const.VERSION): raise ClientException('Memcached version failed', response) version, number = response.split() ...
Current version of the server. :return: ``bytes``, memcached version for current the server.
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L400-L412
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
aio-libs/aiomcache
aiomcache/client.py
Client.flush_all
python
def flush_all(self, conn): command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', response)
Its effect is to invalidate all existing items immediately
train
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L415-L422
null
class Client(object): def __init__(self, host, port=11211, *, pool_size=2, pool_minsize=None, loop=None): if not pool_minsize: pool_minsize = pool_size self._pool = MemcachePool( host, port, minsize=pool_minsize, maxsize=pool_size, loop=loop) # key supp...
jacobtomlinson/datapoint-python
datapoint/__init__.py
connection
python
def connection(profile_name='default', api_key=None): if api_key is None: profile_fname = datapoint.profile.API_profile_fname(profile_name) if not os.path.exists(profile_fname): raise ValueError('Profile not found in {}. Please install your API \n' 'key with ...
Connect to DataPoint with the given API key profile name.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/__init__.py#L12-L22
[ "def API_profile_fname(profile_name='default'):\n \"\"\"Get the API key profile filename.\"\"\"\n return os.path.join(appdirs.user_data_dir('DataPoint'),\n profile_name + '.key')\n" ]
"""Datapoint API to retrieve Met Office data""" __author__ = "Jacob Tomlinson" __author_email__ = "jacob.tomlinson@metoffice.gov.uk" import os.path from datapoint.Manager import Manager import datapoint.profile from ._version import get_versions __version__ = get_versions()['version'] del get_versions
jacobtomlinson/datapoint-python
datapoint/Timestep.py
Timestep.elements
python
def elements(self): elements = [] for el in ct: if isinstance(el[1], datapoint.Element.Element): elements.append(el[1]) return elements
Return a list of the elements which are not None
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Timestep.py#L25-L34
null
class Timestep(object): def __init__(self, api_key=""): self.api_key = api_key self.name = None self.date = None self.weather = None self.temperature = None self.feels_like_temperature = None self.wind_speed = None self.wind_direction = None s...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.__retry_session
python
def __retry_session(self, retries=10, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): # requests.Session allows finer control, which is needed to use the # retrying code the_session = session or requests.Session() # T...
Retry the connection using requests if it fails. Use this as a wrapper to request from datapoint
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L109-L131
null
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.__call_api
python
def __call_api(self, path, params=None, api_url=FORECAST_URL): if not params: params = dict() payload = {'key': self.api_key} payload.update(params) url = "%s/%s" % (api_url, path) # Add a timeout to the request. # The value of 1 second is based on attempting...
Call the datapoint api using the requests module
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L133-L165
[ "def __retry_session(self, retries=10, backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n session=None):\n \"\"\"\n Retry the connection using requests if it fails. Use this as a wrapper\n to request from datapoint\n \"\"\"\n\n # requests.Session allows fi...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager._distance_between_coords
python
def _distance_between_coords(self, lon1, lat1, lon2, lat2): # Convert the coordinates of the points to radians. lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) r = 6371 d_hav = 2 * r * asin(sqrt((sin((lat1 - lat2) / 2))**2 + \ cos(lat1)...
Calculate the great circle distance between two points on the earth (specified in decimal degrees). Haversine formula states that: d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 + cos(lat1)cos(lat2)sin^2((lon1 - lon2) / 2)))) where r is the radius of the sphere. This assumes t...
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L167-L186
null
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager._get_wx_units
python
def _get_wx_units(self, params, name): units = "" for param in params: if str(name) == str(param['name']): units = param['units'] return units
Give the Wx array returned from datapoint and an element name and return the units for that element.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L188-L197
null
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager._visibility_to_text
python
def _visibility_to_text(self, distance): if not isinstance(distance, (int, long)): raise ValueError("Distance must be an integer not", type(distance)) if distance < 0: raise ValueError("Distance out of bounds, should be 0 or greater") if 0 <= distance < 1000: ...
Convert observed visibility in metres to text used in forecast
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L207-L228
null
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_forecast_sites
python
def get_forecast_sites(self): time_now = time() if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None: data = self.__call_api("sitelist/") sites = list() for jsoned in data['Locations']['Locatio...
This function returns a list of Site object.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L239-L278
[ "def __call_api(self, path, params=None, api_url=FORECAST_URL):\n \"\"\"\n Call the datapoint api using the requests module\n\n \"\"\"\n if not params:\n params = dict()\n payload = {'key': self.api_key}\n payload.update(params)\n url = \"%s/%s\" % (api_url, path)\n\n # Add a timeout ...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_site
python
def get_nearest_site(self, latitude=None, longitude=None): warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead' warn(warning_message, DeprecationWarning, stacklevel=2) return self.get_nearest_forecast_site(latitude, longitude)
Deprecated. This function returns nearest Site object to the specified coordinates.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L280-L288
[ "def get_nearest_forecast_site(self, latitude=None, longitude=None):\n \"\"\"\n This function returns the nearest Site object to the specified\n coordinates.\n \"\"\"\n if longitude is None:\n print('ERROR: No latitude given.')\n return False\n\n if latitude is None:\n print(...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_forecast_site
python
def get_nearest_forecast_site(self, latitude=None, longitude=None): if longitude is None: print('ERROR: No latitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = Non...
This function returns the nearest Site object to the specified coordinates.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L290-L325
[ "def _distance_between_coords(self, lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees).\n Haversine formula states that:\n\n d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 +\n cos(lat1)cos(lat2)sin^2((lon1 - lon...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_forecast_for_site
python
def get_forecast_for_site(self, site_id, frequency="daily"): data = self.__call_api(site_id, {"res":frequency}) params = data['SiteRep']['Wx']['Param'] forecast = Forecast() forecast.data_date = data['SiteRep']['DV']['dataDate'] forecast.data_date = datetime.strptime(data['SiteRe...
Get a forecast for the provided site A frequency of "daily" will return two timesteps: "Day" and "Night". A frequency of "3hourly" will return 8 timesteps: 0, 180, 360 ... 1260 (minutes since midnight UTC)
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L327-L430
[ "def __call_api(self, path, params=None, api_url=FORECAST_URL):\n \"\"\"\n Call the datapoint api using the requests module\n\n \"\"\"\n if not params:\n params = dict()\n payload = {'key': self.api_key}\n payload.update(params)\n url = \"%s/%s\" % (api_url, path)\n\n # Add a timeout ...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_observation_sites
python
def get_observation_sites(self): if (time() - self.observation_sites_last_update) > self.observation_sites_update_time: self.observation_sites_last_update = time() data = self.__call_api("sitelist/", None, OBSERVATION_URL) sites = list() for jsoned in data['Locati...
This function returns a list of Site objects for which observations are available.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L433-L467
[ "def __call_api(self, path, params=None, api_url=FORECAST_URL):\n \"\"\"\n Call the datapoint api using the requests module\n\n \"\"\"\n if not params:\n params = dict()\n payload = {'key': self.api_key}\n payload.update(params)\n url = \"%s/%s\" % (api_url, path)\n\n # Add a timeout ...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_observation_site
python
def get_nearest_observation_site(self, latitude=None, longitude=None): if longitude is None: print('ERROR: No longitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = ...
This function returns the nearest Site to the specified coordinates that supports observations
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L469-L501
[ "def _distance_between_coords(self, lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees).\n Haversine formula states that:\n\n d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 +\n cos(lat1)cos(lat2)sin^2((lon1 - lon...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_observations_for_site
python
def get_observations_for_site(self, site_id, frequency='hourly'): data = self.__call_api(site_id,{"res":frequency}, OBSERVATION_URL) params = data['SiteRep']['Wx']['Param'] observation = Observation() observation.data_date = data['SiteRep']['DV']['dataDate'] ...
Get observations for the provided site Returns hourly observations for the previous 24 hours
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L504-L649
[ "def __call_api(self, path, params=None, api_url=FORECAST_URL):\n \"\"\"\n Call the datapoint api using the requests module\n\n \"\"\"\n if not params:\n params = dict()\n payload = {'key': self.api_key}\n payload.update(params)\n url = \"%s/%s\" % (api_url, path)\n\n # Add a timeout ...
class Manager(object): """ Datapoint Manager object """ def __init__(self, api_key=""): self.api_key = api_key self.call_response = None # The list of sites changes infrequently so limit to requesting it # every hour. self.forecast_sites_last_update = 0 ...
jacobtomlinson/datapoint-python
datapoint/regions/RegionManager.py
RegionManager.call_api
python
def call_api(self, path, **kwargs): ''' Call datapoint api ''' if 'key' not in kwargs: kwargs['key'] = self.api_key req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs) if req.status_code != requests.codes.ok: req.raise_for_stat...
Call datapoint api
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L27-L38
null
class RegionManager(object): ''' Datapoint Manager for national and regional text forecasts ''' def __init__(self, api_key, base_url=None): self.api_key = api_key self.all_regions_path = '/sitelist' if not base_url: self.base_url = REGIONS_BASE_URL # The list...
jacobtomlinson/datapoint-python
datapoint/regions/RegionManager.py
RegionManager.get_all_regions
python
def get_all_regions(self): ''' Request a list of regions from Datapoint. Returns each Region as a Site object. Regions rarely change, so we cache the response for one hour to minimise requests to API. ''' if (time() - self.regions_last_update) < self.regions_update_time: ...
Request a list of regions from Datapoint. Returns each Region as a Site object. Regions rarely change, so we cache the response for one hour to minimise requests to API.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L40-L60
[ "def call_api(self, path, **kwargs):\n '''\n Call datapoint api\n '''\n if 'key' not in kwargs:\n kwargs['key'] = self.api_key\n req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)\n\n if req.status_code != requests.codes.ok:\n req.raise_for_status()\n\n return...
class RegionManager(object): ''' Datapoint Manager for national and regional text forecasts ''' def __init__(self, api_key, base_url=None): self.api_key = api_key self.all_regions_path = '/sitelist' if not base_url: self.base_url = REGIONS_BASE_URL # The list...
jacobtomlinson/datapoint-python
datapoint/Forecast.py
Forecast.now
python
def now(self): # From the comments in issue 19: forecast.days[0] is dated for the # previous day shortly after midnight now = None # Set the time now to be in the same time zone as the first timestep in # the forecast. This shouldn't cause problems with daylight savings as ...
Function to return just the current timestep from this forecast
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L22-L80
null
class Forecast(object): def __init__(self, api_key=""): self.api_key = api_key self.data_date = None self.continent = None self.country = None self.name = None self.longitude = None self.latitude = None self.id = None self.elevation = None ...
jacobtomlinson/datapoint-python
datapoint/Forecast.py
Forecast.future
python
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None): future = None # Initialize variables to 0 dd, hh, mm, ss = [0 for i in range(4)] if (in_days != None): dd = dd + in_days if (in_hours != None): hh = hh + in_hours if (in_...
Function to return a future timestep
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L82-L121
[ "def timedelta_total_seconds(self, timedelta):\n return (\n timedelta.microseconds + 0.0 +\n (timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6\n" ]
class Forecast(object): def __init__(self, api_key=""): self.api_key = api_key self.data_date = None self.continent = None self.country = None self.name = None self.longitude = None self.latitude = None self.id = None self.elevation = None ...
jacobtomlinson/datapoint-python
datapoint/profile.py
install_API_key
python
def install_API_key(api_key, profile_name='default'): fname = API_profile_fname(profile_name) if not os.path.isdir(os.path.dirname(fname)): os.makedirs(os.path.dirname(fname)) with open(fname, 'w') as fh: fh.write(api_key)
Put the given API key into the given profile name.
train
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/profile.py#L12-L18
[ "def API_profile_fname(profile_name='default'):\n \"\"\"Get the API key profile filename.\"\"\"\n return os.path.join(appdirs.user_data_dir('DataPoint'),\n profile_name + '.key')\n" ]
import os import appdirs def API_profile_fname(profile_name='default'): """Get the API key profile filename.""" return os.path.join(appdirs.user_data_dir('DataPoint'), profile_name + '.key')
openai/pachi-py
pachi_py/pachi/tools/twogtp.py
GTP_game.writesgf
python
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_na...
Write the game to an SGF file after a game
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/twogtp.py#L272-L310
[ "def coords_to_sgf(size, board_coords):\n global debug\n\n board_coords = string.lower(board_coords)\n if board_coords == \"pass\":\n return \"\"\n if debug:\n print \"Coords: <\" + board_coords + \">\"\n letter = board_coords[0]\n digits = board_coords[1:]\n if letter > \"i\":\n ...
class GTP_game: # Class members: # whiteplayer GTP_player # blackplayer GTP_player # size int # komi float # handicap int # handicap_type string # handicap_stones int # moves list of string # resultw ...
openai/pachi-py
pachi_py/pachi/tools/twogtp.py
GTP_game.play
python
def play(self, sgffile): "Play a game" global verbose if verbose >= 1: print "Setting boardsize and komi for black\n" self.blackplayer.boardsize(self.size) self.blackplayer.komi(self.komi) if verbose >= 1: print "Setting boardsize and komi for wh...
Play a game
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/twogtp.py#L320-L424
[ "def is_known_command(self, command):\n return self.connection.exec_cmd(\"known_command \" + command) == \"true\"\n", "def genmove(self, color):\n if color[0] in [\"b\", \"B\"]:\n command = \"black\"\n elif color[0] in [\"w\", \"W\"]:\n command = \"white\"\n if self.protocol_version == \...
class GTP_game: # Class members: # whiteplayer GTP_player # blackplayer GTP_player # size int # komi float # handicap int # handicap_type string # handicap_stones int # moves list of string # resultw ...
openai/pachi-py
pachi_py/pachi/tools/sgflib/typelib.py
MutableSequence.sort
python
def sort(self, func=None): if func: self.data.sort(func) else: self.data.sort()
Sorts 'self.data' in-place. Argument: - func : optional, default 'None' -- - If 'func' not given, sorting will be in ascending order. - If 'func' given, it will determine the sort order. 'func' must be a two-argument comparison function which returns -1, 0, or 1, to mean before, same, or aft...
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/typelib.py#L459-L472
null
class MutableSequence(Sequence, MutableMixin): """ Superclass for classes which emulate mutable (modifyable in-place) sequences ('List').""" def __setslice__(self, low, high, seq): """ On 'self[low:high]=seq'.""" self.data[low:high] = seq def __delslice__(self, low, high): """ On 'del self[low:high]'.""" ...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
_escapeText
python
def _escapeText(text): output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, index) output = output + text[index:] return output
Adds backslash-escapes to property value characters that need them.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L579-L589
null
#!/usr/local/bin/python # sgflib.py (Smart Game Format Parser Library) # Copyright (C) 2000 David John Goodger (dgoodger@bigfoot.com) # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; ...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parse
python
def parse(self): c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
Parses the SGF data stored in 'self.data', and returns a 'Collection'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L153-L162
[ "def append(self, x):\n\t\"\"\" Inserts object 'x' at the end of 'self.data' in-place.\"\"\"\n\tself.data.append(x)\n", "def parseOneGame(self):\n\t\"\"\" Parses one game from 'self.data'. Returns a 'GameTree' containing\n\t\tone game, or 'None' if the end of 'self.data' has been reached.\"\"\"\n\tif self.index <...
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseOneGame
python
def parseOneGame(self): if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.parseGameTree() return None
Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L164-L172
[ "def parseGameTree(self):\n\t\"\"\" Called when \"(\" encountered, ends when a matching \")\" encountered.\n\t\tParses and returns one 'GameTree' from 'self.data'. Raises\n\t\t'GameTreeParseError' if a problem is encountered.\"\"\"\n\tg = GameTree()\n\twhile self.index < self.datalen:\n\t\tmatch = self.reGameTreeNe...
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseGameTree
python
def parseGameTree(self): g = GameTree() while self.index < self.datalen: match = self.reGameTreeNext.match(self.data, self.index) if match: self.index = match.end() if match.group(1) == ";": # found start of node if g.variations: raise GameTreeParseError( "A node was encountered...
Called when "(" encountered, ends when a matching ")" encountered. Parses and returns one 'GameTree' from 'self.data'. Raises 'GameTreeParseError' if a problem is encountered.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L174-L194
[ "def append(self, x):\n\t\"\"\" Inserts object 'x' at the end of 'self.data' in-place.\"\"\"\n\tself.data.append(x)\n", "def parseNode(self):\n\t\"\"\" Called when \";\" encountered (& is consumed). Parses and returns one\n\t\t'Node', which can be empty. Raises 'NodePropertyParseError' if no\n\t\tproperty values ...
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseVariations
python
def parseVariations(self): v = [] while self.index < self.datalen: # check for ")" at end of GameTree, but don't consume it match = self.reGameTreeEnd.match(self.data, self.index) if match: return v g = self.parseGameTree() if g: v.append(g) # check for next variation, and consume "(" m...
Called when "(" encountered inside a 'GameTree', ends when a non-matching ")" encountered. Returns a list of variation 'GameTree''s. Raises 'EndOfDataParseError' if the end of 'self.data' is reached before the end of the enclosing 'GameTree'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L196-L214
[ "def parseGameTree(self):\n\t\"\"\" Called when \"(\" encountered, ends when a matching \")\" encountered.\n\t\tParses and returns one 'GameTree' from 'self.data'. Raises\n\t\t'GameTreeParseError' if a problem is encountered.\"\"\"\n\tg = GameTree()\n\twhile self.index < self.datalen:\n\t\tmatch = self.reGameTreeNe...
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseNode
python
def parseNode(self): n = Node() while self.index < self.datalen: match = self.reNodeContents.match(self.data, self.index) if match: self.index = match.end() pvlist = self.parsePropertyValue() if pvlist: n.addProperty(n.makeProperty(match.group(1), pvlist)) else: raise NodePropertyPar...
Called when ";" encountered (& is consumed). Parses and returns one 'Node', which can be empty. Raises 'NodePropertyParseError' if no property values are extracted. Raises 'EndOfDataParseError' if the end of 'self.data' is reached before the end of the node (i.e., the start of the next node, the start of a ...
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L216-L235
[ "def parsePropertyValue(self):\n\t\"\"\" Called when \"[\" encountered (but not consumed), ends when the next\n\t\tproperty, node, or variation encountered. Parses and returns a list\n\t\tof property values. Raises 'PropertyValueParseError' if there is a\n\t\tproblem.\"\"\"\n\tpvlist = []\n\twhile self.index < self...
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parsePropertyValue
python
def parsePropertyValue(self): pvlist = [] while self.index < self.datalen: match = self.rePropertyStart.match(self.data, self.index) if match: self.index = match.end() v = "" # value # scan for escaped characters (using '\'), unescape them (remove linebreaks) mend = self.rePropertyEnd....
Called when "[" encountered (but not consumed), ends when the next property, node, or variation encountered. Parses and returns a list of property values. Raises 'PropertyValueParseError' if there is a problem.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L237-L273
[ "def _convertControlChars(self, text):\n\t\"\"\" Converts control characters in 'text' to spaces, using the\n\t\t'self.ctrltrans' translation table. Override for variant\n\t\tbehaviour.\"\"\"\n\treturn string.translate(text, self.ctrltrans)\n" ]
class SGFParser: """ Parser for SGF data. Creates a tree structure based on the SGF standard itself. 'SGFParser.parse()' will return a 'Collection' object for the entire data. Instance Attributes: - self.data : string -- The complete SGF data instance. - self.datalen : integer -- Length of 'self.data'. - self....
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
RootNodeSGFParser.parseNode
python
def parseNode(self): n = SGFParser.parseNode(self) # process one Node as usual self.index = self.datalen # set end of data return n
Calls 'SGFParser.parseNode()', sets 'self.index' to point to the end of the data (effectively ending the 'GameTree' and 'Collection'), and returns the single (root) 'Node' parsed.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L285-L291
[ "def parseNode(self):\n\t\"\"\" Called when \";\" encountered (& is consumed). Parses and returns one\n\t\t'Node', which can be empty. Raises 'NodePropertyParseError' if no\n\t\tproperty values are extracted. Raises 'EndOfDataParseError' if the\n\t\tend of 'self.data' is reached before the end of the node (i.e., th...
class RootNodeSGFParser(SGFParser): """ For parsing only the first 'GameTree''s root Node of an SGF file.""" # we're only interested in the root node
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
GameTree.mainline
python
def mainline(self): if self.variations: return GameTree(self.data + self.variations[0].mainline()) else: return self
Returns the main line of the game (variation A) as a 'GameTree'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L338-L343
null
class GameTree(List): """ An SGF game tree: a game or variation. Instance attributes: - self[.data] : list of 'Node' -- game tree 'trunk'. - self.variations : list of 'GameTree' -- 0 or 2+ variations. 'self.variations[0]' contains the main branch (sequence actually played).""" def __init__(self, nodelist=None,...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
GameTree.propertySearch
python
def propertySearch(self, pid, getall=0): matches = [] for n in self: if n.has_key(pid): matches.append(n) if not getall: break else: # getall or not matches: for v in self.variations: matches = matches + v.propertySearch(pid, getall) if not getall and matches: break return GameTr...
Searches this 'GameTree' for nodes containing matching properties. Returns a 'GameTree' containing the matched node(s). Arguments: - pid : string -- ID of properties to search for. - getall : boolean -- Set to true (1) to return all 'Node''s that match, or to false (0) to return only the first match.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L357-L375
null
class GameTree(List): """ An SGF game tree: a game or variation. Instance attributes: - self[.data] : list of 'Node' -- game tree 'trunk'. - self.variations : list of 'GameTree' -- 0 or 2+ variations. 'self.variations[0]' contains the main branch (sequence actually played).""" def __init__(self, nodelist=None,...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Node.addProperty
python
def addProperty(self, property): """ Adds a 'Property' to this 'Node'. Checks for duplicate properties (illegal), and maintains the property order. Argument: - property : 'Property'""" if self.has_key(property.id): raise DuplicatePropertyError else: self.data[property.id] = property self.order.a...
Adds a 'Property' to this 'Node'. Checks for duplicate properties (illegal), and maintains the property order. Argument: - property : 'Property
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L449-L458
[ "def has_key(self, key):\n\t\"\"\" Returns 1 (true) if 'self.data' has a key 'key', or 0 otherwise.\"\"\"\n\treturn self.data.has_key(key)\n" ]
class Node(Dictionary): """ An SGF node. Instance Attributes: - self[.data] : ordered dictionary -- '{Property.id:Property}' mapping. (Ordered dictionary: allows offset-indexed retrieval). Properties *must* be added using 'self.addProperty()'. Example: Let 'n' be a 'Node' parsed from ';B[aa]BL[250]C[comment]...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.reset
python
def reset(self): self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L511-L519
[ "def _setChildren(self):\n\t\"\"\" Sets up 'self.children'.\"\"\"\n\tif self.index + 1 < len(self.gametree):\n\t\tself.children = [self.gametree[self.index+1]]\n\telse:\n\t\tself.children = map(lambda list: list[0], self.gametree.variations)\n", "def _setFlags(self):\n\t\"\"\" Sets up the flags 'self.atEnd' and '...
class Cursor: """ 'GameTree' navigation tool. Instance attributes: - self.game : 'GameTree' -- The root 'GameTree'. - self.gametree : 'GameTree' -- The current 'GameTree'. - self.node : 'Node' -- The current Node. - self.nodenum : integer -- The offset of 'self.node' from the root of 'self.game'. The nodenum o...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.next
python
def next(self, varnum=0): if self.index + 1 < len(self.gametree): # more main line? if varnum != 0: raise GameTreeNavigationError("Nonexistent variation.") self.index = self.index + 1 elif self.gametree.variations: # variations exist? if varnum < len(self.gametree.variations): self.stack.append(s...
Moves the 'Cursor' to & returns the next 'Node'. Raises 'GameTreeEndError' if the end of a branch is exceeded. Raises 'GameTreeNavigationError' if a non-existent variation is accessed. Argument: - varnum : integer, default 0 -- Variation number. Non-zero only valid at a branching, where variations exis...
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L521-L546
[ "def _setChildren(self):\n\t\"\"\" Sets up 'self.children'.\"\"\"\n\tif self.index + 1 < len(self.gametree):\n\t\tself.children = [self.gametree[self.index+1]]\n\telse:\n\t\tself.children = map(lambda list: list[0], self.gametree.variations)\n", "def _setFlags(self):\n\t\"\"\" Sets up the flags 'self.atEnd' and '...
class Cursor: """ 'GameTree' navigation tool. Instance attributes: - self.game : 'GameTree' -- The root 'GameTree'. - self.gametree : 'GameTree' -- The current 'GameTree'. - self.node : 'Node' -- The current Node. - self.nodenum : integer -- The offset of 'self.node' from the root of 'self.game'. The nodenum o...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.previous
python
def previous(self): if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() self.index = len(self.gametree) - 1 else: raise GameTreeEndError self.node = self.gametree[self.index] self.nodenum = self....
Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L548-L562
[ "def _setChildren(self):\n\t\"\"\" Sets up 'self.children'.\"\"\"\n\tif self.index + 1 < len(self.gametree):\n\t\tself.children = [self.gametree[self.index+1]]\n\telse:\n\t\tself.children = map(lambda list: list[0], self.gametree.variations)\n", "def _setFlags(self):\n\t\"\"\" Sets up the flags 'self.atEnd' and '...
class Cursor: """ 'GameTree' navigation tool. Instance attributes: - self.game : 'GameTree' -- The root 'GameTree'. - self.gametree : 'GameTree' -- The current 'GameTree'. - self.node : 'Node' -- The current Node. - self.nodenum : integer -- The offset of 'self.node' from the root of 'self.game'. The nodenum o...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setChildren
python
def _setChildren(self): if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
Sets up 'self.children'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L564-L569
null
class Cursor: """ 'GameTree' navigation tool. Instance attributes: - self.game : 'GameTree' -- The root 'GameTree'. - self.gametree : 'GameTree' -- The current 'GameTree'. - self.node : 'Node' -- The current Node. - self.nodenum : integer -- The offset of 'self.node' from the root of 'self.game'. The nodenum o...
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setFlags
python
def _setFlags(self): self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
Sets up the flags 'self.atEnd' and 'self.atStart'.
train
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L571-L574
null
class Cursor: """ 'GameTree' navigation tool. Instance attributes: - self.game : 'GameTree' -- The root 'GameTree'. - self.gametree : 'GameTree' -- The current 'GameTree'. - self.node : 'Node' -- The current Node. - self.nodenum : integer -- The offset of 'self.node' from the root of 'self.game'. The nodenum o...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF.fit
python
def fit(self, X, y): self._X = X # matrix of predictive variables ('independent variables') self._y = y # vector of values for outcome variable ('dependent variable') # Set up the properties for ReliefF ------------------------------------------------------------------------------------- ...
Scikit-learn required: Computes the feature importance scores from the training data. Parameters ---------- X: array-like {n_samples, n_features} Training instances to compute the feature importance scores from y: array-like {n_samples} Training labels R...
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L87-L214
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF.transform
python
def transform(self, X): if self._num_attributes < self.n_features_to_select: raise ValueError('Number of features to select is larger than the number of features in the dataset.') return X[:, self.top_features_[:self.n_features_to_select]]
Scikit-learn required: Reduces the feature set down to the top `n_features_to_select` features. Parameters ---------- X: array-like {n_samples, n_features} Feature matrix to perform feature selection on Returns ------- X_reduced: array-like {n_samples, n_fea...
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L217-L234
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._getMultiClassMap
python
def _getMultiClassMap(self): mcmap = dict() for i in range(self._datalen): if(self._y[i] not in mcmap): mcmap[self._y[i]] = 0 else: mcmap[self._y[i]] += 1 for each in self._label_list: mcmap[each] = mcmap[each]/float(self._dat...
Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes. In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF-F variant which was suggested to outperform the RELIEF-E multiclass variant. This strategy weight...
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L258-L275
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._get_attribute_info
python
def _get_attribute_info(self): attr = dict() d = 0 limit = self.discrete_threshold w = self._X.transpose() for idx in range(len(w)): h = self._headers[idx] z = w[idx] if self._missing_data_count > 0: z = z[np.logical_not(np.isn...
Preprocess the training dataset to identify which features/attributes are discrete vs. continuous valued. Ignores missing values in this determination.
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L277-L299
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._distarray_no_missing
python
def _distarray_no_missing(self, xc, xd): from scipy.spatial.distance import pdist, squareform #------------------------------------------# def pre_normalize(x): """Normalizes continuous features so they are in the same range (0 to 1)""" idx = 0 # goes through...
Distance array calculation for data with no missing values. The 'pdist() function outputs a condense distance array, and squareform() converts this vector-form distance vector to a square-form, redundant distance matrix. *This could be a target for saving memory in the future, by not needing to expand t...
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L301-L333
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...
EpistasisLab/scikit-rebate
skrebate/relieff.py
ReliefF._dtype_array
python
def _dtype_array(self): attrtype = [] attrdiff = [] for key in self._headers: if self.attr[key][0] == 'continuous': attrtype.append(1) else: attrtype.append(0) attrdiff.append(self.attr[key][3]) attrtype = np.array(att...
Return mask for discrete(0)/continuous(1) attributes and their indices. Return array of max/min diffs of attributes.
train
https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/relieff.py#L336-L354
null
class ReliefF(BaseEstimator): """Feature selection using data-mined expert knowledge. Based on the ReliefF algorithm as introduced in: Igor et al. Overcoming the myopia of inductive learning algorithms with RELIEFF (1997), Applied Intelligence, 7(1), p39-55""" """Note that ReliefF class establishe...