id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,300
Fizzadar/pyinfra
pyinfra/modules/vzctl.py
set
def set(state, host, ctid, save=True, **settings): ''' Set OpenVZ container details. + ctid: CTID of the container to set + save: whether to save the changes + settings: settings/arguments to apply to the container Settings/arguments: these are mapped directly to ``vztctl`` arguments, eg ``hostname='my-host.net'`` becomes ``--hostname my-host.net``. ''' args = ['{0}'.format(ctid)] if save: args.append('--save') for key, value in six.iteritems(settings): # Handle list values (eg --nameserver X --nameserver X) if isinstance(value, list): args.extend('--{0} {1}'.format(key, v) for v in value) else: args.append('--{0} {1}'.format(key, value)) yield 'vzctl set {0}'.format(' '.join(args))
python
def set(state, host, ctid, save=True, **settings): ''' Set OpenVZ container details. + ctid: CTID of the container to set + save: whether to save the changes + settings: settings/arguments to apply to the container Settings/arguments: these are mapped directly to ``vztctl`` arguments, eg ``hostname='my-host.net'`` becomes ``--hostname my-host.net``. ''' args = ['{0}'.format(ctid)] if save: args.append('--save') for key, value in six.iteritems(settings): # Handle list values (eg --nameserver X --nameserver X) if isinstance(value, list): args.extend('--{0} {1}'.format(key, v) for v in value) else: args.append('--{0} {1}'.format(key, value)) yield 'vzctl set {0}'.format(' '.join(args))
[ "def", "set", "(", "state", ",", "host", ",", "ctid", ",", "save", "=", "True", ",", "*", "*", "settings", ")", ":", "args", "=", "[", "'{0}'", ".", "format", "(", "ctid", ")", "]", "if", "save", ":", "args", ".", "append", "(", "'--save'", ")"...
Set OpenVZ container details. + ctid: CTID of the container to set + save: whether to save the changes + settings: settings/arguments to apply to the container Settings/arguments: these are mapped directly to ``vztctl`` arguments, eg ``hostname='my-host.net'`` becomes ``--hostname my-host.net``.
[ "Set", "OpenVZ", "container", "details", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/vzctl.py#L114-L139
24,301
Fizzadar/pyinfra
pyinfra_cli/util.py
exec_file
def exec_file(filename, return_locals=False, is_deploy_code=False): ''' Execute a Python file and optionally return it's attributes as a dict. ''' if filename not in PYTHON_CODES: with open(filename, 'r') as f: code = f.read() code = compile(code, filename, 'exec') PYTHON_CODES[filename] = code # Create some base attributes for our "module" data = { '__file__': filename, 'state': pseudo_state, } # Execute the code with locals/globals going into the dict above exec(PYTHON_CODES[filename], data) return data
python
def exec_file(filename, return_locals=False, is_deploy_code=False): ''' Execute a Python file and optionally return it's attributes as a dict. ''' if filename not in PYTHON_CODES: with open(filename, 'r') as f: code = f.read() code = compile(code, filename, 'exec') PYTHON_CODES[filename] = code # Create some base attributes for our "module" data = { '__file__': filename, 'state': pseudo_state, } # Execute the code with locals/globals going into the dict above exec(PYTHON_CODES[filename], data) return data
[ "def", "exec_file", "(", "filename", ",", "return_locals", "=", "False", ",", "is_deploy_code", "=", "False", ")", ":", "if", "filename", "not", "in", "PYTHON_CODES", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "code", "=", "...
Execute a Python file and optionally return it's attributes as a dict.
[ "Execute", "a", "Python", "file", "and", "optionally", "return", "it", "s", "attributes", "as", "a", "dict", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra_cli/util.py#L37-L58
24,302
Fizzadar/pyinfra
pyinfra/modules/server.py
shell
def shell(state, host, commands, chdir=None): ''' Run raw shell code. + commands: command or list of commands to execute on the remote server + chdir: directory to cd into before executing commands ''' # Ensure we have a list if isinstance(commands, six.string_types): commands = [commands] for command in commands: if chdir: yield 'cd {0} && ({1})'.format(chdir, command) else: yield command
python
def shell(state, host, commands, chdir=None): ''' Run raw shell code. + commands: command or list of commands to execute on the remote server + chdir: directory to cd into before executing commands ''' # Ensure we have a list if isinstance(commands, six.string_types): commands = [commands] for command in commands: if chdir: yield 'cd {0} && ({1})'.format(chdir, command) else: yield command
[ "def", "shell", "(", "state", ",", "host", ",", "commands", ",", "chdir", "=", "None", ")", ":", "# Ensure we have a list", "if", "isinstance", "(", "commands", ",", "six", ".", "string_types", ")", ":", "commands", "=", "[", "commands", "]", "for", "com...
Run raw shell code. + commands: command or list of commands to execute on the remote server + chdir: directory to cd into before executing commands
[ "Run", "raw", "shell", "code", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L39-L55
24,303
Fizzadar/pyinfra
pyinfra/modules/server.py
script
def script(state, host, filename, chdir=None): ''' Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(filename) yield files.put(state, host, filename, temp_file) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) else: yield temp_file
python
def script(state, host, filename, chdir=None): ''' Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(filename) yield files.put(state, host, filename, temp_file) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) else: yield temp_file
[ "def", "script", "(", "state", ",", "host", ",", "filename", ",", "chdir", "=", "None", ")", ":", "temp_file", "=", "state", ".", "get_temp_filename", "(", "filename", ")", "yield", "files", ".", "put", "(", "state", ",", "host", ",", "filename", ",", ...
Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script
[ "Upload", "and", "execute", "a", "local", "script", "on", "the", "remote", "host", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L59-L75
24,304
Fizzadar/pyinfra
pyinfra/modules/server.py
script_template
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(template_filename) yield files.template(state, host, template_filename, temp_file, **data) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) else: yield temp_file
python
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(template_filename) yield files.template(state, host, template_filename, temp_file, **data) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) else: yield temp_file
[ "def", "script_template", "(", "state", ",", "host", ",", "template_filename", ",", "chdir", "=", "None", ",", "*", "*", "data", ")", ":", "temp_file", "=", "state", ".", "get_temp_filename", "(", "template_filename", ")", "yield", "files", ".", "template", ...
Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script
[ "Generate", "upload", "and", "execute", "a", "local", "script", "template", "on", "the", "remote", "host", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L79-L95
24,305
Fizzadar/pyinfra
pyinfra/modules/server.py
hostname
def hostname(state, host, hostname, hostname_file=None): ''' Set the system hostname. + hostname: the hostname that should be set + hostname_file: the file that permanently sets the hostname Hostname file: By default pyinfra will auto detect this by targetting ``/etc/hostname`` on Linux and ``/etc/myname`` on OpenBSD. ''' if hostname_file is None: os = host.fact.os if os == 'Linux': hostname_file = '/etc/hostname' elif os == 'OpenBSD': hostname_file = '/etc/myname' current_hostname = host.fact.hostname if current_hostname != hostname: yield 'hostname {0}'.format(hostname) if hostname_file: # Create a whole new hostname file file = six.StringIO('{0}\n'.format(hostname)) # And ensure it exists yield files.put( state, host, file, hostname_file, )
python
def hostname(state, host, hostname, hostname_file=None): ''' Set the system hostname. + hostname: the hostname that should be set + hostname_file: the file that permanently sets the hostname Hostname file: By default pyinfra will auto detect this by targetting ``/etc/hostname`` on Linux and ``/etc/myname`` on OpenBSD. ''' if hostname_file is None: os = host.fact.os if os == 'Linux': hostname_file = '/etc/hostname' elif os == 'OpenBSD': hostname_file = '/etc/myname' current_hostname = host.fact.hostname if current_hostname != hostname: yield 'hostname {0}'.format(hostname) if hostname_file: # Create a whole new hostname file file = six.StringIO('{0}\n'.format(hostname)) # And ensure it exists yield files.put( state, host, file, hostname_file, )
[ "def", "hostname", "(", "state", ",", "host", ",", "hostname", ",", "hostname_file", "=", "None", ")", ":", "if", "hostname_file", "is", "None", ":", "os", "=", "host", ".", "fact", ".", "os", "if", "os", "==", "'Linux'", ":", "hostname_file", "=", "...
Set the system hostname. + hostname: the hostname that should be set + hostname_file: the file that permanently sets the hostname Hostname file: By default pyinfra will auto detect this by targetting ``/etc/hostname`` on Linux and ``/etc/myname`` on OpenBSD.
[ "Set", "the", "system", "hostname", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L125-L158
24,306
Fizzadar/pyinfra
pyinfra/modules/server.py
sysctl
def sysctl( state, host, name, value, persist=False, persist_file='/etc/sysctl.conf', ): ''' Edit sysctl configuration. + name: name of the sysctl setting to ensure + value: the value or list of values the sysctl should be + persist: whether to write this sysctl to the config + persist_file: file to write the sysctl to persist on reboot ''' string_value = ( ' '.join(value) if isinstance(value, list) else value ) existing_value = host.fact.sysctl.get(name) if not existing_value or existing_value != value: yield 'sysctl {0}={1}'.format(name, string_value) if persist: yield files.line( state, host, persist_file, '{0}[[:space:]]*=[[:space:]]*{1}'.format(name, string_value), replace='{0} = {1}'.format(name, string_value), )
python
def sysctl( state, host, name, value, persist=False, persist_file='/etc/sysctl.conf', ): ''' Edit sysctl configuration. + name: name of the sysctl setting to ensure + value: the value or list of values the sysctl should be + persist: whether to write this sysctl to the config + persist_file: file to write the sysctl to persist on reboot ''' string_value = ( ' '.join(value) if isinstance(value, list) else value ) existing_value = host.fact.sysctl.get(name) if not existing_value or existing_value != value: yield 'sysctl {0}={1}'.format(name, string_value) if persist: yield files.line( state, host, persist_file, '{0}[[:space:]]*=[[:space:]]*{1}'.format(name, string_value), replace='{0} = {1}'.format(name, string_value), )
[ "def", "sysctl", "(", "state", ",", "host", ",", "name", ",", "value", ",", "persist", "=", "False", ",", "persist_file", "=", "'/etc/sysctl.conf'", ",", ")", ":", "string_value", "=", "(", "' '", ".", "join", "(", "value", ")", "if", "isinstance", "("...
Edit sysctl configuration. + name: name of the sysctl setting to ensure + value: the value or list of values the sysctl should be + persist: whether to write this sysctl to the config + persist_file: file to write the sysctl to persist on reboot
[ "Edit", "sysctl", "configuration", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/server.py#L162-L191
24,307
Fizzadar/pyinfra
pyinfra/modules/files.py
download
def download( state, host, source_url, destination, user=None, group=None, mode=None, cache_time=None, force=False, ): ''' Download files from remote locations. + source_url: source URl of the file + destination: where to save the file + user: user to own the files + group: group to own the files + mode: permissions of the files + cache_time: if the file exists already, re-download after this time (in s) + force: always download the file, even if it already exists ''' # Get destination info info = host.fact.file(destination) # Destination is a directory? if info is False: raise OperationError( 'Destination {0} already exists and is not a file'.format(destination), ) # Do we download the file? Force by default download = force # Doesn't exist, lets download it if info is None: download = True # Destination file exists & cache_time: check when the file was last modified, # download if old elif cache_time: # Time on files is not tz-aware, and will be the same tz as the server's time, # so we can safely remove the tzinfo from host.fact.date before comparison. cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time) if info['mtime'] and info['mtime'] > cache_time: download = True # If we download, always do user/group/mode as SSH user may be different if download: yield 'wget -q {0} -O {1}'.format(source_url, destination) if user or group: yield chown(destination, user, group) if mode: yield chmod(destination, mode)
python
def download( state, host, source_url, destination, user=None, group=None, mode=None, cache_time=None, force=False, ): ''' Download files from remote locations. + source_url: source URl of the file + destination: where to save the file + user: user to own the files + group: group to own the files + mode: permissions of the files + cache_time: if the file exists already, re-download after this time (in s) + force: always download the file, even if it already exists ''' # Get destination info info = host.fact.file(destination) # Destination is a directory? if info is False: raise OperationError( 'Destination {0} already exists and is not a file'.format(destination), ) # Do we download the file? Force by default download = force # Doesn't exist, lets download it if info is None: download = True # Destination file exists & cache_time: check when the file was last modified, # download if old elif cache_time: # Time on files is not tz-aware, and will be the same tz as the server's time, # so we can safely remove the tzinfo from host.fact.date before comparison. cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time) if info['mtime'] and info['mtime'] > cache_time: download = True # If we download, always do user/group/mode as SSH user may be different if download: yield 'wget -q {0} -O {1}'.format(source_url, destination) if user or group: yield chown(destination, user, group) if mode: yield chmod(destination, mode)
[ "def", "download", "(", "state", ",", "host", ",", "source_url", ",", "destination", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ",", "cache_time", "=", "None", ",", "force", "=", "False", ",", ")", ":", "# Get dest...
Download files from remote locations. + source_url: source URl of the file + destination: where to save the file + user: user to own the files + group: group to own the files + mode: permissions of the files + cache_time: if the file exists already, re-download after this time (in s) + force: always download the file, even if it already exists
[ "Download", "files", "from", "remote", "locations", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L30-L79
24,308
Fizzadar/pyinfra
pyinfra/modules/files.py
replace
def replace(state, host, name, match, replace, flags=None): ''' A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed ''' yield sed_replace(name, match, replace, flags=flags)
python
def replace(state, host, name, match, replace, flags=None): ''' A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed ''' yield sed_replace(name, match, replace, flags=flags)
[ "def", "replace", "(", "state", ",", "host", ",", "name", ",", "match", ",", "replace", ",", "flags", "=", "None", ")", ":", "yield", "sed_replace", "(", "name", ",", "match", ",", "replace", ",", "flags", "=", "flags", ")" ]
A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed
[ "A", "simple", "shortcut", "for", "replacing", "text", "in", "files", "with", "sed", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L169-L179
24,309
Fizzadar/pyinfra
pyinfra/modules/files.py
sync
def sync( state, host, source, destination, user=None, group=None, mode=None, delete=False, exclude=None, exclude_dir=None, add_deploy_dir=True, ): ''' Syncs a local directory with a remote one, with delete support. Note that delete will remove extra files on the remote side, but not extra directories. + source: local directory to sync + destination: remote directory to sync to + user: user to own the files and directories + group: group to own the files and directories + mode: permissions of the files + delete: delete remote files not present locally + exclude: string or list/tuple of strings to match & exclude files (eg *.pyc) + exclude_dir: string or list/tuple of strings to match & exclude directories (eg node_modules) ''' # If we don't enforce the source ending with /, remote_dirname below might start with # a /, which makes the path.join cut off the destination bit. if not source.endswith(path.sep): source = '{0}{1}'.format(source, path.sep) # Add deploy directory? if add_deploy_dir and state.deploy_dir: source = path.join(state.deploy_dir, source) # Ensure the source directory exists if not path.isdir(source): raise IOError('No such directory: {0}'.format(source)) # Ensure exclude is a list/tuple if exclude is not None: if not isinstance(exclude, (list, tuple)): exclude = [exclude] # Ensure exclude_dir is a list/tuple if exclude_dir is not None: if not isinstance(exclude_dir, (list, tuple)): exclude_dir = [exclude_dir] put_files = [] ensure_dirnames = [] for dirname, _, filenames in walk(source): remote_dirname = dirname.replace(source, '') # Should we exclude this dir? if exclude_dir and any(fnmatch(remote_dirname, match) for match in exclude_dir): continue if remote_dirname: ensure_dirnames.append(remote_dirname) for filename in filenames: full_filename = path.join(dirname, filename) # Should we exclude this file? if exclude and any(fnmatch(full_filename, match) for match in exclude): continue put_files.append(( # Join local as normal (unix, win) full_filename, # Join remote as unix like '/'.join( item for item in (destination, remote_dirname, filename) if item ), )) # Ensure the destination directory yield directory( state, host, destination, user=user, group=group, ) # Ensure any remote dirnames for dirname in ensure_dirnames: yield directory( state, host, '/'.join((destination, dirname)), user=user, group=group, ) # Put each file combination for local_filename, remote_filename in put_files: yield put( state, host, local_filename, remote_filename, user=user, group=group, mode=mode, add_deploy_dir=False, ) # Delete any extra files if delete: remote_filenames = set(host.fact.find_files(destination) or []) wanted_filenames = set([remote_filename for _, remote_filename in put_files]) files_to_delete = remote_filenames - wanted_filenames for filename in files_to_delete: # Should we exclude this file? if exclude and any(fnmatch(filename, match) for match in exclude): continue yield file(state, host, filename, present=False)
python
def sync( state, host, source, destination, user=None, group=None, mode=None, delete=False, exclude=None, exclude_dir=None, add_deploy_dir=True, ): ''' Syncs a local directory with a remote one, with delete support. Note that delete will remove extra files on the remote side, but not extra directories. + source: local directory to sync + destination: remote directory to sync to + user: user to own the files and directories + group: group to own the files and directories + mode: permissions of the files + delete: delete remote files not present locally + exclude: string or list/tuple of strings to match & exclude files (eg *.pyc) + exclude_dir: string or list/tuple of strings to match & exclude directories (eg node_modules) ''' # If we don't enforce the source ending with /, remote_dirname below might start with # a /, which makes the path.join cut off the destination bit. if not source.endswith(path.sep): source = '{0}{1}'.format(source, path.sep) # Add deploy directory? if add_deploy_dir and state.deploy_dir: source = path.join(state.deploy_dir, source) # Ensure the source directory exists if not path.isdir(source): raise IOError('No such directory: {0}'.format(source)) # Ensure exclude is a list/tuple if exclude is not None: if not isinstance(exclude, (list, tuple)): exclude = [exclude] # Ensure exclude_dir is a list/tuple if exclude_dir is not None: if not isinstance(exclude_dir, (list, tuple)): exclude_dir = [exclude_dir] put_files = [] ensure_dirnames = [] for dirname, _, filenames in walk(source): remote_dirname = dirname.replace(source, '') # Should we exclude this dir? if exclude_dir and any(fnmatch(remote_dirname, match) for match in exclude_dir): continue if remote_dirname: ensure_dirnames.append(remote_dirname) for filename in filenames: full_filename = path.join(dirname, filename) # Should we exclude this file? if exclude and any(fnmatch(full_filename, match) for match in exclude): continue put_files.append(( # Join local as normal (unix, win) full_filename, # Join remote as unix like '/'.join( item for item in (destination, remote_dirname, filename) if item ), )) # Ensure the destination directory yield directory( state, host, destination, user=user, group=group, ) # Ensure any remote dirnames for dirname in ensure_dirnames: yield directory( state, host, '/'.join((destination, dirname)), user=user, group=group, ) # Put each file combination for local_filename, remote_filename in put_files: yield put( state, host, local_filename, remote_filename, user=user, group=group, mode=mode, add_deploy_dir=False, ) # Delete any extra files if delete: remote_filenames = set(host.fact.find_files(destination) or []) wanted_filenames = set([remote_filename for _, remote_filename in put_files]) files_to_delete = remote_filenames - wanted_filenames for filename in files_to_delete: # Should we exclude this file? if exclude and any(fnmatch(filename, match) for match in exclude): continue yield file(state, host, filename, present=False)
[ "def", "sync", "(", "state", ",", "host", ",", "source", ",", "destination", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ",", "delete", "=", "False", ",", "exclude", "=", "None", ",", "exclude_dir", "=", "None", "...
Syncs a local directory with a remote one, with delete support. Note that delete will remove extra files on the remote side, but not extra directories. + source: local directory to sync + destination: remote directory to sync to + user: user to own the files and directories + group: group to own the files and directories + mode: permissions of the files + delete: delete remote files not present locally + exclude: string or list/tuple of strings to match & exclude files (eg *.pyc) + exclude_dir: string or list/tuple of strings to match & exclude directories (eg node_modules)
[ "Syncs", "a", "local", "directory", "with", "a", "remote", "one", "with", "delete", "support", ".", "Note", "that", "delete", "will", "remove", "extra", "files", "on", "the", "remote", "side", "but", "not", "extra", "directories", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L185-L290
24,310
Fizzadar/pyinfra
pyinfra/modules/files.py
put
def put( state, host, local_filename, remote_filename, user=None, group=None, mode=None, add_deploy_dir=True, ): ''' Copy a local file to the remote system. + local_filename: local filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files ''' # Upload IO objects as-is if hasattr(local_filename, 'read'): local_file = local_filename # Assume string filename else: # Add deploy directory? if add_deploy_dir and state.deploy_dir: local_filename = path.join(state.deploy_dir, local_filename) local_file = local_filename if not path.isfile(local_file): raise IOError('No such file: {0}'.format(local_file)) mode = ensure_mode_int(mode) remote_file = host.fact.file(remote_filename) # No remote file, always upload and user/group/mode if supplied if not remote_file: yield (local_file, remote_filename) if user or group: yield chown(remote_filename, user, group) if mode: yield chmod(remote_filename, mode) # File exists, check sum and check user/group/mode if supplied else: local_sum = get_file_sha1(local_filename) remote_sum = host.fact.sha1_file(remote_filename) # Check sha1sum, upload if needed if local_sum != remote_sum: yield (local_file, remote_filename) if user or group: yield chown(remote_filename, user, group) if mode: yield chmod(remote_filename, mode) else: # Check mode if mode and remote_file['mode'] != mode: yield chmod(remote_filename, mode) # Check user/group if ( (user and remote_file['user'] != user) or (group and remote_file['group'] != group) ): yield chown(remote_filename, user, group)
python
def put( state, host, local_filename, remote_filename, user=None, group=None, mode=None, add_deploy_dir=True, ): ''' Copy a local file to the remote system. + local_filename: local filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files ''' # Upload IO objects as-is if hasattr(local_filename, 'read'): local_file = local_filename # Assume string filename else: # Add deploy directory? if add_deploy_dir and state.deploy_dir: local_filename = path.join(state.deploy_dir, local_filename) local_file = local_filename if not path.isfile(local_file): raise IOError('No such file: {0}'.format(local_file)) mode = ensure_mode_int(mode) remote_file = host.fact.file(remote_filename) # No remote file, always upload and user/group/mode if supplied if not remote_file: yield (local_file, remote_filename) if user or group: yield chown(remote_filename, user, group) if mode: yield chmod(remote_filename, mode) # File exists, check sum and check user/group/mode if supplied else: local_sum = get_file_sha1(local_filename) remote_sum = host.fact.sha1_file(remote_filename) # Check sha1sum, upload if needed if local_sum != remote_sum: yield (local_file, remote_filename) if user or group: yield chown(remote_filename, user, group) if mode: yield chmod(remote_filename, mode) else: # Check mode if mode and remote_file['mode'] != mode: yield chmod(remote_filename, mode) # Check user/group if ( (user and remote_file['user'] != user) or (group and remote_file['group'] != group) ): yield chown(remote_filename, user, group)
[ "def", "put", "(", "state", ",", "host", ",", "local_filename", ",", "remote_filename", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ",", "add_deploy_dir", "=", "True", ",", ")", ":", "# Upload IO objects as-is", "if", "...
Copy a local file to the remote system. + local_filename: local filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files
[ "Copy", "a", "local", "file", "to", "the", "remote", "system", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L297-L364
24,311
Fizzadar/pyinfra
pyinfra/modules/files.py
template
def template( state, host, template_filename, remote_filename, user=None, group=None, mode=None, **data ): ''' Generate a template and write it to the remote system. + template_filename: local template filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files ''' if state.deploy_dir: template_filename = path.join(state.deploy_dir, template_filename) # Ensure host is always available inside templates data['host'] = host data['inventory'] = state.inventory # Render and make file-like it's output try: output = get_template(template_filename).render(data) except (TemplateSyntaxError, UndefinedError) as e: _, _, trace = sys.exc_info() # Jump through to the *second last* traceback, which contains the line number # of the error within the in-memory Template object while trace.tb_next: if trace.tb_next.tb_next: trace = trace.tb_next else: break line_number = trace.tb_frame.f_lineno # Quickly read the line in question and one above/below for nicer debugging template_lines = open(template_filename, 'r').readlines() template_lines = [line.strip() for line in template_lines] relevant_lines = template_lines[max(line_number - 2, 0):line_number + 1] raise OperationError('Error in template: {0} (L{1}): {2}\n...\n{3}\n...'.format( template_filename, line_number, e, '\n'.join(relevant_lines), )) output_file = six.StringIO(output) # Set the template attribute for nicer debugging output_file.template = template_filename # Pass to the put function yield put( state, host, output_file, remote_filename, user=user, group=group, mode=mode, add_deploy_dir=False, )
python
def template( state, host, template_filename, remote_filename, user=None, group=None, mode=None, **data ): ''' Generate a template and write it to the remote system. + template_filename: local template filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files ''' if state.deploy_dir: template_filename = path.join(state.deploy_dir, template_filename) # Ensure host is always available inside templates data['host'] = host data['inventory'] = state.inventory # Render and make file-like it's output try: output = get_template(template_filename).render(data) except (TemplateSyntaxError, UndefinedError) as e: _, _, trace = sys.exc_info() # Jump through to the *second last* traceback, which contains the line number # of the error within the in-memory Template object while trace.tb_next: if trace.tb_next.tb_next: trace = trace.tb_next else: break line_number = trace.tb_frame.f_lineno # Quickly read the line in question and one above/below for nicer debugging template_lines = open(template_filename, 'r').readlines() template_lines = [line.strip() for line in template_lines] relevant_lines = template_lines[max(line_number - 2, 0):line_number + 1] raise OperationError('Error in template: {0} (L{1}): {2}\n...\n{3}\n...'.format( template_filename, line_number, e, '\n'.join(relevant_lines), )) output_file = six.StringIO(output) # Set the template attribute for nicer debugging output_file.template = template_filename # Pass to the put function yield put( state, host, output_file, remote_filename, user=user, group=group, mode=mode, add_deploy_dir=False, )
[ "def", "template", "(", "state", ",", "host", ",", "template_filename", ",", "remote_filename", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ",", "*", "*", "data", ")", ":", "if", "state", ".", "deploy_dir", ":", "te...
Generate a template and write it to the remote system. + template_filename: local template filename + remote_filename: remote filename + user: user to own the files + group: group to own the files + mode: permissions of the files
[ "Generate", "a", "template", "and", "write", "it", "to", "the", "remote", "system", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L368-L424
24,312
Fizzadar/pyinfra
pyinfra/modules/postgresql.py
sql
def sql( state, host, sql, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Execute arbitrary SQL against PostgreSQL. + sql: SQL command(s) to execute + database: optional database to execute against + postgresql_*: global module arguments, see above ''' yield make_execute_psql_command( sql, database=database, user=postgresql_user, password=postgresql_password, host=postgresql_host, port=postgresql_port, )
python
def sql( state, host, sql, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Execute arbitrary SQL against PostgreSQL. + sql: SQL command(s) to execute + database: optional database to execute against + postgresql_*: global module arguments, see above ''' yield make_execute_psql_command( sql, database=database, user=postgresql_user, password=postgresql_password, host=postgresql_host, port=postgresql_port, )
[ "def", "sql", "(", "state", ",", "host", ",", "sql", ",", "database", "=", "None", ",", "# Details for speaking to PostgreSQL via `psql` CLI", "postgresql_user", "=", "None", ",", "postgresql_password", "=", "None", ",", "postgresql_host", "=", "None", ",", "postg...
Execute arbitrary SQL against PostgreSQL. + sql: SQL command(s) to execute + database: optional database to execute against + postgresql_*: global module arguments, see above
[ "Execute", "arbitrary", "SQL", "against", "PostgreSQL", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/postgresql.py#L22-L44
24,313
Fizzadar/pyinfra
pyinfra/modules/postgresql.py
dump
def dump( state, host, remote_filename, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + database: name of the database to dump + remote_filename: name of the file to dump the SQL to + postgresql_*: global module arguments, see above ''' yield '{0} > {1}'.format(make_psql_command( executable='pg_dump', database=database, user=postgresql_user, password=postgresql_password, host=postgresql_host, port=postgresql_port, ), remote_filename)
python
def dump( state, host, remote_filename, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + database: name of the database to dump + remote_filename: name of the file to dump the SQL to + postgresql_*: global module arguments, see above ''' yield '{0} > {1}'.format(make_psql_command( executable='pg_dump', database=database, user=postgresql_user, password=postgresql_password, host=postgresql_host, port=postgresql_port, ), remote_filename)
[ "def", "dump", "(", "state", ",", "host", ",", "remote_filename", ",", "database", "=", "None", ",", "# Details for speaking to PostgreSQL via `psql` CLI", "postgresql_user", "=", "None", ",", "postgresql_password", "=", "None", ",", "postgresql_host", "=", "None", ...
Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + database: name of the database to dump + remote_filename: name of the file to dump the SQL to + postgresql_*: global module arguments, see above
[ "Dump", "a", "PostgreSQL", "database", "into", "a", ".", "sql", "file", ".", "Requires", "mysqldump", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/postgresql.py#L201-L223
24,314
Fizzadar/pyinfra
pyinfra/api/facts.py
get_fact
def get_fact(state, host, name): ''' Wrapper around ``get_facts`` returning facts for one host or a function that does. ''' # Expecting a function to return if callable(getattr(FACTS[name], 'command', None)): def wrapper(*args): fact_data = get_facts(state, name, args=args, ensure_hosts=(host,)) return fact_data.get(host) return wrapper # Expecting the fact as a return value else: # Get the fact fact_data = get_facts(state, name, ensure_hosts=(host,)) return fact_data.get(host)
python
def get_fact(state, host, name): ''' Wrapper around ``get_facts`` returning facts for one host or a function that does. ''' # Expecting a function to return if callable(getattr(FACTS[name], 'command', None)): def wrapper(*args): fact_data = get_facts(state, name, args=args, ensure_hosts=(host,)) return fact_data.get(host) return wrapper # Expecting the fact as a return value else: # Get the fact fact_data = get_facts(state, name, ensure_hosts=(host,)) return fact_data.get(host)
[ "def", "get_fact", "(", "state", ",", "host", ",", "name", ")", ":", "# Expecting a function to return", "if", "callable", "(", "getattr", "(", "FACTS", "[", "name", "]", ",", "'command'", ",", "None", ")", ")", ":", "def", "wrapper", "(", "*", "args", ...
Wrapper around ``get_facts`` returning facts for one host or a function that does.
[ "Wrapper", "around", "get_facts", "returning", "facts", "for", "one", "host", "or", "a", "function", "that", "does", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/facts.py#L249-L268
24,315
Fizzadar/pyinfra
pyinfra/modules/apt.py
key
def key(state, host, key=None, keyserver=None, keyid=None): ''' Add apt gpg keys with ``apt-key``. + key: filename or URL + keyserver: URL of keyserver to fetch key from + keyid: key identifier when using keyserver Note: Always returns an add command, not state checking. keyserver/id: These must be provided together. ''' if key: # If URL, wget the key to stdout and pipe into apt-key, because the "adv" # apt-key passes to gpg which doesn't always support https! if urlparse(key).scheme: yield 'wget -O- {0} | apt-key add -'.format(key) else: yield 'apt-key add {0}'.format(key) if keyserver and keyid: yield 'apt-key adv --keyserver {0} --recv-keys {1}'.format(keyserver, keyid)
python
def key(state, host, key=None, keyserver=None, keyid=None): ''' Add apt gpg keys with ``apt-key``. + key: filename or URL + keyserver: URL of keyserver to fetch key from + keyid: key identifier when using keyserver Note: Always returns an add command, not state checking. keyserver/id: These must be provided together. ''' if key: # If URL, wget the key to stdout and pipe into apt-key, because the "adv" # apt-key passes to gpg which doesn't always support https! if urlparse(key).scheme: yield 'wget -O- {0} | apt-key add -'.format(key) else: yield 'apt-key add {0}'.format(key) if keyserver and keyid: yield 'apt-key adv --keyserver {0} --recv-keys {1}'.format(keyserver, keyid)
[ "def", "key", "(", "state", ",", "host", ",", "key", "=", "None", ",", "keyserver", "=", "None", ",", "keyid", "=", "None", ")", ":", "if", "key", ":", "# If URL, wget the key to stdout and pipe into apt-key, because the \"adv\"", "# apt-key passes to gpg which doesn'...
Add apt gpg keys with ``apt-key``. + key: filename or URL + keyserver: URL of keyserver to fetch key from + keyid: key identifier when using keyserver Note: Always returns an add command, not state checking. keyserver/id: These must be provided together.
[ "Add", "apt", "gpg", "keys", "with", "apt", "-", "key", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/apt.py#L40-L64
24,316
Fizzadar/pyinfra
pyinfra/modules/apt.py
update
def update(state, host, cache_time=None, touch_periodic=False): ''' Updates apt repos. + cache_time: cache updates for this many seconds + touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update ''' # If cache_time check when apt was last updated, prevent updates if within time if cache_time: # Ubuntu provides this handy file cache_info = host.fact.file(APT_UPDATE_FILENAME) # Time on files is not tz-aware, and will be the same tz as the server's time, # so we can safely remove the tzinfo from host.fact.date before comparison. host_cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time) if cache_info and cache_info['mtime'] and cache_info['mtime'] > host_cache_time: return yield 'apt-get update' # Some apt systems (Debian) have the /var/lib/apt/periodic directory, but # don't bother touching anything in there - so pyinfra does it, enabling # cache_time to work. if cache_time: yield 'touch {0}'.format(APT_UPDATE_FILENAME)
python
def update(state, host, cache_time=None, touch_periodic=False): ''' Updates apt repos. + cache_time: cache updates for this many seconds + touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update ''' # If cache_time check when apt was last updated, prevent updates if within time if cache_time: # Ubuntu provides this handy file cache_info = host.fact.file(APT_UPDATE_FILENAME) # Time on files is not tz-aware, and will be the same tz as the server's time, # so we can safely remove the tzinfo from host.fact.date before comparison. host_cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time) if cache_info and cache_info['mtime'] and cache_info['mtime'] > host_cache_time: return yield 'apt-get update' # Some apt systems (Debian) have the /var/lib/apt/periodic directory, but # don't bother touching anything in there - so pyinfra does it, enabling # cache_time to work. if cache_time: yield 'touch {0}'.format(APT_UPDATE_FILENAME)
[ "def", "update", "(", "state", ",", "host", ",", "cache_time", "=", "None", ",", "touch_periodic", "=", "False", ")", ":", "# If cache_time check when apt was last updated, prevent updates if within time", "if", "cache_time", ":", "# Ubuntu provides this handy file", "cache...
Updates apt repos. + cache_time: cache updates for this many seconds + touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update
[ "Updates", "apt", "repos", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/apt.py#L188-L213
24,317
Fizzadar/pyinfra
pyinfra/api/connectors/local.py
run_shell_command
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer. ''' command = make_command(command, **command_kwargs) logger.debug('--> Running command on localhost: {0}'.format(command)) if print_output: print('{0}>>> {1}'.format(host.print_prefix, command)) process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) # Iterate through outputs to get an exit status and generate desired list # output, done in two greenlets so stdout isn't printed before stderr. Not # attached to state.pool to avoid blocking it with 2x n-hosts greenlets. stdout_reader = gevent.spawn( read_buffer, process.stdout, print_output=print_output, print_func=lambda line: '{0}{1}'.format(host.print_prefix, line), ) stderr_reader = gevent.spawn( read_buffer, process.stderr, print_output=print_output, print_func=lambda line: '{0}{1}'.format( host.print_prefix, click.style(line, 'red'), ), ) # Wait on output, with our timeout (or None) greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout) # Timeout doesn't raise an exception, but gevent.wait returns the greenlets # which did complete. So if both haven't completed, we kill them and fail # with a timeout. if len(greenlets) != 2: stdout_reader.kill() stderr_reader.kill() raise timeout_error() # Read the buffers into a list of lines stdout = stdout_reader.get() stderr = stderr_reader.get() logger.debug('--> Waiting for exit status...') process.wait() # Close any open file descriptor process.stdout.close() logger.debug('--> Command exit status: {0}'.format(process.returncode)) return process.returncode == 0, stdout, stderr
python
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer. ''' command = make_command(command, **command_kwargs) logger.debug('--> Running command on localhost: {0}'.format(command)) if print_output: print('{0}>>> {1}'.format(host.print_prefix, command)) process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) # Iterate through outputs to get an exit status and generate desired list # output, done in two greenlets so stdout isn't printed before stderr. Not # attached to state.pool to avoid blocking it with 2x n-hosts greenlets. stdout_reader = gevent.spawn( read_buffer, process.stdout, print_output=print_output, print_func=lambda line: '{0}{1}'.format(host.print_prefix, line), ) stderr_reader = gevent.spawn( read_buffer, process.stderr, print_output=print_output, print_func=lambda line: '{0}{1}'.format( host.print_prefix, click.style(line, 'red'), ), ) # Wait on output, with our timeout (or None) greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout) # Timeout doesn't raise an exception, but gevent.wait returns the greenlets # which did complete. So if both haven't completed, we kill them and fail # with a timeout. if len(greenlets) != 2: stdout_reader.kill() stderr_reader.kill() raise timeout_error() # Read the buffers into a list of lines stdout = stdout_reader.get() stderr = stderr_reader.get() logger.debug('--> Waiting for exit status...') process.wait() # Close any open file descriptor process.stdout.close() logger.debug('--> Command exit status: {0}'.format(process.returncode)) return process.returncode == 0, stdout, stderr
[ "def", "run_shell_command", "(", "state", ",", "host", ",", "command", ",", "get_pty", "=", "False", ",", "timeout", "=", "None", ",", "print_output", "=", "False", ",", "*", "*", "command_kwargs", ")", ":", "command", "=", "make_command", "(", "command", ...
Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer.
[ "Execute", "a", "command", "on", "the", "local", "machine", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/local.py#L39-L110
24,318
Fizzadar/pyinfra
pyinfra/modules/init.py
upstart
def upstart( state, host, name, running=True, restarted=False, reloaded=False, command=None, enabled=None, ): ''' Manage the state of upstart managed services. + name: name of the service to manage + running: whether the service should be running + restarted: whether the service should be restarted + reloaded: whether the service should be reloaded + command: custom command to pass like: ``/etc/rc.d/<name> <command>`` + enabled: whether this service should be enabled/disabled on boot Enabling/disabling services: Upstart jobs define runlevels in their config files - as such there is no way to edit/list these without fiddling with the config. So pyinfra simply manages the existence of a ``/etc/init/<service>.override`` file, and sets its content to "manual" to disable automatic start of services. ''' yield _handle_service_control( name, host.fact.upstart_status, 'initctl {1} {0}', running, restarted, reloaded, command, ) # Upstart jobs are setup w/runlevels etc in their config files, so here we just check # there's no override file. if enabled is True: yield files.file( state, host, '/etc/init/{0}.override'.format(name), present=False, ) # Set the override file to "manual" to disable automatic start elif enabled is False: yield 'echo "manual" > /etc/init/{0}.override'.format(name)
python
def upstart( state, host, name, running=True, restarted=False, reloaded=False, command=None, enabled=None, ): ''' Manage the state of upstart managed services. + name: name of the service to manage + running: whether the service should be running + restarted: whether the service should be restarted + reloaded: whether the service should be reloaded + command: custom command to pass like: ``/etc/rc.d/<name> <command>`` + enabled: whether this service should be enabled/disabled on boot Enabling/disabling services: Upstart jobs define runlevels in their config files - as such there is no way to edit/list these without fiddling with the config. So pyinfra simply manages the existence of a ``/etc/init/<service>.override`` file, and sets its content to "manual" to disable automatic start of services. ''' yield _handle_service_control( name, host.fact.upstart_status, 'initctl {1} {0}', running, restarted, reloaded, command, ) # Upstart jobs are setup w/runlevels etc in their config files, so here we just check # there's no override file. if enabled is True: yield files.file( state, host, '/etc/init/{0}.override'.format(name), present=False, ) # Set the override file to "manual" to disable automatic start elif enabled is False: yield 'echo "manual" > /etc/init/{0}.override'.format(name)
[ "def", "upstart", "(", "state", ",", "host", ",", "name", ",", "running", "=", "True", ",", "restarted", "=", "False", ",", "reloaded", "=", "False", ",", "command", "=", "None", ",", "enabled", "=", "None", ",", ")", ":", "yield", "_handle_service_con...
Manage the state of upstart managed services. + name: name of the service to manage + running: whether the service should be running + restarted: whether the service should be restarted + reloaded: whether the service should be reloaded + command: custom command to pass like: ``/etc/rc.d/<name> <command>`` + enabled: whether this service should be enabled/disabled on boot Enabling/disabling services: Upstart jobs define runlevels in their config files - as such there is no way to edit/list these without fiddling with the config. So pyinfra simply manages the existence of a ``/etc/init/<service>.override`` file, and sets its content to "manual" to disable automatic start of services.
[ "Manage", "the", "state", "of", "upstart", "managed", "services", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/init.py#L209-L248
24,319
Fizzadar/pyinfra
pyinfra/modules/init.py
service
def service( state, host, *args, **kwargs ): ''' Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments. ''' if host.fact.which('systemctl'): yield systemd(state, host, *args, **kwargs) return if host.fact.which('initctl'): yield upstart(state, host, *args, **kwargs) return if host.fact.directory('/etc/init.d'): yield d(state, host, *args, **kwargs) return if host.fact.directory('/etc/rc.d'): yield rc(state, host, *args, **kwargs) return raise OperationError(( 'No init system found ' '(no systemctl, initctl, /etc/init.d or /etc/rc.d found)' ))
python
def service( state, host, *args, **kwargs ): ''' Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments. ''' if host.fact.which('systemctl'): yield systemd(state, host, *args, **kwargs) return if host.fact.which('initctl'): yield upstart(state, host, *args, **kwargs) return if host.fact.directory('/etc/init.d'): yield d(state, host, *args, **kwargs) return if host.fact.directory('/etc/rc.d'): yield rc(state, host, *args, **kwargs) return raise OperationError(( 'No init system found ' '(no systemctl, initctl, /etc/init.d or /etc/rc.d found)' ))
[ "def", "service", "(", "state", ",", "host", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "host", ".", "fact", ".", "which", "(", "'systemctl'", ")", ":", "yield", "systemd", "(", "state", ",", "host", ",", "*", "args", ",", "*", ...
Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments.
[ "Manage", "the", "state", "of", "services", ".", "This", "command", "checks", "for", "the", "presence", "of", "all", "the", "init", "systems", "pyinfra", "can", "handle", "and", "executes", "the", "relevant", "operation", ".", "See", "init", "system", "sepci...
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/init.py#L321-L350
24,320
Fizzadar/pyinfra
pyinfra/api/connectors/ssh.py
connect
def connect(state, host, for_fact=None): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be provided via SSH config (alias), data, or the hosts name hostname = kwargs.pop( 'hostname', host.data.ssh_hostname or host.name, ) try: # Create new client & connect to the host client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname, **kwargs) # Enable SSH forwarding session = client.get_transport().open_session() AgentRequestHandler(session) # Log log_message = '{0}{1}'.format( host.print_prefix, click.style('Connected', 'green'), ) if for_fact: log_message = '{0}{1}'.format( log_message, ' (for {0} fact)'.format(for_fact), ) logger.info(log_message) return client except AuthenticationException: auth_kwargs = {} for key, value in kwargs.items(): if key in ('username', 'password'): auth_kwargs[key] = value continue if key == 'pkey' and value: auth_kwargs['key'] = host.data.ssh_key auth_args = ', '.join( '{0}={1}'.format(key, value) for key, value in auth_kwargs.items() ) _log_connect_error(host, 'Authentication error', auth_args) except SSHException as e: _log_connect_error(host, 'SSH error', e) except gaierror: _log_connect_error(host, 'Could not resolve hostname', hostname) except socket_error as e: _log_connect_error(host, 'Could not connect', e) except EOFError as e: _log_connect_error(host, 'EOF error', e)
python
def connect(state, host, for_fact=None): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be provided via SSH config (alias), data, or the hosts name hostname = kwargs.pop( 'hostname', host.data.ssh_hostname or host.name, ) try: # Create new client & connect to the host client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname, **kwargs) # Enable SSH forwarding session = client.get_transport().open_session() AgentRequestHandler(session) # Log log_message = '{0}{1}'.format( host.print_prefix, click.style('Connected', 'green'), ) if for_fact: log_message = '{0}{1}'.format( log_message, ' (for {0} fact)'.format(for_fact), ) logger.info(log_message) return client except AuthenticationException: auth_kwargs = {} for key, value in kwargs.items(): if key in ('username', 'password'): auth_kwargs[key] = value continue if key == 'pkey' and value: auth_kwargs['key'] = host.data.ssh_key auth_args = ', '.join( '{0}={1}'.format(key, value) for key, value in auth_kwargs.items() ) _log_connect_error(host, 'Authentication error', auth_args) except SSHException as e: _log_connect_error(host, 'SSH error', e) except gaierror: _log_connect_error(host, 'Could not resolve hostname', hostname) except socket_error as e: _log_connect_error(host, 'Could not connect', e) except EOFError as e: _log_connect_error(host, 'EOF error', e)
[ "def", "connect", "(", "state", ",", "host", ",", "for_fact", "=", "None", ")", ":", "kwargs", "=", "_make_paramiko_kwargs", "(", "state", ",", "host", ")", "logger", ".", "debug", "(", "'Connecting to: {0} ({1})'", ".", "format", "(", "host", ".", "name",...
Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel.
[ "Connect", "to", "a", "single", "host", ".", "Returns", "the", "SSH", "client", "if", "succesful", ".", "Stateless", "by", "design", "so", "can", "be", "run", "in", "parallel", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/ssh.py#L150-L219
24,321
Fizzadar/pyinfra
pyinfra/api/connectors/ssh.py
run_shell_command
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the specified host. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer. ''' command = make_command(command, **command_kwargs) logger.debug('Running command on {0}: (pty={1}) {2}'.format( host.name, get_pty, command, )) if print_output: print('{0}>>> {1}'.format(host.print_prefix, command)) # Run it! Get stdout, stderr & the underlying channel _, stdout_buffer, stderr_buffer = host.connection.exec_command( command, get_pty=get_pty, ) channel = stdout_buffer.channel # Iterate through outputs to get an exit status and generate desired list # output, done in two greenlets so stdout isn't printed before stderr. Not # attached to state.pool to avoid blocking it with 2x n-hosts greenlets. stdout_reader = gevent.spawn( read_buffer, stdout_buffer, print_output=print_output, print_func=lambda line: '{0}{1}'.format(host.print_prefix, line), ) stderr_reader = gevent.spawn( read_buffer, stderr_buffer, print_output=print_output, print_func=lambda line: '{0}{1}'.format( host.print_prefix, click.style(line, 'red'), ), ) # Wait on output, with our timeout (or None) greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout) # Timeout doesn't raise an exception, but gevent.wait returns the greenlets # which did complete. So if both haven't completed, we kill them and fail # with a timeout. if len(greenlets) != 2: stdout_reader.kill() stderr_reader.kill() raise timeout_error() # Read the buffers into a list of lines stdout = stdout_reader.get() stderr = stderr_reader.get() logger.debug('Waiting for exit status...') exit_status = channel.recv_exit_status() logger.debug('Command exit status: {0}'.format(exit_status)) return exit_status == 0, stdout, stderr
python
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the specified host. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer. ''' command = make_command(command, **command_kwargs) logger.debug('Running command on {0}: (pty={1}) {2}'.format( host.name, get_pty, command, )) if print_output: print('{0}>>> {1}'.format(host.print_prefix, command)) # Run it! Get stdout, stderr & the underlying channel _, stdout_buffer, stderr_buffer = host.connection.exec_command( command, get_pty=get_pty, ) channel = stdout_buffer.channel # Iterate through outputs to get an exit status and generate desired list # output, done in two greenlets so stdout isn't printed before stderr. Not # attached to state.pool to avoid blocking it with 2x n-hosts greenlets. stdout_reader = gevent.spawn( read_buffer, stdout_buffer, print_output=print_output, print_func=lambda line: '{0}{1}'.format(host.print_prefix, line), ) stderr_reader = gevent.spawn( read_buffer, stderr_buffer, print_output=print_output, print_func=lambda line: '{0}{1}'.format( host.print_prefix, click.style(line, 'red'), ), ) # Wait on output, with our timeout (or None) greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout) # Timeout doesn't raise an exception, but gevent.wait returns the greenlets # which did complete. So if both haven't completed, we kill them and fail # with a timeout. if len(greenlets) != 2: stdout_reader.kill() stderr_reader.kill() raise timeout_error() # Read the buffers into a list of lines stdout = stdout_reader.get() stderr = stderr_reader.get() logger.debug('Waiting for exit status...') exit_status = channel.recv_exit_status() logger.debug('Command exit status: {0}'.format(exit_status)) return exit_status == 0, stdout, stderr
[ "def", "run_shell_command", "(", "state", ",", "host", ",", "command", ",", "get_pty", "=", "False", ",", "timeout", "=", "None", ",", "print_output", "=", "False", ",", "*", "*", "command_kwargs", ")", ":", "command", "=", "make_command", "(", "command", ...
Execute a command on the specified host. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer.
[ "Execute", "a", "command", "on", "the", "specified", "host", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/ssh.py#L222-L298
24,322
Fizzadar/pyinfra
pyinfra/api/connectors/ssh.py
put_file
def put_file( state, host, filename_or_io, remote_filename, sudo=False, sudo_user=None, su_user=None, print_output=False, ): ''' Upload file-ios to the specified host using SFTP. Supports uploading files with sudo by uploading to a temporary directory then moving & chowning. ''' # sudo/su are a little more complicated, as you can only sftp with the SSH # user connected, so upload to tmp and copy/chown w/sudo and/or su_user if sudo or su_user: # Get temp file location temp_file = state.get_temp_filename(remote_filename) _put_file(host, filename_or_io, temp_file) if print_output: print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename)) # Execute run_shell_command w/sudo and/or su_user command = 'mv {0} {1}'.format(temp_file, remote_filename) # Move it to the su_user if present if su_user: command = '{0} && chown {1} {2}'.format(command, su_user, remote_filename) # Otherwise any sudo_user elif sudo_user: command = '{0} && chown {1} {2}'.format(command, sudo_user, remote_filename) status, _, stderr = run_shell_command( state, host, command, sudo=sudo, sudo_user=sudo_user, su_user=su_user, print_output=print_output, ) if status is False: logger.error('File error: {0}'.format('\n'.join(stderr))) return False # No sudo and no su_user, so just upload it! else: _put_file(host, filename_or_io, remote_filename) if print_output: print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename)) return True
python
def put_file( state, host, filename_or_io, remote_filename, sudo=False, sudo_user=None, su_user=None, print_output=False, ): ''' Upload file-ios to the specified host using SFTP. Supports uploading files with sudo by uploading to a temporary directory then moving & chowning. ''' # sudo/su are a little more complicated, as you can only sftp with the SSH # user connected, so upload to tmp and copy/chown w/sudo and/or su_user if sudo or su_user: # Get temp file location temp_file = state.get_temp_filename(remote_filename) _put_file(host, filename_or_io, temp_file) if print_output: print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename)) # Execute run_shell_command w/sudo and/or su_user command = 'mv {0} {1}'.format(temp_file, remote_filename) # Move it to the su_user if present if su_user: command = '{0} && chown {1} {2}'.format(command, su_user, remote_filename) # Otherwise any sudo_user elif sudo_user: command = '{0} && chown {1} {2}'.format(command, sudo_user, remote_filename) status, _, stderr = run_shell_command( state, host, command, sudo=sudo, sudo_user=sudo_user, su_user=su_user, print_output=print_output, ) if status is False: logger.error('File error: {0}'.format('\n'.join(stderr))) return False # No sudo and no su_user, so just upload it! else: _put_file(host, filename_or_io, remote_filename) if print_output: print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename)) return True
[ "def", "put_file", "(", "state", ",", "host", ",", "filename_or_io", ",", "remote_filename", ",", "sudo", "=", "False", ",", "sudo_user", "=", "None", ",", "su_user", "=", "None", ",", "print_output", "=", "False", ",", ")", ":", "# sudo/su are a little more...
Upload file-ios to the specified host using SFTP. Supports uploading files with sudo by uploading to a temporary directory then moving & chowning.
[ "Upload", "file", "-", "ios", "to", "the", "specified", "host", "using", "SFTP", ".", "Supports", "uploading", "files", "with", "sudo", "by", "uploading", "to", "a", "temporary", "directory", "then", "moving", "&", "chowning", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/ssh.py#L331-L378
24,323
Fizzadar/pyinfra
pyinfra/api/state.py
State.deploy
def deploy(self, name, kwargs, data, line_number, in_deploy=True): ''' Wraps a group of operations as a deploy, this should not be used directly, instead use ``pyinfra.api.deploy.deploy``. ''' # Handle nested deploy names if self.deploy_name: name = _make_name(self.deploy_name, name) # Store the previous values old_in_deploy = self.in_deploy old_deploy_name = self.deploy_name old_deploy_kwargs = self.deploy_kwargs old_deploy_data = self.deploy_data old_deploy_line_numbers = self.deploy_line_numbers self.in_deploy = in_deploy # Limit the new hosts to a subset of the old hosts if they existed if ( old_deploy_kwargs and old_deploy_kwargs.get('hosts') is not None ): # If we have hosts - subset them based on the old hosts if 'hosts' in kwargs: kwargs['hosts'] = [ host for host in kwargs['hosts'] if host in old_deploy_kwargs['hosts'] ] # Otherwise simply carry the previous hosts else: kwargs['hosts'] = old_deploy_kwargs['hosts'] # Make new line numbers - note convert from and back to tuple to avoid # keeping deploy_line_numbers mutable. new_line_numbers = list(self.deploy_line_numbers or []) new_line_numbers.append(line_number) new_line_numbers = tuple(new_line_numbers) # Set the new values self.deploy_name = name self.deploy_kwargs = kwargs self.deploy_data = data self.deploy_line_numbers = new_line_numbers logger.debug('Starting deploy {0} (args={1}, data={2})'.format( name, kwargs, data, )) yield # Restore the previous values self.in_deploy = old_in_deploy self.deploy_name = old_deploy_name self.deploy_kwargs = old_deploy_kwargs self.deploy_data = old_deploy_data self.deploy_line_numbers = old_deploy_line_numbers logger.debug('Reset deploy to {0} (args={1}, data={2})'.format( old_deploy_name, old_deploy_kwargs, old_deploy_data, ))
python
def deploy(self, name, kwargs, data, line_number, in_deploy=True): ''' Wraps a group of operations as a deploy, this should not be used directly, instead use ``pyinfra.api.deploy.deploy``. ''' # Handle nested deploy names if self.deploy_name: name = _make_name(self.deploy_name, name) # Store the previous values old_in_deploy = self.in_deploy old_deploy_name = self.deploy_name old_deploy_kwargs = self.deploy_kwargs old_deploy_data = self.deploy_data old_deploy_line_numbers = self.deploy_line_numbers self.in_deploy = in_deploy # Limit the new hosts to a subset of the old hosts if they existed if ( old_deploy_kwargs and old_deploy_kwargs.get('hosts') is not None ): # If we have hosts - subset them based on the old hosts if 'hosts' in kwargs: kwargs['hosts'] = [ host for host in kwargs['hosts'] if host in old_deploy_kwargs['hosts'] ] # Otherwise simply carry the previous hosts else: kwargs['hosts'] = old_deploy_kwargs['hosts'] # Make new line numbers - note convert from and back to tuple to avoid # keeping deploy_line_numbers mutable. new_line_numbers = list(self.deploy_line_numbers or []) new_line_numbers.append(line_number) new_line_numbers = tuple(new_line_numbers) # Set the new values self.deploy_name = name self.deploy_kwargs = kwargs self.deploy_data = data self.deploy_line_numbers = new_line_numbers logger.debug('Starting deploy {0} (args={1}, data={2})'.format( name, kwargs, data, )) yield # Restore the previous values self.in_deploy = old_in_deploy self.deploy_name = old_deploy_name self.deploy_kwargs = old_deploy_kwargs self.deploy_data = old_deploy_data self.deploy_line_numbers = old_deploy_line_numbers logger.debug('Reset deploy to {0} (args={1}, data={2})'.format( old_deploy_name, old_deploy_kwargs, old_deploy_data, ))
[ "def", "deploy", "(", "self", ",", "name", ",", "kwargs", ",", "data", ",", "line_number", ",", "in_deploy", "=", "True", ")", ":", "# Handle nested deploy names", "if", "self", ".", "deploy_name", ":", "name", "=", "_make_name", "(", "self", ".", "deploy_...
Wraps a group of operations as a deploy, this should not be used directly, instead use ``pyinfra.api.deploy.deploy``.
[ "Wraps", "a", "group", "of", "operations", "as", "a", "deploy", "this", "should", "not", "be", "used", "directly", "instead", "use", "pyinfra", ".", "api", ".", "deploy", ".", "deploy", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L275-L334
24,324
Fizzadar/pyinfra
pyinfra/api/state.py
State.activate_host
def activate_host(self, host): ''' Flag a host as active. ''' logger.debug('Activating host: {0}'.format(host)) # Add to *both* activated and active - active will reduce as hosts fail # but connected will not, enabling us to track failed %. self.activated_hosts.add(host) self.active_hosts.add(host)
python
def activate_host(self, host): ''' Flag a host as active. ''' logger.debug('Activating host: {0}'.format(host)) # Add to *both* activated and active - active will reduce as hosts fail # but connected will not, enabling us to track failed %. self.activated_hosts.add(host) self.active_hosts.add(host)
[ "def", "activate_host", "(", "self", ",", "host", ")", ":", "logger", ".", "debug", "(", "'Activating host: {0}'", ".", "format", "(", "host", ")", ")", "# Add to *both* activated and active - active will reduce as hosts fail", "# but connected will not, enabling us to track ...
Flag a host as active.
[ "Flag", "a", "host", "as", "active", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L345-L355
24,325
Fizzadar/pyinfra
pyinfra/api/state.py
State.fail_hosts
def fail_hosts(self, hosts_to_fail, activated_count=None): ''' Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``. ''' if not hosts_to_fail: return activated_count = activated_count or len(self.activated_hosts) logger.debug('Failing hosts: {0}'.format(', '.join( (host.name for host in hosts_to_fail), ))) # Remove the failed hosts from the inventory self.active_hosts -= hosts_to_fail # Check we're not above the fail percent active_hosts = self.active_hosts # No hosts left! if not active_hosts: raise PyinfraError('No hosts remaining!') if self.config.FAIL_PERCENT is not None: percent_failed = ( 1 - len(active_hosts) / activated_count ) * 100 if percent_failed > self.config.FAIL_PERCENT: raise PyinfraError('Over {0}% of hosts failed ({1}%)'.format( self.config.FAIL_PERCENT, int(round(percent_failed)), ))
python
def fail_hosts(self, hosts_to_fail, activated_count=None): ''' Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``. ''' if not hosts_to_fail: return activated_count = activated_count or len(self.activated_hosts) logger.debug('Failing hosts: {0}'.format(', '.join( (host.name for host in hosts_to_fail), ))) # Remove the failed hosts from the inventory self.active_hosts -= hosts_to_fail # Check we're not above the fail percent active_hosts = self.active_hosts # No hosts left! if not active_hosts: raise PyinfraError('No hosts remaining!') if self.config.FAIL_PERCENT is not None: percent_failed = ( 1 - len(active_hosts) / activated_count ) * 100 if percent_failed > self.config.FAIL_PERCENT: raise PyinfraError('Over {0}% of hosts failed ({1}%)'.format( self.config.FAIL_PERCENT, int(round(percent_failed)), ))
[ "def", "fail_hosts", "(", "self", ",", "hosts_to_fail", ",", "activated_count", "=", "None", ")", ":", "if", "not", "hosts_to_fail", ":", "return", "activated_count", "=", "activated_count", "or", "len", "(", "self", ".", "activated_hosts", ")", "logger", ".",...
Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``.
[ "Flag", "a", "set", "of", "hosts", "as", "failed", "error", "for", "config", ".", "FAIL_PERCENT", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L365-L398
24,326
Fizzadar/pyinfra
pyinfra/api/state.py
State.is_host_in_limit
def is_host_in_limit(self, host): ''' Returns a boolean indicating if the host is within the current state limit. ''' limit_hosts = self.limit_hosts if not isinstance(limit_hosts, list): return True return host in limit_hosts
python
def is_host_in_limit(self, host): ''' Returns a boolean indicating if the host is within the current state limit. ''' limit_hosts = self.limit_hosts if not isinstance(limit_hosts, list): return True return host in limit_hosts
[ "def", "is_host_in_limit", "(", "self", ",", "host", ")", ":", "limit_hosts", "=", "self", ".", "limit_hosts", "if", "not", "isinstance", "(", "limit_hosts", ",", "list", ")", ":", "return", "True", "return", "host", "in", "limit_hosts" ]
Returns a boolean indicating if the host is within the current state limit.
[ "Returns", "a", "boolean", "indicating", "if", "the", "host", "is", "within", "the", "current", "state", "limit", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L400-L409
24,327
Fizzadar/pyinfra
pyinfra/api/state.py
State.get_temp_filename
def get_temp_filename(self, hash_key=None): ''' Generate a temporary filename for this deploy. ''' if not hash_key: hash_key = six.text_type(uuid4()) temp_filename = '{0}/{1}'.format( self.config.TEMP_DIR, sha1_hash(hash_key), ) return temp_filename
python
def get_temp_filename(self, hash_key=None): ''' Generate a temporary filename for this deploy. ''' if not hash_key: hash_key = six.text_type(uuid4()) temp_filename = '{0}/{1}'.format( self.config.TEMP_DIR, sha1_hash(hash_key), ) return temp_filename
[ "def", "get_temp_filename", "(", "self", ",", "hash_key", "=", "None", ")", ":", "if", "not", "hash_key", ":", "hash_key", "=", "six", ".", "text_type", "(", "uuid4", "(", ")", ")", "temp_filename", "=", "'{0}/{1}'", ".", "format", "(", "self", ".", "c...
Generate a temporary filename for this deploy.
[ "Generate", "a", "temporary", "filename", "for", "this", "deploy", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L411-L423
24,328
Fizzadar/pyinfra
pyinfra/api/operations.py
_run_server_ops
def _run_server_ops(state, host, progress=None): ''' Run all ops for a single server. ''' logger.debug('Running all ops on {0}'.format(host)) for op_hash in state.get_op_order(): op_meta = state.op_meta[op_hash] logger.info('--> {0} {1} on {2}'.format( click.style('--> Starting operation:', 'blue'), click.style(', '.join(op_meta['names']), bold=True), click.style(host.name, bold=True), )) result = _run_server_op(state, host, op_hash) # Trigger CLI progress if provided if progress: progress((host, op_hash)) if result is False: raise PyinfraError('Error in operation {0} on {1}'.format( ', '.join(op_meta['names']), host, )) if pyinfra.is_cli: print()
python
def _run_server_ops(state, host, progress=None): ''' Run all ops for a single server. ''' logger.debug('Running all ops on {0}'.format(host)) for op_hash in state.get_op_order(): op_meta = state.op_meta[op_hash] logger.info('--> {0} {1} on {2}'.format( click.style('--> Starting operation:', 'blue'), click.style(', '.join(op_meta['names']), bold=True), click.style(host.name, bold=True), )) result = _run_server_op(state, host, op_hash) # Trigger CLI progress if provided if progress: progress((host, op_hash)) if result is False: raise PyinfraError('Error in operation {0} on {1}'.format( ', '.join(op_meta['names']), host, )) if pyinfra.is_cli: print()
[ "def", "_run_server_ops", "(", "state", ",", "host", ",", "progress", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Running all ops on {0}'", ".", "format", "(", "host", ")", ")", "for", "op_hash", "in", "state", ".", "get_op_order", "(", ")", ":...
Run all ops for a single server.
[ "Run", "all", "ops", "for", "a", "single", "server", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operations.py#L216-L244
24,329
Fizzadar/pyinfra
pyinfra/api/operations.py
_run_serial_ops
def _run_serial_ops(state): ''' Run all ops for all servers, one server at a time. ''' for host in list(state.inventory): host_operations = product([host], state.get_op_order()) with progress_spinner(host_operations) as progress: try: _run_server_ops( state, host, progress=progress, ) except PyinfraError: state.fail_hosts({host})
python
def _run_serial_ops(state): ''' Run all ops for all servers, one server at a time. ''' for host in list(state.inventory): host_operations = product([host], state.get_op_order()) with progress_spinner(host_operations) as progress: try: _run_server_ops( state, host, progress=progress, ) except PyinfraError: state.fail_hosts({host})
[ "def", "_run_serial_ops", "(", "state", ")", ":", "for", "host", "in", "list", "(", "state", ".", "inventory", ")", ":", "host_operations", "=", "product", "(", "[", "host", "]", ",", "state", ".", "get_op_order", "(", ")", ")", "with", "progress_spinner...
Run all ops for all servers, one server at a time.
[ "Run", "all", "ops", "for", "all", "servers", "one", "server", "at", "a", "time", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operations.py#L247-L261
24,330
Fizzadar/pyinfra
pyinfra/api/operations.py
_run_no_wait_ops
def _run_no_wait_ops(state): ''' Run all ops for all servers at once. ''' hosts_operations = product(state.inventory, state.get_op_order()) with progress_spinner(hosts_operations) as progress: # Spawn greenlet for each host to run *all* ops greenlets = [ state.pool.spawn( _run_server_ops, state, host, progress=progress, ) for host in state.inventory ] gevent.joinall(greenlets)
python
def _run_no_wait_ops(state): ''' Run all ops for all servers at once. ''' hosts_operations = product(state.inventory, state.get_op_order()) with progress_spinner(hosts_operations) as progress: # Spawn greenlet for each host to run *all* ops greenlets = [ state.pool.spawn( _run_server_ops, state, host, progress=progress, ) for host in state.inventory ] gevent.joinall(greenlets)
[ "def", "_run_no_wait_ops", "(", "state", ")", ":", "hosts_operations", "=", "product", "(", "state", ".", "inventory", ",", "state", ".", "get_op_order", "(", ")", ")", "with", "progress_spinner", "(", "hosts_operations", ")", "as", "progress", ":", "# Spawn g...
Run all ops for all servers at once.
[ "Run", "all", "ops", "for", "all", "servers", "at", "once", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operations.py#L264-L279
24,331
Fizzadar/pyinfra
pyinfra/api/operations.py
_run_single_op
def _run_single_op(state, op_hash): ''' Run a single operation for all servers. Can be configured to run in serial. ''' op_meta = state.op_meta[op_hash] op_types = [] if op_meta['serial']: op_types.append('serial') if op_meta['run_once']: op_types.append('run once') logger.info('{0} {1} {2}'.format( click.style('--> Starting{0}operation:'.format( ' {0} '.format(', '.join(op_types)) if op_types else ' ', ), 'blue'), click.style(', '.join(op_meta['names']), bold=True), tuple(op_meta['args']) if op_meta['args'] else '', )) failed_hosts = set() if op_meta['serial']: with progress_spinner(state.inventory) as progress: # For each host, run the op for host in state.inventory: result = _run_server_op(state, host, op_hash) progress(host) if not result: failed_hosts.add(host) else: # Start with the whole inventory in one batch batches = [state.inventory] # If parallel set break up the inventory into a series of batches if op_meta['parallel']: parallel = op_meta['parallel'] hosts = list(state.inventory) batches = [ hosts[i:i + parallel] for i in range(0, len(hosts), parallel) ] for batch in batches: with progress_spinner(batch) as progress: # Spawn greenlet for each host greenlet_to_host = { state.pool.spawn(_run_server_op, state, host, op_hash): host for host in batch } # Trigger CLI progress as hosts complete if provided for greenlet in gevent.iwait(greenlet_to_host.keys()): host = greenlet_to_host[greenlet] progress(host) # Get all the results for greenlet, host in six.iteritems(greenlet_to_host): if not greenlet.get(): failed_hosts.add(host) # Now all the batches/hosts are complete, fail any failures if not op_meta['ignore_errors']: state.fail_hosts(failed_hosts) if pyinfra.is_cli: print()
python
def _run_single_op(state, op_hash): ''' Run a single operation for all servers. Can be configured to run in serial. ''' op_meta = state.op_meta[op_hash] op_types = [] if op_meta['serial']: op_types.append('serial') if op_meta['run_once']: op_types.append('run once') logger.info('{0} {1} {2}'.format( click.style('--> Starting{0}operation:'.format( ' {0} '.format(', '.join(op_types)) if op_types else ' ', ), 'blue'), click.style(', '.join(op_meta['names']), bold=True), tuple(op_meta['args']) if op_meta['args'] else '', )) failed_hosts = set() if op_meta['serial']: with progress_spinner(state.inventory) as progress: # For each host, run the op for host in state.inventory: result = _run_server_op(state, host, op_hash) progress(host) if not result: failed_hosts.add(host) else: # Start with the whole inventory in one batch batches = [state.inventory] # If parallel set break up the inventory into a series of batches if op_meta['parallel']: parallel = op_meta['parallel'] hosts = list(state.inventory) batches = [ hosts[i:i + parallel] for i in range(0, len(hosts), parallel) ] for batch in batches: with progress_spinner(batch) as progress: # Spawn greenlet for each host greenlet_to_host = { state.pool.spawn(_run_server_op, state, host, op_hash): host for host in batch } # Trigger CLI progress as hosts complete if provided for greenlet in gevent.iwait(greenlet_to_host.keys()): host = greenlet_to_host[greenlet] progress(host) # Get all the results for greenlet, host in six.iteritems(greenlet_to_host): if not greenlet.get(): failed_hosts.add(host) # Now all the batches/hosts are complete, fail any failures if not op_meta['ignore_errors']: state.fail_hosts(failed_hosts) if pyinfra.is_cli: print()
[ "def", "_run_single_op", "(", "state", ",", "op_hash", ")", ":", "op_meta", "=", "state", ".", "op_meta", "[", "op_hash", "]", "op_types", "=", "[", "]", "if", "op_meta", "[", "'serial'", "]", ":", "op_types", ".", "append", "(", "'serial'", ")", "if",...
Run a single operation for all servers. Can be configured to run in serial.
[ "Run", "a", "single", "operation", "for", "all", "servers", ".", "Can", "be", "configured", "to", "run", "in", "serial", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operations.py#L282-L354
24,332
Fizzadar/pyinfra
pyinfra/api/operations.py
run_ops
def run_ops(state, serial=False, no_wait=False): ''' Runs all operations across all servers in a configurable manner. Args: state (``pyinfra.api.State`` obj): the deploy state to execute serial (boolean): whether to run operations host by host no_wait (boolean): whether to wait for all hosts between operations ''' # Flag state as deploy in process state.deploying = True # Run all ops, but server by server if serial: _run_serial_ops(state) # Run all the ops on each server in parallel (not waiting at each operation) elif no_wait: _run_no_wait_ops(state) # Default: run all ops in order, waiting at each for all servers to complete for op_hash in state.get_op_order(): _run_single_op(state, op_hash)
python
def run_ops(state, serial=False, no_wait=False): ''' Runs all operations across all servers in a configurable manner. Args: state (``pyinfra.api.State`` obj): the deploy state to execute serial (boolean): whether to run operations host by host no_wait (boolean): whether to wait for all hosts between operations ''' # Flag state as deploy in process state.deploying = True # Run all ops, but server by server if serial: _run_serial_ops(state) # Run all the ops on each server in parallel (not waiting at each operation) elif no_wait: _run_no_wait_ops(state) # Default: run all ops in order, waiting at each for all servers to complete for op_hash in state.get_op_order(): _run_single_op(state, op_hash)
[ "def", "run_ops", "(", "state", ",", "serial", "=", "False", ",", "no_wait", "=", "False", ")", ":", "# Flag state as deploy in process", "state", ".", "deploying", "=", "True", "# Run all ops, but server by server", "if", "serial", ":", "_run_serial_ops", "(", "s...
Runs all operations across all servers in a configurable manner. Args: state (``pyinfra.api.State`` obj): the deploy state to execute serial (boolean): whether to run operations host by host no_wait (boolean): whether to wait for all hosts between operations
[ "Runs", "all", "operations", "across", "all", "servers", "in", "a", "configurable", "manner", "." ]
006f751f7db2e07d32522c0285160783de2feb79
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operations.py#L357-L380
24,333
eruvanos/openbrokerapi
openbrokerapi/api.py
serve
def serve(service_brokers: Union[List[ServiceBroker], ServiceBroker], credentials: Union[List[BrokerCredentials], BrokerCredentials, None], logger: logging.Logger = logging.root, port=5000, debug=False): """ Starts flask with the given brokers. You can provide a list or just one ServiceBroker :param service_brokers: ServicesBroker for services to provide :param credentials: Username and password that will be required to communicate with service broker :param logger: Used for api logs. This will not influence Flasks logging behavior :param port: Port :param debug: Enables debugging in flask app """ from gevent.pywsgi import WSGIServer from flask import Flask app = Flask(__name__) app.debug = debug blueprint = get_blueprint(service_brokers, credentials, logger) logger.debug("Register openbrokerapi blueprint") app.register_blueprint(blueprint) logger.info("Start Flask on 0.0.0.0:%s" % port) http_server = WSGIServer(('0.0.0.0', port), app) http_server.serve_forever()
python
def serve(service_brokers: Union[List[ServiceBroker], ServiceBroker], credentials: Union[List[BrokerCredentials], BrokerCredentials, None], logger: logging.Logger = logging.root, port=5000, debug=False): from gevent.pywsgi import WSGIServer from flask import Flask app = Flask(__name__) app.debug = debug blueprint = get_blueprint(service_brokers, credentials, logger) logger.debug("Register openbrokerapi blueprint") app.register_blueprint(blueprint) logger.info("Start Flask on 0.0.0.0:%s" % port) http_server = WSGIServer(('0.0.0.0', port), app) http_server.serve_forever()
[ "def", "serve", "(", "service_brokers", ":", "Union", "[", "List", "[", "ServiceBroker", "]", ",", "ServiceBroker", "]", ",", "credentials", ":", "Union", "[", "List", "[", "BrokerCredentials", "]", ",", "BrokerCredentials", ",", "None", "]", ",", "logger", ...
Starts flask with the given brokers. You can provide a list or just one ServiceBroker :param service_brokers: ServicesBroker for services to provide :param credentials: Username and password that will be required to communicate with service broker :param logger: Used for api logs. This will not influence Flasks logging behavior :param port: Port :param debug: Enables debugging in flask app
[ "Starts", "flask", "with", "the", "given", "brokers", ".", "You", "can", "provide", "a", "list", "or", "just", "one", "ServiceBroker" ]
29d514e5932f2eac27e03995dd41c8cecf40bb10
https://github.com/eruvanos/openbrokerapi/blob/29d514e5932f2eac27e03995dd41c8cecf40bb10/openbrokerapi/api.py#L320-L348
24,334
romana/multi-ping
multiping/__init__.py
multi_ping
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False): """ Combine send and receive measurement into single function. This offers a retry mechanism: Overall timeout time is divided by number of retries. Additional ICMPecho packets are sent to those addresses from which we have not received answers, yet. The retry mechanism is useful, because individual ICMP packets may get lost. If 'retry' is set to 0 then only a single packet is sent to each address. If 'ignore_lookup_errors' is set then any issues with resolving target names or looking up their address information will silently be ignored. Those targets simply appear in the 'no_results' return list. """ retry = int(retry) if retry < 0: retry = 0 timeout = float(timeout) if timeout < 0.1: raise MultiPingError("Timeout < 0.1 seconds not allowed") retry_timeout = float(timeout) / (retry + 1) if retry_timeout < 0.1: raise MultiPingError("Time between ping retries < 0.1 seconds") mp = MultiPing(dest_addrs, ignore_lookup_errors=ignore_lookup_errors) results = {} retry_count = 0 while retry_count <= retry: # Send a batch of pings mp.send() single_results, no_results = mp.receive(retry_timeout) # Add the results from the last sending of pings to the overall results results.update(single_results) if not no_results: # No addresses left? We are done. break retry_count += 1 return results, no_results
python
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False): retry = int(retry) if retry < 0: retry = 0 timeout = float(timeout) if timeout < 0.1: raise MultiPingError("Timeout < 0.1 seconds not allowed") retry_timeout = float(timeout) / (retry + 1) if retry_timeout < 0.1: raise MultiPingError("Time between ping retries < 0.1 seconds") mp = MultiPing(dest_addrs, ignore_lookup_errors=ignore_lookup_errors) results = {} retry_count = 0 while retry_count <= retry: # Send a batch of pings mp.send() single_results, no_results = mp.receive(retry_timeout) # Add the results from the last sending of pings to the overall results results.update(single_results) if not no_results: # No addresses left? We are done. break retry_count += 1 return results, no_results
[ "def", "multi_ping", "(", "dest_addrs", ",", "timeout", ",", "retry", "=", "0", ",", "ignore_lookup_errors", "=", "False", ")", ":", "retry", "=", "int", "(", "retry", ")", "if", "retry", "<", "0", ":", "retry", "=", "0", "timeout", "=", "float", "("...
Combine send and receive measurement into single function. This offers a retry mechanism: Overall timeout time is divided by number of retries. Additional ICMPecho packets are sent to those addresses from which we have not received answers, yet. The retry mechanism is useful, because individual ICMP packets may get lost. If 'retry' is set to 0 then only a single packet is sent to each address. If 'ignore_lookup_errors' is set then any issues with resolving target names or looking up their address information will silently be ignored. Those targets simply appear in the 'no_results' return list.
[ "Combine", "send", "and", "receive", "measurement", "into", "single", "function", "." ]
59f024c867a17fae5b4a7b52f97effc6fb1b0ca5
https://github.com/romana/multi-ping/blob/59f024c867a17fae5b4a7b52f97effc6fb1b0ca5/multiping/__init__.py#L460-L506
24,335
romana/multi-ping
multiping/__init__.py
MultiPing._checksum
def _checksum(self, msg): """ Calculate the checksum of a packet. This is inspired by a response on StackOverflow here: https://stackoverflow.com/a/1769267/7242672 Thank you to StackOverflow user Jason Orendorff. """ def carry_around_add(a, b): c = a + b return (c & 0xffff) + (c >> 16) s = 0 for i in range(0, len(msg), 2): w = (msg[i] << 8) + msg[i + 1] s = carry_around_add(s, w) s = ~s & 0xffff return s
python
def _checksum(self, msg): def carry_around_add(a, b): c = a + b return (c & 0xffff) + (c >> 16) s = 0 for i in range(0, len(msg), 2): w = (msg[i] << 8) + msg[i + 1] s = carry_around_add(s, w) s = ~s & 0xffff return s
[ "def", "_checksum", "(", "self", ",", "msg", ")", ":", "def", "carry_around_add", "(", "a", ",", "b", ")", ":", "c", "=", "a", "+", "b", "return", "(", "c", "&", "0xffff", ")", "+", "(", "c", ">>", "16", ")", "s", "=", "0", "for", "i", "in"...
Calculate the checksum of a packet. This is inspired by a response on StackOverflow here: https://stackoverflow.com/a/1769267/7242672 Thank you to StackOverflow user Jason Orendorff.
[ "Calculate", "the", "checksum", "of", "a", "packet", "." ]
59f024c867a17fae5b4a7b52f97effc6fb1b0ca5
https://github.com/romana/multi-ping/blob/59f024c867a17fae5b4a7b52f97effc6fb1b0ca5/multiping/__init__.py#L187-L207
24,336
romana/multi-ping
multiping/__init__.py
MultiPing.send
def send(self): """ Send pings to multiple addresses, ensuring unique IDs for each request. This operation is non-blocking. Use 'receive' to get the results. Send can be called multiple times. If there are any addresses left from the previous send, from which results have not been received yet, then it will resend pings to those remaining addresses. """ # Collect all the addresses for which we have not seen responses yet. if not self._receive_has_been_called: all_addrs = self._dest_addrs else: all_addrs = [a for (i, a) in list(self._id_to_addr.items()) if i in self._remaining_ids] if self._last_used_id is None: # Will attempt to continue at the last request ID we used. But if # we never sent anything before then we create a first ID # 'randomly' from the current time. ID is only a 16 bit field, so # need to trim it down. self._last_used_id = int(time.time()) & 0xffff # Send ICMPecho to all addresses... for addr in all_addrs: # Make a unique ID, wrapping around at 65535. self._last_used_id = (self._last_used_id + 1) & 0xffff # Remember the address for each ID so we can produce meaningful # result lists later on. self._id_to_addr[self._last_used_id] = addr # Send an ICMPecho request packet. We specify a payload consisting # of the current time stamp. This is returned to us in the # response and allows us to calculate the 'ping time'. self._send_ping(addr, payload=struct.pack("d", time.time()))
python
def send(self): # Collect all the addresses for which we have not seen responses yet. if not self._receive_has_been_called: all_addrs = self._dest_addrs else: all_addrs = [a for (i, a) in list(self._id_to_addr.items()) if i in self._remaining_ids] if self._last_used_id is None: # Will attempt to continue at the last request ID we used. But if # we never sent anything before then we create a first ID # 'randomly' from the current time. ID is only a 16 bit field, so # need to trim it down. self._last_used_id = int(time.time()) & 0xffff # Send ICMPecho to all addresses... for addr in all_addrs: # Make a unique ID, wrapping around at 65535. self._last_used_id = (self._last_used_id + 1) & 0xffff # Remember the address for each ID so we can produce meaningful # result lists later on. self._id_to_addr[self._last_used_id] = addr # Send an ICMPecho request packet. We specify a payload consisting # of the current time stamp. This is returned to us in the # response and allows us to calculate the 'ping time'. self._send_ping(addr, payload=struct.pack("d", time.time()))
[ "def", "send", "(", "self", ")", ":", "# Collect all the addresses for which we have not seen responses yet.", "if", "not", "self", ".", "_receive_has_been_called", ":", "all_addrs", "=", "self", ".", "_dest_addrs", "else", ":", "all_addrs", "=", "[", "a", "for", "(...
Send pings to multiple addresses, ensuring unique IDs for each request. This operation is non-blocking. Use 'receive' to get the results. Send can be called multiple times. If there are any addresses left from the previous send, from which results have not been received yet, then it will resend pings to those remaining addresses.
[ "Send", "pings", "to", "multiple", "addresses", "ensuring", "unique", "IDs", "for", "each", "request", "." ]
59f024c867a17fae5b4a7b52f97effc6fb1b0ca5
https://github.com/romana/multi-ping/blob/59f024c867a17fae5b4a7b52f97effc6fb1b0ca5/multiping/__init__.py#L268-L303
24,337
romana/multi-ping
multiping/__init__.py
MultiPing._read_all_from_socket
def _read_all_from_socket(self, timeout): """ Read all packets we currently can on the socket. Returns list of tuples. Each tuple contains a packet and the time at which it was received. NOTE: The receive time is the time when our recv() call returned, which greatly depends on when it was called. The time is NOT the time at which the packet arrived at our host, but it's the closest we can come to the real ping time. If nothing was received within the timeout time, the return list is empty. First read is blocking with timeout, so we'll wait at least that long. Then, in case any more packets have arrived, we read everything we can from the socket in non-blocking mode. """ pkts = [] try: self._sock.settimeout(timeout) while True: p = self._sock.recv(64) # Store the packet and the current time pkts.append((bytearray(p), time.time())) # Continue the loop to receive any additional packets that # may have arrived at this point. Changing the socket to # non-blocking (by setting the timeout to 0), so that we'll # only continue the loop until all current packets have been # read. self._sock.settimeout(0) except socket.timeout: # In the first blocking read with timout, we may not receive # anything. This is not an error, it just means no data was # available in the specified time. pass except socket.error as e: # When we read in non-blocking mode, we may get this error with # errno 11 to indicate that no more data is available. That's ok, # just like the timeout. if e.errno == errno.EWOULDBLOCK: pass else: # We're not expecting any other socket exceptions, so we # re-raise in that case. raise if self._ipv6_address_present: try: self._sock6.settimeout(timeout) while True: p = self._sock6.recv(128) pkts.append((bytearray(p), time.time())) self._sock6.settimeout(0) except socket.timeout: pass except socket.error as e: if e.errno == errno.EWOULDBLOCK: pass else: raise return pkts
python
def _read_all_from_socket(self, timeout): pkts = [] try: self._sock.settimeout(timeout) while True: p = self._sock.recv(64) # Store the packet and the current time pkts.append((bytearray(p), time.time())) # Continue the loop to receive any additional packets that # may have arrived at this point. Changing the socket to # non-blocking (by setting the timeout to 0), so that we'll # only continue the loop until all current packets have been # read. self._sock.settimeout(0) except socket.timeout: # In the first blocking read with timout, we may not receive # anything. This is not an error, it just means no data was # available in the specified time. pass except socket.error as e: # When we read in non-blocking mode, we may get this error with # errno 11 to indicate that no more data is available. That's ok, # just like the timeout. if e.errno == errno.EWOULDBLOCK: pass else: # We're not expecting any other socket exceptions, so we # re-raise in that case. raise if self._ipv6_address_present: try: self._sock6.settimeout(timeout) while True: p = self._sock6.recv(128) pkts.append((bytearray(p), time.time())) self._sock6.settimeout(0) except socket.timeout: pass except socket.error as e: if e.errno == errno.EWOULDBLOCK: pass else: raise return pkts
[ "def", "_read_all_from_socket", "(", "self", ",", "timeout", ")", ":", "pkts", "=", "[", "]", "try", ":", "self", ".", "_sock", ".", "settimeout", "(", "timeout", ")", "while", "True", ":", "p", "=", "self", ".", "_sock", ".", "recv", "(", "64", ")...
Read all packets we currently can on the socket. Returns list of tuples. Each tuple contains a packet and the time at which it was received. NOTE: The receive time is the time when our recv() call returned, which greatly depends on when it was called. The time is NOT the time at which the packet arrived at our host, but it's the closest we can come to the real ping time. If nothing was received within the timeout time, the return list is empty. First read is blocking with timeout, so we'll wait at least that long. Then, in case any more packets have arrived, we read everything we can from the socket in non-blocking mode.
[ "Read", "all", "packets", "we", "currently", "can", "on", "the", "socket", "." ]
59f024c867a17fae5b4a7b52f97effc6fb1b0ca5
https://github.com/romana/multi-ping/blob/59f024c867a17fae5b4a7b52f97effc6fb1b0ca5/multiping/__init__.py#L305-L367
24,338
numat/midas
midas/driver.py
GasDetector.get
async def get(self): """Get current state from the Midas gas detector.""" try: return self._parse(await self.read_registers(0, 16)) except TimeoutError: return {'ip': self.ip, 'connected': False}
python
async def get(self): try: return self._parse(await self.read_registers(0, 16)) except TimeoutError: return {'ip': self.ip, 'connected': False}
[ "async", "def", "get", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_parse", "(", "await", "self", ".", "read_registers", "(", "0", ",", "16", ")", ")", "except", "TimeoutError", ":", "return", "{", "'ip'", ":", "self", ".", "ip", ","...
Get current state from the Midas gas detector.
[ "Get", "current", "state", "from", "the", "Midas", "gas", "detector", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/driver.py#L65-L70
24,339
numat/midas
midas/driver.py
GasDetector._parse
def _parse(self, registers): """Parse the response, returning a dictionary.""" result = {'ip': self.ip, 'connected': True} decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=Endian.Big, wordorder=Endian.Little) # Register 40001 is a collection of alarm status signals b = [decoder.decode_bits(), decoder.decode_bits()] reg_40001 = b[1] + b[0] # Bits 0-3 map to the monitor state monitor_integer = sum(1 << i for i, b in enumerate(reg_40001[:4]) if b) result['state'] = options['monitor state'][monitor_integer] # Bits 4-5 map to fault status fault_integer = sum(1 << i for i, b in enumerate(reg_40001[4:6]) if b) result['fault'] = {'status': options['fault status'][fault_integer]} # Bits 6 and 7 tell if low and high alarms are active low, high = reg_40001[6:8] result['alarm'] = options['alarm level'][low + high] # Bits 8-10 tell if internal sensor relays 1-3 are energized. Skipping. # Bit 11 is a heartbeat bit that toggles every two seconds. Skipping. # Bit 12 tells if relays are under modbus control. Skipping. # Remaining bits are empty. Skipping. # Register 40002 has a gas ID and a sensor cartridge ID. Skipping. decoder._pointer += 2 # Registers 40003-40004 are the gas concentration as a float result['concentration'] = decoder.decode_32bit_float() # Register 40005 is the concentration as an int. Skipping. decoder._pointer += 2 # Register 40006 is the number of the most important fault. fault_number = decoder.decode_16bit_uint() if fault_number != 0: code = ('m' if fault_number < 30 else 'F') + str(fault_number) result['fault']['code'] = code result['fault'].update(faults[code]) # Register 40007 holds the concentration unit in the second byte # Instead of being an int, it's the position of the up bit unit_bit = decoder.decode_bits().index(True) result['units'] = options['concentration unit'][unit_bit] decoder._pointer += 1 # Register 40008 holds the sensor temperature in Celsius result['temperature'] = decoder.decode_16bit_int() # Register 40009 holds number of hours remaining in cell life result['life'] = decoder.decode_16bit_uint() / 24.0 # Register 40010 holds the number of heartbeats (16 LSB). Skipping. decoder._pointer += 2 # Register 40011 is the sample flow rate in cc / min result['flow'] = decoder.decode_16bit_uint() # Register 40012 is blank. Skipping. decoder._pointer += 2 # Registers 40013-40016 are the alarm concentration thresholds result['low-alarm threshold'] = round(decoder.decode_32bit_float(), 6) result['high-alarm threshold'] = round(decoder.decode_32bit_float(), 6) # Despite what the manual says, thresholds are always reported in ppm. # Let's fix that to match the concentration units. if result['units'] == 'ppb': result['concentration'] *= 1000 result['low-alarm threshold'] *= 1000 result['high-alarm threshold'] *= 1000 return result
python
def _parse(self, registers): result = {'ip': self.ip, 'connected': True} decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=Endian.Big, wordorder=Endian.Little) # Register 40001 is a collection of alarm status signals b = [decoder.decode_bits(), decoder.decode_bits()] reg_40001 = b[1] + b[0] # Bits 0-3 map to the monitor state monitor_integer = sum(1 << i for i, b in enumerate(reg_40001[:4]) if b) result['state'] = options['monitor state'][monitor_integer] # Bits 4-5 map to fault status fault_integer = sum(1 << i for i, b in enumerate(reg_40001[4:6]) if b) result['fault'] = {'status': options['fault status'][fault_integer]} # Bits 6 and 7 tell if low and high alarms are active low, high = reg_40001[6:8] result['alarm'] = options['alarm level'][low + high] # Bits 8-10 tell if internal sensor relays 1-3 are energized. Skipping. # Bit 11 is a heartbeat bit that toggles every two seconds. Skipping. # Bit 12 tells if relays are under modbus control. Skipping. # Remaining bits are empty. Skipping. # Register 40002 has a gas ID and a sensor cartridge ID. Skipping. decoder._pointer += 2 # Registers 40003-40004 are the gas concentration as a float result['concentration'] = decoder.decode_32bit_float() # Register 40005 is the concentration as an int. Skipping. decoder._pointer += 2 # Register 40006 is the number of the most important fault. fault_number = decoder.decode_16bit_uint() if fault_number != 0: code = ('m' if fault_number < 30 else 'F') + str(fault_number) result['fault']['code'] = code result['fault'].update(faults[code]) # Register 40007 holds the concentration unit in the second byte # Instead of being an int, it's the position of the up bit unit_bit = decoder.decode_bits().index(True) result['units'] = options['concentration unit'][unit_bit] decoder._pointer += 1 # Register 40008 holds the sensor temperature in Celsius result['temperature'] = decoder.decode_16bit_int() # Register 40009 holds number of hours remaining in cell life result['life'] = decoder.decode_16bit_uint() / 24.0 # Register 40010 holds the number of heartbeats (16 LSB). Skipping. decoder._pointer += 2 # Register 40011 is the sample flow rate in cc / min result['flow'] = decoder.decode_16bit_uint() # Register 40012 is blank. Skipping. decoder._pointer += 2 # Registers 40013-40016 are the alarm concentration thresholds result['low-alarm threshold'] = round(decoder.decode_32bit_float(), 6) result['high-alarm threshold'] = round(decoder.decode_32bit_float(), 6) # Despite what the manual says, thresholds are always reported in ppm. # Let's fix that to match the concentration units. if result['units'] == 'ppb': result['concentration'] *= 1000 result['low-alarm threshold'] *= 1000 result['high-alarm threshold'] *= 1000 return result
[ "def", "_parse", "(", "self", ",", "registers", ")", ":", "result", "=", "{", "'ip'", ":", "self", ".", "ip", ",", "'connected'", ":", "True", "}", "decoder", "=", "BinaryPayloadDecoder", ".", "fromRegisters", "(", "registers", ",", "byteorder", "=", "En...
Parse the response, returning a dictionary.
[ "Parse", "the", "response", "returning", "a", "dictionary", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/driver.py#L72-L130
24,340
numat/midas
midas/util.py
AsyncioModbusClient._connect
async def _connect(self): """Start asynchronous reconnect loop.""" self.waiting = True await self.client.start(self.ip) self.waiting = False if self.client.protocol is None: raise IOError("Could not connect to '{}'.".format(self.ip)) self.open = True
python
async def _connect(self): self.waiting = True await self.client.start(self.ip) self.waiting = False if self.client.protocol is None: raise IOError("Could not connect to '{}'.".format(self.ip)) self.open = True
[ "async", "def", "_connect", "(", "self", ")", ":", "self", ".", "waiting", "=", "True", "await", "self", ".", "client", ".", "start", "(", "self", ".", "ip", ")", "self", ".", "waiting", "=", "False", "if", "self", ".", "client", ".", "protocol", "...
Start asynchronous reconnect loop.
[ "Start", "asynchronous", "reconnect", "loop", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L36-L43
24,341
numat/midas
midas/util.py
AsyncioModbusClient.read_registers
async def read_registers(self, address, count): """Read modbus registers. The Modbus protocol doesn't allow responses longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ registers = [] while count > 124: r = await self._request('read_holding_registers', address, 124) registers += r.registers address, count = address + 124, count - 124 r = await self._request('read_holding_registers', address, count) registers += r.registers return registers
python
async def read_registers(self, address, count): registers = [] while count > 124: r = await self._request('read_holding_registers', address, 124) registers += r.registers address, count = address + 124, count - 124 r = await self._request('read_holding_registers', address, count) registers += r.registers return registers
[ "async", "def", "read_registers", "(", "self", ",", "address", ",", "count", ")", ":", "registers", "=", "[", "]", "while", "count", ">", "124", ":", "r", "=", "await", "self", ".", "_request", "(", "'read_holding_registers'", ",", "address", ",", "124",...
Read modbus registers. The Modbus protocol doesn't allow responses longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests.
[ "Read", "modbus", "registers", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L49-L63
24,342
numat/midas
midas/util.py
AsyncioModbusClient.write_register
async def write_register(self, address, value, skip_encode=False): """Write a modbus register.""" await self._request('write_registers', address, value, skip_encode=skip_encode)
python
async def write_register(self, address, value, skip_encode=False): await self._request('write_registers', address, value, skip_encode=skip_encode)
[ "async", "def", "write_register", "(", "self", ",", "address", ",", "value", ",", "skip_encode", "=", "False", ")", ":", "await", "self", ".", "_request", "(", "'write_registers'", ",", "address", ",", "value", ",", "skip_encode", "=", "skip_encode", ")" ]
Write a modbus register.
[ "Write", "a", "modbus", "register", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L73-L75
24,343
numat/midas
midas/util.py
AsyncioModbusClient.write_registers
async def write_registers(self, address, values, skip_encode=False): """Write modbus registers. The Modbus protocol doesn't allow requests longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ while len(values) > 62: await self._request('write_registers', address, values, skip_encode=skip_encode) address, values = address + 124, values[62:] await self._request('write_registers', address, values, skip_encode=skip_encode)
python
async def write_registers(self, address, values, skip_encode=False): while len(values) > 62: await self._request('write_registers', address, values, skip_encode=skip_encode) address, values = address + 124, values[62:] await self._request('write_registers', address, values, skip_encode=skip_encode)
[ "async", "def", "write_registers", "(", "self", ",", "address", ",", "values", ",", "skip_encode", "=", "False", ")", ":", "while", "len", "(", "values", ")", ">", "62", ":", "await", "self", ".", "_request", "(", "'write_registers'", ",", "address", ","...
Write modbus registers. The Modbus protocol doesn't allow requests longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests.
[ "Write", "modbus", "registers", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L77-L89
24,344
numat/midas
midas/util.py
AsyncioModbusClient._request
async def _request(self, method, *args, **kwargs): """Send a request to the device and awaits a response. This mainly ensures that requests are sent serially, as the Modbus protocol does not allow simultaneous requests (it'll ignore any request sent while it's processing something). The driver handles this by assuming there is only one client instance. If other clients exist, other logic will have to be added to either prevent or manage race conditions. """ if not self.open: await self._connect() while self.waiting: await asyncio.sleep(0.1) if self.client.protocol is None or not self.client.protocol.connected: raise TimeoutError("Not connected to device.") try: future = getattr(self.client.protocol, method)(*args, **kwargs) except AttributeError: raise TimeoutError("Not connected to device.") self.waiting = True try: return await asyncio.wait_for(future, timeout=self.timeout) except asyncio.TimeoutError as e: if self.open: # This came from reading through the pymodbus@python3 source # Problem was that the driver was not detecting disconnect if hasattr(self, 'modbus'): self.client.protocol_lost_connection(self.modbus) self.open = False raise TimeoutError(e) except pymodbus.exceptions.ConnectionException as e: raise ConnectionError(e) finally: self.waiting = False
python
async def _request(self, method, *args, **kwargs): if not self.open: await self._connect() while self.waiting: await asyncio.sleep(0.1) if self.client.protocol is None or not self.client.protocol.connected: raise TimeoutError("Not connected to device.") try: future = getattr(self.client.protocol, method)(*args, **kwargs) except AttributeError: raise TimeoutError("Not connected to device.") self.waiting = True try: return await asyncio.wait_for(future, timeout=self.timeout) except asyncio.TimeoutError as e: if self.open: # This came from reading through the pymodbus@python3 source # Problem was that the driver was not detecting disconnect if hasattr(self, 'modbus'): self.client.protocol_lost_connection(self.modbus) self.open = False raise TimeoutError(e) except pymodbus.exceptions.ConnectionException as e: raise ConnectionError(e) finally: self.waiting = False
[ "async", "def", "_request", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "open", ":", "await", "self", ".", "_connect", "(", ")", "while", "self", ".", "waiting", ":", "await", "asyncio"...
Send a request to the device and awaits a response. This mainly ensures that requests are sent serially, as the Modbus protocol does not allow simultaneous requests (it'll ignore any request sent while it's processing something). The driver handles this by assuming there is only one client instance. If other clients exist, other logic will have to be added to either prevent or manage race conditions.
[ "Send", "a", "request", "to", "the", "device", "and", "awaits", "a", "response", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L91-L125
24,345
numat/midas
midas/util.py
AsyncioModbusClient._close
def _close(self): """Close the TCP connection.""" self.client.stop() self.open = False self.waiting = False
python
def _close(self): self.client.stop() self.open = False self.waiting = False
[ "def", "_close", "(", "self", ")", ":", "self", ".", "client", ".", "stop", "(", ")", "self", ".", "open", "=", "False", "self", ".", "waiting", "=", "False" ]
Close the TCP connection.
[ "Close", "the", "TCP", "connection", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L127-L131
24,346
numat/midas
midas/__init__.py
command_line
def command_line(): """Command-line tool for Midas gas detector communication.""" import argparse import asyncio import json parser = argparse.ArgumentParser(description="Read a Honeywell Midas gas " "detector state from the command line.") parser.add_argument('address', help="The IP address of the gas detector.") args = parser.parse_args() async def get(): async with GasDetector(args.address) as detector: print(json.dumps(await detector.get(), indent=4, sort_keys=True)) loop = asyncio.get_event_loop() loop.run_until_complete(get()) loop.close()
python
def command_line(): import argparse import asyncio import json parser = argparse.ArgumentParser(description="Read a Honeywell Midas gas " "detector state from the command line.") parser.add_argument('address', help="The IP address of the gas detector.") args = parser.parse_args() async def get(): async with GasDetector(args.address) as detector: print(json.dumps(await detector.get(), indent=4, sort_keys=True)) loop = asyncio.get_event_loop() loop.run_until_complete(get()) loop.close()
[ "def", "command_line", "(", ")", ":", "import", "argparse", "import", "asyncio", "import", "json", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Read a Honeywell Midas gas \"", "\"detector state from the command line.\"", ")", "parser", "...
Command-line tool for Midas gas detector communication.
[ "Command", "-", "line", "tool", "for", "Midas", "gas", "detector", "communication", "." ]
c3a97a6cd67df1283831c3c78bf3f984212e97a8
https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/__init__.py#L11-L28
24,347
bioinf-jku/FCD
build/lib/fcd/FCD.py
build_masked_loss
def build_masked_loss(loss_function, mask_value): """Builds a loss function that masks based on targets Args: loss_function: The loss function to mask mask_value: The value to mask in the targets Returns: function: a loss function that acts like loss_function with masked inputs """ def masked_loss_function(y_true, y_pred): mask = K.cast(K.not_equal(y_true, mask_value), K.floatx()) return loss_function(y_true * mask, y_pred * mask) return masked_loss_function
python
def build_masked_loss(loss_function, mask_value): def masked_loss_function(y_true, y_pred): mask = K.cast(K.not_equal(y_true, mask_value), K.floatx()) return loss_function(y_true * mask, y_pred * mask) return masked_loss_function
[ "def", "build_masked_loss", "(", "loss_function", ",", "mask_value", ")", ":", "def", "masked_loss_function", "(", "y_true", ",", "y_pred", ")", ":", "mask", "=", "K", ".", "cast", "(", "K", ".", "not_equal", "(", "y_true", ",", "mask_value", ")", ",", "...
Builds a loss function that masks based on targets Args: loss_function: The loss function to mask mask_value: The value to mask in the targets Returns: function: a loss function that acts like loss_function with masked inputs
[ "Builds", "a", "loss", "function", "that", "masks", "based", "on", "targets" ]
fe542b16d72a2d0899989374e1a86cc930d891e1
https://github.com/bioinf-jku/FCD/blob/fe542b16d72a2d0899989374e1a86cc930d891e1/build/lib/fcd/FCD.py#L88-L103
24,348
google/python-gflags
gflags2man.py
ProgramInfo.Run
def Run(self): """Run it and collect output. Returns: 1 (true) If everything went well. 0 (false) If there were problems. """ if not self.executable: logging.error('Could not locate "%s"' % self.long_name) return 0 finfo = os.stat(self.executable) self.date = time.localtime(finfo[stat.ST_MTIME]) logging.info('Running: %s %s </dev/null 2>&1' % (self.executable, FLAGS.help_flag)) # --help output is often routed to stderr, so we combine with stdout. # Re-direct stdin to /dev/null to encourage programs that # don't understand --help to exit. (child_stdin, child_stdout_and_stderr) = os.popen4( [self.executable, FLAGS.help_flag]) child_stdin.close() # '</dev/null' self.output = child_stdout_and_stderr.readlines() child_stdout_and_stderr.close() if len(self.output) < _MIN_VALID_USAGE_MSG: logging.error('Error: "%s %s" returned only %d lines: %s' % (self.name, FLAGS.help_flag, len(self.output), self.output)) return 0 return 1
python
def Run(self): if not self.executable: logging.error('Could not locate "%s"' % self.long_name) return 0 finfo = os.stat(self.executable) self.date = time.localtime(finfo[stat.ST_MTIME]) logging.info('Running: %s %s </dev/null 2>&1' % (self.executable, FLAGS.help_flag)) # --help output is often routed to stderr, so we combine with stdout. # Re-direct stdin to /dev/null to encourage programs that # don't understand --help to exit. (child_stdin, child_stdout_and_stderr) = os.popen4( [self.executable, FLAGS.help_flag]) child_stdin.close() # '</dev/null' self.output = child_stdout_and_stderr.readlines() child_stdout_and_stderr.close() if len(self.output) < _MIN_VALID_USAGE_MSG: logging.error('Error: "%s %s" returned only %d lines: %s' % (self.name, FLAGS.help_flag, len(self.output), self.output)) return 0 return 1
[ "def", "Run", "(", "self", ")", ":", "if", "not", "self", ".", "executable", ":", "logging", ".", "error", "(", "'Could not locate \"%s\"'", "%", "self", ".", "long_name", ")", "return", "0", "finfo", "=", "os", ".", "stat", "(", "self", ".", "executab...
Run it and collect output. Returns: 1 (true) If everything went well. 0 (false) If there were problems.
[ "Run", "it", "and", "collect", "output", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L185-L214
24,349
google/python-gflags
gflags2man.py
ProgramInfo.Parse
def Parse(self): """Parse program output.""" (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line)
python
def Parse(self): (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line)
[ "def", "Parse", "(", "self", ")", ":", "(", "start_line", ",", "lang", ")", "=", "self", ".", "ParseDesc", "(", ")", "if", "start_line", "<", "0", ":", "return", "if", "'python'", "==", "lang", ":", "self", ".", "ParsePythonFlags", "(", "start_line", ...
Parse program output.
[ "Parse", "program", "output", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L216-L226
24,350
google/python-gflags
gflags2man.py
ProgramInfo.ParseDesc
def ParseDesc(self, start_line=0): """Parse the initial description. This could be Python or C++. Returns: (start_line, lang_type) start_line Line to start parsing flags on (int) lang_type Either 'python' or 'c' (-1, '') if the flags start could not be found """ exec_mod_start = self.executable + ':' after_blank = 0 start_line = 0 # ignore the passed-in arg for now (?) for start_line in range(start_line, len(self.output)): # collect top description line = self.output[start_line].rstrip() # Python flags start with 'flags:\n' if ('flags:' == line and len(self.output) > start_line+1 and '' == self.output[start_line+1].rstrip()): start_line += 2 logging.debug('Flags start (python): %s' % line) return (start_line, 'python') # SWIG flags just have the module name followed by colon. if exec_mod_start == line: logging.debug('Flags start (swig): %s' % line) return (start_line, 'python') # C++ flags begin after a blank line and with a constant string if after_blank and line.startswith(' Flags from '): logging.debug('Flags start (c): %s' % line) return (start_line, 'c') # java flags begin with a constant string if line == 'where flags are': logging.debug('Flags start (java): %s' % line) start_line += 2 # skip "Standard flags:" return (start_line, 'java') logging.debug('Desc: %s' % line) self.desc.append(line) after_blank = (line == '') else: logging.warn('Never found the start of the flags section for "%s"!' % self.long_name) return (-1, '')
python
def ParseDesc(self, start_line=0): exec_mod_start = self.executable + ':' after_blank = 0 start_line = 0 # ignore the passed-in arg for now (?) for start_line in range(start_line, len(self.output)): # collect top description line = self.output[start_line].rstrip() # Python flags start with 'flags:\n' if ('flags:' == line and len(self.output) > start_line+1 and '' == self.output[start_line+1].rstrip()): start_line += 2 logging.debug('Flags start (python): %s' % line) return (start_line, 'python') # SWIG flags just have the module name followed by colon. if exec_mod_start == line: logging.debug('Flags start (swig): %s' % line) return (start_line, 'python') # C++ flags begin after a blank line and with a constant string if after_blank and line.startswith(' Flags from '): logging.debug('Flags start (c): %s' % line) return (start_line, 'c') # java flags begin with a constant string if line == 'where flags are': logging.debug('Flags start (java): %s' % line) start_line += 2 # skip "Standard flags:" return (start_line, 'java') logging.debug('Desc: %s' % line) self.desc.append(line) after_blank = (line == '') else: logging.warn('Never found the start of the flags section for "%s"!' % self.long_name) return (-1, '')
[ "def", "ParseDesc", "(", "self", ",", "start_line", "=", "0", ")", ":", "exec_mod_start", "=", "self", ".", "executable", "+", "':'", "after_blank", "=", "0", "start_line", "=", "0", "# ignore the passed-in arg for now (?)", "for", "start_line", "in", "range", ...
Parse the initial description. This could be Python or C++. Returns: (start_line, lang_type) start_line Line to start parsing flags on (int) lang_type Either 'python' or 'c' (-1, '') if the flags start could not be found
[ "Parse", "the", "initial", "description", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L228-L272
24,351
google/python-gflags
gflags2man.py
ProgramInfo.ParseCFlags
def ParseCFlags(self, start_line=0): """Parse C style flags.""" modname = None # name of current module modlist = [] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() if not line: # blank lines terminate flags if flag: # save last flag modlist.append(flag) flag = None continue mobj = self.module_c_re.match(line) if mobj: # start of a new module modname = mobj.group(1) logging.debug('Module: %s' % line) if flag: modlist.append(flag) self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None continue mobj = self.flag_c_re.match(line) if mobj: # start of a new flag if flag: # save last flag modlist.append(flag) logging.debug('Flag: %s' % line) flag = Flag(mobj.group(1), mobj.group(2)) continue # append to flag help. type and default are part of the main text if flag: flag.help += ' ' + line.strip() else: logging.info('Extra: %s' % line) if flag: modlist.append(flag)
python
def ParseCFlags(self, start_line=0): modname = None # name of current module modlist = [] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() if not line: # blank lines terminate flags if flag: # save last flag modlist.append(flag) flag = None continue mobj = self.module_c_re.match(line) if mobj: # start of a new module modname = mobj.group(1) logging.debug('Module: %s' % line) if flag: modlist.append(flag) self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None continue mobj = self.flag_c_re.match(line) if mobj: # start of a new flag if flag: # save last flag modlist.append(flag) logging.debug('Flag: %s' % line) flag = Flag(mobj.group(1), mobj.group(2)) continue # append to flag help. type and default are part of the main text if flag: flag.help += ' ' + line.strip() else: logging.info('Extra: %s' % line) if flag: modlist.append(flag)
[ "def", "ParseCFlags", "(", "self", ",", "start_line", "=", "0", ")", ":", "modname", "=", "None", "# name of current module", "modlist", "=", "[", "]", "flag", "=", "None", "for", "line_num", "in", "range", "(", "start_line", ",", "len", "(", "self", "."...
Parse C style flags.
[ "Parse", "C", "style", "flags", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L323-L362
24,352
google/python-gflags
gflags2man.py
ProgramInfo.Filter
def Filter(self): """Filter parsed data to create derived fields.""" if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self.name) self.short_desc = self.desc[0] word_list = self.short_desc.split(' ') all_names = [ self.name, self.short_name, ] # Since the short_desc is always listed right after the name, # trim it from the short_desc while word_list and (word_list[0] in all_names or word_list[0].lower() in all_names): del word_list[0] self.short_desc = '' # signal need to reconstruct if not self.short_desc and word_list: self.short_desc = ' '.join(word_list)
python
def Filter(self): if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self.name) self.short_desc = self.desc[0] word_list = self.short_desc.split(' ') all_names = [ self.name, self.short_name, ] # Since the short_desc is always listed right after the name, # trim it from the short_desc while word_list and (word_list[0] in all_names or word_list[0].lower() in all_names): del word_list[0] self.short_desc = '' # signal need to reconstruct if not self.short_desc and word_list: self.short_desc = ' '.join(word_list)
[ "def", "Filter", "(", "self", ")", ":", "if", "not", "self", ".", "desc", ":", "self", ".", "short_desc", "=", "''", "return", "for", "i", "in", "range", "(", "len", "(", "self", ".", "desc", ")", ")", ":", "# replace full path with name", "if", "sel...
Filter parsed data to create derived fields.
[ "Filter", "parsed", "data", "to", "create", "derived", "fields", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L411-L431
24,353
google/python-gflags
gflags2man.py
GenerateDoc.Output
def Output(self): """Output all sections of the page.""" self.Open() self.Header() self.Body() self.Footer()
python
def Output(self): self.Open() self.Header() self.Body() self.Footer()
[ "def", "Output", "(", "self", ")", ":", "self", ".", "Open", "(", ")", "self", ".", "Header", "(", ")", "self", ".", "Body", "(", ")", "self", ".", "Footer", "(", ")" ]
Output all sections of the page.
[ "Output", "all", "sections", "of", "the", "page", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L446-L451
24,354
google/python-gflags
gflags/_helpers.py
GetFlagSuggestions
def GetFlagSuggestions(attempt, longopt_list): """Get helpful similar matches for an invalid flag.""" # Don't suggest on very short strings, or if no longopts are specified. if len(attempt) <= 2 or not longopt_list: return [] option_names = [v.split('=')[0] for v in longopt_list] # Find close approximations in flag prefixes. # This also handles the case where the flag is spelled right but ambiguous. distances = [(_DamerauLevenshtein(attempt, option[0:len(attempt)]), option) for option in option_names] distances.sort(key=lambda t: t[0]) least_errors, _ = distances[0] # Don't suggest excessively bad matches. if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt): return [] suggestions = [] for errors, name in distances: if errors == least_errors: suggestions.append(name) else: break return suggestions
python
def GetFlagSuggestions(attempt, longopt_list): # Don't suggest on very short strings, or if no longopts are specified. if len(attempt) <= 2 or not longopt_list: return [] option_names = [v.split('=')[0] for v in longopt_list] # Find close approximations in flag prefixes. # This also handles the case where the flag is spelled right but ambiguous. distances = [(_DamerauLevenshtein(attempt, option[0:len(attempt)]), option) for option in option_names] distances.sort(key=lambda t: t[0]) least_errors, _ = distances[0] # Don't suggest excessively bad matches. if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt): return [] suggestions = [] for errors, name in distances: if errors == least_errors: suggestions.append(name) else: break return suggestions
[ "def", "GetFlagSuggestions", "(", "attempt", ",", "longopt_list", ")", ":", "# Don't suggest on very short strings, or if no longopts are specified.", "if", "len", "(", "attempt", ")", "<=", "2", "or", "not", "longopt_list", ":", "return", "[", "]", "option_names", "=...
Get helpful similar matches for an invalid flag.
[ "Get", "helpful", "similar", "matches", "for", "an", "invalid", "flag", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/_helpers.py#L216-L241
24,355
google/python-gflags
gflags/_helpers.py
_DamerauLevenshtein
def _DamerauLevenshtein(a, b): """Damerau-Levenshtein edit distance from a to b.""" memo = {} def Distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min( Distance(x[1:], y) + 1, # correct an insertion error Distance(x, y[1:]) + 1, # correct a deletion error Distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]: # Correct a transposition. t = Distance(x[2:], y[2:]) + 1 if d > t: d = t memo[x, y] = d return d return Distance(a, b)
python
def _DamerauLevenshtein(a, b): memo = {} def Distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min( Distance(x[1:], y) + 1, # correct an insertion error Distance(x, y[1:]) + 1, # correct a deletion error Distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]: # Correct a transposition. t = Distance(x[2:], y[2:]) + 1 if d > t: d = t memo[x, y] = d return d return Distance(a, b)
[ "def", "_DamerauLevenshtein", "(", "a", ",", "b", ")", ":", "memo", "=", "{", "}", "def", "Distance", "(", "x", ",", "y", ")", ":", "\"\"\"Recursively defined string distance with memoization.\"\"\"", "if", "(", "x", ",", "y", ")", "in", "memo", ":", "retu...
Damerau-Levenshtein edit distance from a to b.
[ "Damerau", "-", "Levenshtein", "edit", "distance", "from", "a", "to", "b", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/_helpers.py#L244-L269
24,356
google/python-gflags
gflags/_helpers.py
FlagDictToArgs
def FlagDictToArgs(flag_map): """Convert a dict of values into process call parameters. This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module. Args: flag_map: a mapping where the keys are flag names (strings). values are treated according to their type: * If value is None, then only the name is emitted. * If value is True, then only the name is emitted. * If value is False, then only the name prepended with 'no' is emitted. * If value is a string then --name=value is emitted. * If value is a collection, this will emit --name=value1,value2,value3. * Everything else is converted to string an passed as such. Yields: sequence of string suitable for a subprocess execution. """ for key, value in six.iteritems(flag_map): if value is None: yield '--%s' % key elif isinstance(value, bool): if value: yield '--%s' % key else: yield '--no%s' % key elif isinstance(value, (bytes, type(u''))): # We don't want strings to be handled like python collections. yield '--%s=%s' % (key, value) else: # Now we attempt to deal with collections. try: yield '--%s=%s' % (key, ','.join(str(item) for item in value)) except TypeError: # Default case. yield '--%s=%s' % (key, value)
python
def FlagDictToArgs(flag_map): for key, value in six.iteritems(flag_map): if value is None: yield '--%s' % key elif isinstance(value, bool): if value: yield '--%s' % key else: yield '--no%s' % key elif isinstance(value, (bytes, type(u''))): # We don't want strings to be handled like python collections. yield '--%s=%s' % (key, value) else: # Now we attempt to deal with collections. try: yield '--%s=%s' % (key, ','.join(str(item) for item in value)) except TypeError: # Default case. yield '--%s=%s' % (key, value)
[ "def", "FlagDictToArgs", "(", "flag_map", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "flag_map", ")", ":", "if", "value", "is", "None", ":", "yield", "'--%s'", "%", "key", "elif", "isinstance", "(", "value", ",", "bool", ...
Convert a dict of values into process call parameters. This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module. Args: flag_map: a mapping where the keys are flag names (strings). values are treated according to their type: * If value is None, then only the name is emitted. * If value is True, then only the name is emitted. * If value is False, then only the name prepended with 'no' is emitted. * If value is a string then --name=value is emitted. * If value is a collection, this will emit --name=value1,value2,value3. * Everything else is converted to string an passed as such. Yields: sequence of string suitable for a subprocess execution.
[ "Convert", "a", "dict", "of", "values", "into", "process", "call", "parameters", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/_helpers.py#L329-L364
24,357
google/python-gflags
gflags/_helpers.py
define_both_methods
def define_both_methods(class_name, class_dict, old_name, new_name): # pylint: disable=invalid-name """Function to help CamelCase to PEP8 style class methods migration. For any class definition: 1. Assert it does not define both old and new methods, otherwise it does not work. 2. If it defines the old method, create the same new method. 3. If it defines the new method, create the same old method. Args: class_name: the class name. class_dict: the class dictionary. old_name: old method's name. new_name: new method's name. Raises: AssertionError: raised when the class defines both the old_name and new_name. """ assert old_name not in class_dict or new_name not in class_dict, ( 'Class "{}" cannot define both "{}" and "{}" methods.'.format( class_name, old_name, new_name)) if old_name in class_dict: class_dict[new_name] = class_dict[old_name] elif new_name in class_dict: class_dict[old_name] = class_dict[new_name]
python
def define_both_methods(class_name, class_dict, old_name, new_name): # pylint: disable=invalid-name assert old_name not in class_dict or new_name not in class_dict, ( 'Class "{}" cannot define both "{}" and "{}" methods.'.format( class_name, old_name, new_name)) if old_name in class_dict: class_dict[new_name] = class_dict[old_name] elif new_name in class_dict: class_dict[old_name] = class_dict[new_name]
[ "def", "define_both_methods", "(", "class_name", ",", "class_dict", ",", "old_name", ",", "new_name", ")", ":", "# pylint: disable=invalid-name", "assert", "old_name", "not", "in", "class_dict", "or", "new_name", "not", "in", "class_dict", ",", "(", "'Class \"{}\" c...
Function to help CamelCase to PEP8 style class methods migration. For any class definition: 1. Assert it does not define both old and new methods, otherwise it does not work. 2. If it defines the old method, create the same new method. 3. If it defines the new method, create the same old method. Args: class_name: the class name. class_dict: the class dictionary. old_name: old method's name. new_name: new method's name. Raises: AssertionError: raised when the class defines both the old_name and new_name.
[ "Function", "to", "help", "CamelCase", "to", "PEP8", "style", "class", "methods", "migration", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/_helpers.py#L405-L430
24,358
google/python-gflags
gflags/flagvalues.py
FlagValues._IsUnparsedFlagAccessAllowed
def _IsUnparsedFlagAccessAllowed(self, name): """Determine whether to allow unparsed flag access or not.""" if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ: # We've been told explicitly what to do. allow_unparsed_flag_access = ( os.getenv(_UNPARSED_FLAG_ACCESS_ENV_NAME) == '1') elif self.__dict__['__reset_called']: # Raise exception if .Reset() was called. This mostly happens in tests. allow_unparsed_flag_access = False elif _helpers.IsRunningTest(): # Staged "rollout", based on name of the flag so that we don't break # everyone. Hashing the flag is a way of choosing a random but # consistent subset of flags to lock down which we can make larger # over time. name_bytes = name.encode('utf8') if not isinstance(name, bytes) else name flag_percentile = ( struct.unpack('<I', hashlib.md5(name_bytes).digest()[:4])[0] % 100) allow_unparsed_flag_access = ( _UNPARSED_ACCESS_DISABLED_PERCENT <= flag_percentile) else: allow_unparsed_flag_access = True return allow_unparsed_flag_access
python
def _IsUnparsedFlagAccessAllowed(self, name): if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ: # We've been told explicitly what to do. allow_unparsed_flag_access = ( os.getenv(_UNPARSED_FLAG_ACCESS_ENV_NAME) == '1') elif self.__dict__['__reset_called']: # Raise exception if .Reset() was called. This mostly happens in tests. allow_unparsed_flag_access = False elif _helpers.IsRunningTest(): # Staged "rollout", based on name of the flag so that we don't break # everyone. Hashing the flag is a way of choosing a random but # consistent subset of flags to lock down which we can make larger # over time. name_bytes = name.encode('utf8') if not isinstance(name, bytes) else name flag_percentile = ( struct.unpack('<I', hashlib.md5(name_bytes).digest()[:4])[0] % 100) allow_unparsed_flag_access = ( _UNPARSED_ACCESS_DISABLED_PERCENT <= flag_percentile) else: allow_unparsed_flag_access = True return allow_unparsed_flag_access
[ "def", "_IsUnparsedFlagAccessAllowed", "(", "self", ",", "name", ")", ":", "if", "_UNPARSED_FLAG_ACCESS_ENV_NAME", "in", "os", ".", "environ", ":", "# We've been told explicitly what to do.", "allow_unparsed_flag_access", "=", "(", "os", ".", "getenv", "(", "_UNPARSED_F...
Determine whether to allow unparsed flag access or not.
[ "Determine", "whether", "to", "allow", "unparsed", "flag", "access", "or", "not", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L490-L511
24,359
google/python-gflags
gflags/flagvalues.py
FlagValues._AssertValidators
def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValueError: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise exceptions.IllegalFlagValueError('%s: %s' % (message, str(e)))
python
def _AssertValidators(self, validators): for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise exceptions.IllegalFlagValueError('%s: %s' % (message, str(e)))
[ "def", "_AssertValidators", "(", "self", ",", "validators", ")", ":", "for", "validator", "in", "sorted", "(", "validators", ",", "key", "=", "lambda", "validator", ":", "validator", ".", "insertion_index", ")", ":", "try", ":", "validator", ".", "verify", ...
Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValueError: if validation fails for at least one validator
[ "Assert", "if", "all", "validators", "in", "the", "list", "are", "satisfied", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L561-L578
24,360
google/python-gflags
gflags/flagvalues.py
FlagValues._RemoveAllFlagAppearances
def _RemoveAllFlagAppearances(self, name): """Removes flag with name for all appearances. A flag can be registered with its long name and an optional short name. This method removes both of them. This is different than __delattr__. Args: name: Either flag's long name or short name. Raises: UnrecognizedFlagError: When flag name is not found. """ flag_dict = self.FlagDict() if name not in flag_dict: raise exceptions.UnrecognizedFlagError(name) flag = flag_dict[name] names_to_remove = {name} names_to_remove.add(flag.name) if flag.short_name: names_to_remove.add(flag.short_name) for n in names_to_remove: self.__delattr__(n)
python
def _RemoveAllFlagAppearances(self, name): flag_dict = self.FlagDict() if name not in flag_dict: raise exceptions.UnrecognizedFlagError(name) flag = flag_dict[name] names_to_remove = {name} names_to_remove.add(flag.name) if flag.short_name: names_to_remove.add(flag.short_name) for n in names_to_remove: self.__delattr__(n)
[ "def", "_RemoveAllFlagAppearances", "(", "self", ",", "name", ")", ":", "flag_dict", "=", "self", ".", "FlagDict", "(", ")", "if", "name", "not", "in", "flag_dict", ":", "raise", "exceptions", ".", "UnrecognizedFlagError", "(", "name", ")", "flag", "=", "f...
Removes flag with name for all appearances. A flag can be registered with its long name and an optional short name. This method removes both of them. This is different than __delattr__. Args: name: Either flag's long name or short name. Raises: UnrecognizedFlagError: When flag name is not found.
[ "Removes", "flag", "with", "name", "for", "all", "appearances", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L610-L631
24,361
google/python-gflags
gflags/flagvalues.py
FlagValues.GetHelp
def GetHelp(self, prefix='', include_special_flags=True): """Generates a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of _SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message. """ # TODO(vrusinov): this function needs a test. helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = sys.argv[0] if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) if include_special_flags: self.__RenderModuleFlags('gflags', _helpers.SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. values = self.FlagDict().values() if include_special_flags: values.append(_helpers.SPECIAL_FLAGS.FlagDict().values()) self.__RenderFlagList(values, helplist, prefix) return '\n'.join(helplist)
python
def GetHelp(self, prefix='', include_special_flags=True): # TODO(vrusinov): this function needs a test. helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = sys.argv[0] if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) if include_special_flags: self.__RenderModuleFlags('gflags', _helpers.SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. values = self.FlagDict().values() if include_special_flags: values.append(_helpers.SPECIAL_FLAGS.FlagDict().values()) self.__RenderFlagList(values, helplist, prefix) return '\n'.join(helplist)
[ "def", "GetHelp", "(", "self", ",", "prefix", "=", "''", ",", "include_special_flags", "=", "True", ")", ":", "# TODO(vrusinov): this function needs a test.", "helplist", "=", "[", "]", "flags_by_module", "=", "self", ".", "FlagsByModuleDict", "(", ")", "if", "f...
Generates a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of _SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message.
[ "Generates", "a", "help", "string", "for", "all", "known", "flags", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L849-L886
24,362
google/python-gflags
gflags/flagvalues.py
FlagValues.__RenderOurModuleKeyFlags
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
python
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''): key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
[ "def", "__RenderOurModuleKeyFlags", "(", "self", ",", "module", ",", "output_lines", ",", "prefix", "=", "''", ")", ":", "key_flags", "=", "self", ".", "_GetKeyFlagsForModule", "(", "module", ")", "if", "key_flags", ":", "self", ".", "__RenderModuleFlags", "("...
Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line.
[ "Generates", "a", "help", "string", "for", "the", "key", "flags", "of", "a", "given", "module", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L901-L912
24,363
google/python-gflags
gflags/flagvalues.py
FlagValues.ModuleHelp
def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
python
def ModuleHelp(self, module): helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
[ "def", "ModuleHelp", "(", "self", ",", "module", ")", ":", "helplist", "=", "[", "]", "self", ".", "__RenderOurModuleKeyFlags", "(", "module", ",", "helplist", ")", "return", "'\\n'", ".", "join", "(", "helplist", ")" ]
Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module.
[ "Describe", "the", "key", "flags", "of", "a", "module", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L914-L925
24,364
google/python-gflags
gflags/__init__.py
register_multi_flags_validator
def register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=FLAGS): """Adds a constraint to multiple flags. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_names: [str], a list of the flag names to be checked. multi_flags_checker: callable, a function to validate the flag. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags.ValidationError. message: Error text to be shown to the user if checker returns False. If checker raises gflags.ValidationError, message from the raised error will be shown. flag_values: An optional FlagValues instance to validate against. Raises: AttributeError: If a flag is not registered as a valid flag name. """ v = gflags_validators.MultiFlagsValidator( flag_names, multi_flags_checker, message) _add_validator(flag_values, v)
python
def register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=FLAGS): v = gflags_validators.MultiFlagsValidator( flag_names, multi_flags_checker, message) _add_validator(flag_values, v)
[ "def", "register_multi_flags_validator", "(", "flag_names", ",", "multi_flags_checker", ",", "message", "=", "'Flags validation failed'", ",", "flag_values", "=", "FLAGS", ")", ":", "v", "=", "gflags_validators", ".", "MultiFlagsValidator", "(", "flag_names", ",", "mu...
Adds a constraint to multiple flags. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_names: [str], a list of the flag names to be checked. multi_flags_checker: callable, a function to validate the flag. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags.ValidationError. message: Error text to be shown to the user if checker returns False. If checker raises gflags.ValidationError, message from the raised error will be shown. flag_values: An optional FlagValues instance to validate against. Raises: AttributeError: If a flag is not registered as a valid flag name.
[ "Adds", "a", "constraint", "to", "multiple", "flags", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L187-L214
24,365
google/python-gflags
gflags/__init__.py
multi_flags_validator
def multi_flags_validator(flag_names, message='Flag validation failed', flag_values=FLAGS): """A function decorator for defining a multi-flag validator. Registers the decorated function as a validator for flag_names, e.g. @gflags.multi_flags_validator(['foo', 'bar']) def _CheckFooBar(flags_dict): ... See register_multi_flags_validator() for the specification of checker function. Args: flag_names: [str], a list of the flag names to be checked. message: error text to be shown to the user if checker returns False. If checker raises ValidationError, message from the raised error will be shown. flag_values: An optional FlagValues instance to validate against. Returns: A function decorator that registers its function argument as a validator. Raises: AttributeError: If a flag is not registered as a valid flag name. """ def decorate(function): register_multi_flags_validator(flag_names, function, message=message, flag_values=flag_values) return function return decorate
python
def multi_flags_validator(flag_names, message='Flag validation failed', flag_values=FLAGS): def decorate(function): register_multi_flags_validator(flag_names, function, message=message, flag_values=flag_values) return function return decorate
[ "def", "multi_flags_validator", "(", "flag_names", ",", "message", "=", "'Flag validation failed'", ",", "flag_values", "=", "FLAGS", ")", ":", "def", "decorate", "(", "function", ")", ":", "register_multi_flags_validator", "(", "flag_names", ",", "function", ",", ...
A function decorator for defining a multi-flag validator. Registers the decorated function as a validator for flag_names, e.g. @gflags.multi_flags_validator(['foo', 'bar']) def _CheckFooBar(flags_dict): ... See register_multi_flags_validator() for the specification of checker function. Args: flag_names: [str], a list of the flag names to be checked. message: error text to be shown to the user if checker returns False. If checker raises ValidationError, message from the raised error will be shown. flag_values: An optional FlagValues instance to validate against. Returns: A function decorator that registers its function argument as a validator. Raises: AttributeError: If a flag is not registered as a valid flag name.
[ "A", "function", "decorator", "for", "defining", "a", "multi", "-", "flag", "validator", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L217-L252
24,366
google/python-gflags
gflags/__init__.py
mark_flag_as_required
def mark_flag_as_required(flag_name, flag_values=FLAGS): """Ensures that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on. It is recommended to call this method like this: if __name__ == '__main__': gflags.mark_flag_as_required('your_flag_name') app.run() Because validation happens at app.run() we want to ensure required-ness is enforced at that time. However, you generally do not want to force users who import your code to have additional required flags for their own binaries or tests. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ if flag_values[flag_name].default is not None: # TODO(vrusinov): Turn this warning into an exception. warnings.warn( 'Flag %s has a non-None default value; therefore, ' 'mark_flag_as_required will pass even if flag is not specified in the ' 'command line!' % flag_name) register_validator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values)
python
def mark_flag_as_required(flag_name, flag_values=FLAGS): if flag_values[flag_name].default is not None: # TODO(vrusinov): Turn this warning into an exception. warnings.warn( 'Flag %s has a non-None default value; therefore, ' 'mark_flag_as_required will pass even if flag is not specified in the ' 'command line!' % flag_name) register_validator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values)
[ "def", "mark_flag_as_required", "(", "flag_name", ",", "flag_values", "=", "FLAGS", ")", ":", "if", "flag_values", "[", "flag_name", "]", ".", "default", "is", "not", "None", ":", "# TODO(vrusinov): Turn this warning into an exception.", "warnings", ".", "warn", "("...
Ensures that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on. It is recommended to call this method like this: if __name__ == '__main__': gflags.mark_flag_as_required('your_flag_name') app.run() Because validation happens at app.run() we want to ensure required-ness is enforced at that time. However, you generally do not want to force users who import your code to have additional required flags for their own binaries or tests. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name.
[ "Ensures", "that", "flag", "is", "not", "None", "during", "program", "execution", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L255-L288
24,367
google/python-gflags
gflags/__init__.py
mark_flags_as_mutual_exclusive
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): """Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to validate against. """ def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True message = ('%s one of (%s) must be specified.' % ('Exactly' if required else 'At most', ', '.join(flag_names))) raise ValidationError(message) register_multi_flags_validator( flag_names, validate_mutual_exclusion, flag_values=flag_values)
python
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True message = ('%s one of (%s) must be specified.' % ('Exactly' if required else 'At most', ', '.join(flag_names))) raise ValidationError(message) register_multi_flags_validator( flag_names, validate_mutual_exclusion, flag_values=flag_values)
[ "def", "mark_flags_as_mutual_exclusive", "(", "flag_names", ",", "required", "=", "False", ",", "flag_values", "=", "FLAGS", ")", ":", "def", "validate_mutual_exclusion", "(", "flags_dict", ")", ":", "flag_count", "=", "sum", "(", "1", "for", "val", "in", "fla...
Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to validate against.
[ "Ensures", "that", "only", "one", "flag", "among", "flag_names", "is", "set", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L310-L330
24,368
google/python-gflags
gflags/__init__.py
DEFINE_enum
def DEFINE_enum( # pylint: disable=g-bad-name,redefined-builtin name, default, enum_values, help, flag_values=FLAGS, module_name=None, **args): """Registers a flag whose value can be any string from enum_values. Args: name: A string, the flag name. default: The default value of the flag. enum_values: A list of strings with the possible values for the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values, module_name)
python
def DEFINE_enum( # pylint: disable=g-bad-name,redefined-builtin name, default, enum_values, help, flag_values=FLAGS, module_name=None, **args): DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values, module_name)
[ "def", "DEFINE_enum", "(", "# pylint: disable=g-bad-name,redefined-builtin", "name", ",", "default", ",", "enum_values", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "module_name", "=", "None", ",", "*", "*", "args", ")", ":", "DEFINE_flag", "(", "EnumFla...
Registers a flag whose value can be any string from enum_values. Args: name: A string, the flag name. default: The default value of the flag. enum_values: A list of strings with the possible values for the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "any", "string", "from", "enum_values", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L639-L656
24,369
google/python-gflags
gflags/__init__.py
DEFINE_list
def DEFINE_list( # pylint: disable=g-bad-name,redefined-builtin name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings. The flag value is parsed with a CSV parser. Args: name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ parser = ListParser() serializer = CsvListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args)
python
def DEFINE_list( # pylint: disable=g-bad-name,redefined-builtin name, default, help, flag_values=FLAGS, **args): parser = ListParser() serializer = CsvListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args)
[ "def", "DEFINE_list", "(", "# pylint: disable=g-bad-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "ListParser", "(", ")", "serializer", "=", "CsvListSerializer", "(...
Registers a flag whose value is a comma-separated list of strings. The flag value is parsed with a CSV parser. Args: name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "is", "a", "comma", "-", "separated", "list", "of", "strings", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L659-L675
24,370
google/python-gflags
gflags/__init__.py
DEFINE_multi
def DEFINE_multi( # pylint: disable=g-bad-name,redefined-builtin parser, serializer, name, default, help, flag_values=FLAGS, module_name=None, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. Args: parser: ArgumentParser that is used to parse the flag arguments. serializer: ArgumentSerializer that serializes the flag value. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values, module_name)
python
def DEFINE_multi( # pylint: disable=g-bad-name,redefined-builtin parser, serializer, name, default, help, flag_values=FLAGS, module_name=None, **args): DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values, module_name)
[ "def", "DEFINE_multi", "(", "# pylint: disable=g-bad-name,redefined-builtin", "parser", ",", "serializer", ",", "name", ",", "default", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "module_name", "=", "None", ",", "*", "*", "args", ")", ":", "DEFINE_flag"...
Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. Args: parser: ArgumentParser that is used to parse the flag arguments. serializer: ArgumentSerializer that serializes the flag value. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "generic", "MultiFlag", "that", "parses", "its", "args", "with", "a", "given", "parser", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L700-L724
24,371
google/python-gflags
gflags/__init__.py
DEFINE_multi_float
def DEFINE_multi_float( # pylint: disable=g-bad-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. Args: name: A string, the flag name. default: The default value of the flag. help: A help string. lower_bound: float, min values of the flag. upper_bound: float, max values of the flag. flag_values: FlagValues object with which the flag will be registered. **args: Dictionary with extra keyword args that are passed to the Flag __init__. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
python
def DEFINE_multi_float( # pylint: disable=g-bad-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
[ "def", "DEFINE_multi_float", "(", "# pylint: disable=g-bad-name,redefined-builtin", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "parser"...
Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. Args: name: A string, the flag name. default: The default value of the flag. help: A help string. lower_bound: float, min values of the flag. upper_bound: float, max values of the flag. flag_values: FlagValues object with which the flag will be registered. **args: Dictionary with extra keyword args that are passed to the Flag __init__.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "a", "list", "of", "arbitrary", "floats", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L775-L797
24,372
google/python-gflags
gflags/__init__.py
DEFINE_alias
def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name """Defines an alias flag for an existing one. Args: name: A string, name of the alias flag. original_name: A string, name of the original flag. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the module that defines this flag. Raises: gflags.FlagError: UnrecognizedFlagError: if the referenced flag doesn't exist. DuplicateFlagError: if the alias name has been used by some existing flag. """ if original_name not in flag_values: raise UnrecognizedFlagError(original_name) flag = flag_values[original_name] class _Parser(ArgumentParser): """The parser for the alias flag calls the original flag parser.""" def parse(self, argument): flag.parse(argument) return flag.value class _FlagAlias(Flag): """Overrides Flag class so alias value is copy of original flag value.""" @property def value(self): return flag.value @value.setter def value(self, value): flag.value = value help_msg = 'Alias for --%s.' % flag.name # If alias_name has been used, gflags.DuplicatedFlag will be raised. DEFINE_flag(_FlagAlias(_Parser(), flag.serializer, name, flag.default, help_msg, boolean=flag.boolean), flag_values, module_name)
python
def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name if original_name not in flag_values: raise UnrecognizedFlagError(original_name) flag = flag_values[original_name] class _Parser(ArgumentParser): """The parser for the alias flag calls the original flag parser.""" def parse(self, argument): flag.parse(argument) return flag.value class _FlagAlias(Flag): """Overrides Flag class so alias value is copy of original flag value.""" @property def value(self): return flag.value @value.setter def value(self, value): flag.value = value help_msg = 'Alias for --%s.' % flag.name # If alias_name has been used, gflags.DuplicatedFlag will be raised. DEFINE_flag(_FlagAlias(_Parser(), flag.serializer, name, flag.default, help_msg, boolean=flag.boolean), flag_values, module_name)
[ "def", "DEFINE_alias", "(", "name", ",", "original_name", ",", "flag_values", "=", "FLAGS", ",", "module_name", "=", "None", ")", ":", "# pylint: disable=g-bad-name", "if", "original_name", "not", "in", "flag_values", ":", "raise", "UnrecognizedFlagError", "(", "o...
Defines an alias flag for an existing one. Args: name: A string, name of the alias flag. original_name: A string, name of the original flag. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the module that defines this flag. Raises: gflags.FlagError: UnrecognizedFlagError: if the referenced flag doesn't exist. DuplicateFlagError: if the alias name has been used by some existing flag.
[ "Defines", "an", "alias", "flag", "for", "an", "existing", "one", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/__init__.py#L825-L865
24,373
google/python-gflags
gflags/exceptions.py
DuplicateFlagError.from_flag
def from_flag(cls, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. Returns: An instance of DuplicateFlagError. """ first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _helpers.GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') flag_summary = flag_values[flagname].help msg = ("The flag '%s' is defined twice. First from %s, Second from %s. " "Description from first occurrence: %s") % ( flagname, first_module, second_module, flag_summary) return cls(msg)
python
def from_flag(cls, flagname, flag_values, other_flag_values=None): first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _helpers.GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') flag_summary = flag_values[flagname].help msg = ("The flag '%s' is defined twice. First from %s, Second from %s. " "Description from first occurrence: %s") % ( flagname, first_module, second_module, flag_summary) return cls(msg)
[ "def", "from_flag", "(", "cls", ",", "flagname", ",", "flag_values", ",", "other_flag_values", "=", "None", ")", ":", "first_module", "=", "flag_values", ".", "FindModuleDefiningFlag", "(", "flagname", ",", "default", "=", "'<unknown>'", ")", "if", "other_flag_v...
Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. Returns: An instance of DuplicateFlagError.
[ "Create", "a", "DuplicateFlagError", "by", "providing", "flag", "name", "and", "values", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/exceptions.py#L71-L98
24,374
google/python-gflags
gflags/argument_parser.py
BooleanParser.convert
def convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument)
python
def convert(self, argument): if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument)
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "str", ")", ":", "if", "argument", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'t'", ",", "'1'", "]", ":", "return", "True", "elif", "argumen...
Converts the argument to a boolean; raise ValueError on errors.
[ "Converts", "the", "argument", "to", "a", "boolean", ";", "raise", "ValueError", "on", "errors", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/argument_parser.py#L270-L284
24,375
google/python-gflags
gflags/argument_parser.py
EnumParser.parse
def parse(self, argument): """Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. Args: argument: The supplied flag value. Returns: The matching element from enum_values, or argument if enum_values is empty. Raises: ValueError: enum_values was non-empty, but argument didn't match anything in enum. """ if not self.enum_values: return argument elif self.case_sensitive: if argument not in self.enum_values: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return argument else: if argument.upper() not in [value.upper() for value in self.enum_values]: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return [value for value in self.enum_values if value.upper() == argument.upper()][0]
python
def parse(self, argument): if not self.enum_values: return argument elif self.case_sensitive: if argument not in self.enum_values: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return argument else: if argument.upper() not in [value.upper() for value in self.enum_values]: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return [value for value in self.enum_values if value.upper() == argument.upper()][0]
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "not", "self", ".", "enum_values", ":", "return", "argument", "elif", "self", ".", "case_sensitive", ":", "if", "argument", "not", "in", "self", ".", "enum_values", ":", "raise", "ValueError", ...
Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. Args: argument: The supplied flag value. Returns: The matching element from enum_values, or argument if enum_values is empty. Raises: ValueError: enum_values was non-empty, but argument didn't match anything in enum.
[ "Determine", "validity", "of", "argument", "and", "return", "the", "correct", "element", "of", "enum", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/argument_parser.py#L311-L345
24,376
google/python-gflags
gflags/argument_parser.py
CsvListSerializer.serialize
def serialize(self, value): """Serialize a list as a string, if possible, or as a unicode string.""" if six.PY2: # In Python2 csv.writer doesn't accept unicode, so we convert to UTF-8. output = io.BytesIO() csv.writer(output).writerow([unicode(x).encode('utf-8') for x in value]) serialized_value = output.getvalue().decode('utf-8').strip() else: # In Python3 csv.writer expects a text stream. output = io.StringIO() csv.writer(output).writerow([str(x) for x in value]) serialized_value = output.getvalue().strip() # We need the returned value to be pure ascii or Unicodes so that # when the xml help is generated they are usefully encodable. return _helpers.StrOrUnicode(serialized_value)
python
def serialize(self, value): if six.PY2: # In Python2 csv.writer doesn't accept unicode, so we convert to UTF-8. output = io.BytesIO() csv.writer(output).writerow([unicode(x).encode('utf-8') for x in value]) serialized_value = output.getvalue().decode('utf-8').strip() else: # In Python3 csv.writer expects a text stream. output = io.StringIO() csv.writer(output).writerow([str(x) for x in value]) serialized_value = output.getvalue().strip() # We need the returned value to be pure ascii or Unicodes so that # when the xml help is generated they are usefully encodable. return _helpers.StrOrUnicode(serialized_value)
[ "def", "serialize", "(", "self", ",", "value", ")", ":", "if", "six", ".", "PY2", ":", "# In Python2 csv.writer doesn't accept unicode, so we convert to UTF-8.", "output", "=", "io", ".", "BytesIO", "(", ")", "csv", ".", "writer", "(", "output", ")", ".", "wri...
Serialize a list as a string, if possible, or as a unicode string.
[ "Serialize", "a", "list", "as", "a", "string", "if", "possible", "or", "as", "a", "unicode", "string", "." ]
4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/argument_parser.py#L365-L380
24,377
shichao-an/soundmeter
soundmeter/meter.py
Meter.record
def record(self): """ Record PyAudio stream into StringIO output This coroutine keeps stream open; the stream is closed in stop() """ while True: frames = [] self.stream.start_stream() for i in range(self.num_frames): data = self.stream.read(self.config.FRAMES_PER_BUFFER) frames.append(data) self.output.seek(0) w = wave.open(self.output, 'wb') w.setnchannels(self.config.CHANNELS) w.setsampwidth(self.audio.get_sample_size(self.config.FORMAT)) w.setframerate(self.config.RATE) w.writeframes(b''.join(frames)) w.close() yield
python
def record(self): while True: frames = [] self.stream.start_stream() for i in range(self.num_frames): data = self.stream.read(self.config.FRAMES_PER_BUFFER) frames.append(data) self.output.seek(0) w = wave.open(self.output, 'wb') w.setnchannels(self.config.CHANNELS) w.setsampwidth(self.audio.get_sample_size(self.config.FORMAT)) w.setframerate(self.config.RATE) w.writeframes(b''.join(frames)) w.close() yield
[ "def", "record", "(", "self", ")", ":", "while", "True", ":", "frames", "=", "[", "]", "self", ".", "stream", ".", "start_stream", "(", ")", "for", "i", "in", "range", "(", "self", ".", "num_frames", ")", ":", "data", "=", "self", ".", "stream", ...
Record PyAudio stream into StringIO output This coroutine keeps stream open; the stream is closed in stop()
[ "Record", "PyAudio", "stream", "into", "StringIO", "output" ]
89222cd45e6ac24da32a1197d6b4be891d63267d
https://github.com/shichao-an/soundmeter/blob/89222cd45e6ac24da32a1197d6b4be891d63267d/soundmeter/meter.py#L84-L104
24,378
shichao-an/soundmeter
soundmeter/meter.py
Meter.stop
def stop(self): """Stop the stream and terminate PyAudio""" self.prestop() if not self._graceful: self._graceful = True self.stream.stop_stream() self.audio.terminate() msg = 'Stopped' self.verbose_info(msg, log=False) # Log 'Stopped' anyway if self.log: self.logging.info(msg) if self.collect: if self._data: print('Collected result:') print(' min: %10d' % self._data['min']) print(' max: %10d' % self._data['max']) print(' avg: %10d' % int(self._data['avg'])) self.poststop()
python
def stop(self): self.prestop() if not self._graceful: self._graceful = True self.stream.stop_stream() self.audio.terminate() msg = 'Stopped' self.verbose_info(msg, log=False) # Log 'Stopped' anyway if self.log: self.logging.info(msg) if self.collect: if self._data: print('Collected result:') print(' min: %10d' % self._data['min']) print(' max: %10d' % self._data['max']) print(' avg: %10d' % int(self._data['avg'])) self.poststop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "prestop", "(", ")", "if", "not", "self", ".", "_graceful", ":", "self", ".", "_graceful", "=", "True", "self", ".", "stream", ".", "stop_stream", "(", ")", "self", ".", "audio", ".", "terminate", ...
Stop the stream and terminate PyAudio
[ "Stop", "the", "stream", "and", "terminate", "PyAudio" ]
89222cd45e6ac24da32a1197d6b4be891d63267d
https://github.com/shichao-an/soundmeter/blob/89222cd45e6ac24da32a1197d6b4be891d63267d/soundmeter/meter.py#L161-L179
24,379
shichao-an/soundmeter
soundmeter/meter.py
Meter.get_threshold
def get_threshold(self): """Get and validate raw RMS value from threshold""" if self.threshold.startswith('+'): if self.threshold[1:].isdigit(): self._threshold = int(self.threshold[1:]) self._upper = True elif self.threshold.startswith('-'): if self.threshold[1:].isdigit(): self._threshold = int(self.threshold[1:]) self._upper = False else: if self.threshold.isdigit(): self._threshold = int(self.threshold) self._upper = True if not hasattr(self, '_threshold'): raise ValueError('Invalid threshold')
python
def get_threshold(self): if self.threshold.startswith('+'): if self.threshold[1:].isdigit(): self._threshold = int(self.threshold[1:]) self._upper = True elif self.threshold.startswith('-'): if self.threshold[1:].isdigit(): self._threshold = int(self.threshold[1:]) self._upper = False else: if self.threshold.isdigit(): self._threshold = int(self.threshold) self._upper = True if not hasattr(self, '_threshold'): raise ValueError('Invalid threshold')
[ "def", "get_threshold", "(", "self", ")", ":", "if", "self", ".", "threshold", ".", "startswith", "(", "'+'", ")", ":", "if", "self", ".", "threshold", "[", "1", ":", "]", ".", "isdigit", "(", ")", ":", "self", ".", "_threshold", "=", "int", "(", ...
Get and validate raw RMS value from threshold
[ "Get", "and", "validate", "raw", "RMS", "value", "from", "threshold" ]
89222cd45e6ac24da32a1197d6b4be891d63267d
https://github.com/shichao-an/soundmeter/blob/89222cd45e6ac24da32a1197d6b4be891d63267d/soundmeter/meter.py#L181-L197
24,380
shichao-an/soundmeter
soundmeter/meter.py
Meter.collect_rms
def collect_rms(self, rms): """Collect and calculate min, max and average RMS values""" if self._data: self._data['min'] = min(rms, self._data['min']) self._data['max'] = max(rms, self._data['max']) self._data['avg'] = float(rms + self._data['avg']) / 2 else: self._data['min'] = rms self._data['max'] = rms self._data['avg'] = rms
python
def collect_rms(self, rms): if self._data: self._data['min'] = min(rms, self._data['min']) self._data['max'] = max(rms, self._data['max']) self._data['avg'] = float(rms + self._data['avg']) / 2 else: self._data['min'] = rms self._data['max'] = rms self._data['avg'] = rms
[ "def", "collect_rms", "(", "self", ",", "rms", ")", ":", "if", "self", ".", "_data", ":", "self", ".", "_data", "[", "'min'", "]", "=", "min", "(", "rms", ",", "self", ".", "_data", "[", "'min'", "]", ")", "self", ".", "_data", "[", "'max'", "]...
Collect and calculate min, max and average RMS values
[ "Collect", "and", "calculate", "min", "max", "and", "average", "RMS", "values" ]
89222cd45e6ac24da32a1197d6b4be891d63267d
https://github.com/shichao-an/soundmeter/blob/89222cd45e6ac24da32a1197d6b4be891d63267d/soundmeter/meter.py#L258-L267
24,381
chainside/btcpy
btcpy/structs/transaction.py
TimeBasedSequence.from_timedelta
def from_timedelta(cls, timedelta): """expects a datetime.timedelta object""" from math import ceil units = ceil(timedelta.total_seconds() / cls.time_unit) return cls.create(units)
python
def from_timedelta(cls, timedelta): from math import ceil units = ceil(timedelta.total_seconds() / cls.time_unit) return cls.create(units)
[ "def", "from_timedelta", "(", "cls", ",", "timedelta", ")", ":", "from", "math", "import", "ceil", "units", "=", "ceil", "(", "timedelta", ".", "total_seconds", "(", ")", "/", "cls", ".", "time_unit", ")", "return", "cls", ".", "create", "(", "units", ...
expects a datetime.timedelta object
[ "expects", "a", "datetime", ".", "timedelta", "object" ]
8e75c630dacf0f997ed0e0e8739bed428a95d7b1
https://github.com/chainside/btcpy/blob/8e75c630dacf0f997ed0e0e8739bed428a95d7b1/btcpy/structs/transaction.py#L126-L130
24,382
chainside/btcpy
btcpy/lib/base58.py
b58decode_check
def b58decode_check(v: str) -> bytes: '''Decode and verify the checksum of a Base58 encoded string''' result = b58decode(v) result, check = result[:-4], result[-4:] digest = sha256(sha256(result).digest()).digest() if check != digest[:4]: raise ValueError("Invalid checksum") return result
python
def b58decode_check(v: str) -> bytes: '''Decode and verify the checksum of a Base58 encoded string''' result = b58decode(v) result, check = result[:-4], result[-4:] digest = sha256(sha256(result).digest()).digest() if check != digest[:4]: raise ValueError("Invalid checksum") return result
[ "def", "b58decode_check", "(", "v", ":", "str", ")", "->", "bytes", ":", "result", "=", "b58decode", "(", "v", ")", "result", ",", "check", "=", "result", "[", ":", "-", "4", "]", ",", "result", "[", "-", "4", ":", "]", "digest", "=", "sha256", ...
Decode and verify the checksum of a Base58 encoded string
[ "Decode", "and", "verify", "the", "checksum", "of", "a", "Base58", "encoded", "string" ]
8e75c630dacf0f997ed0e0e8739bed428a95d7b1
https://github.com/chainside/btcpy/blob/8e75c630dacf0f997ed0e0e8739bed428a95d7b1/btcpy/lib/base58.py#L64-L74
24,383
chainside/btcpy
btcpy/lib/bech32.py
bech32_decode
def bech32_decode(bech): """Validate a Bech32 string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return None, None bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(bech) or len(bech) > 90: return None, None if not all(x in CHARSET for x in bech[pos+1:]): return None, None hrp = bech[:pos] data = [CHARSET.find(x) for x in bech[pos+1:]] if not bech32_verify_checksum(hrp, data): return None, None return hrp, data[:-6]
python
def bech32_decode(bech): if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return None, None bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(bech) or len(bech) > 90: return None, None if not all(x in CHARSET for x in bech[pos+1:]): return None, None hrp = bech[:pos] data = [CHARSET.find(x) for x in bech[pos+1:]] if not bech32_verify_checksum(hrp, data): return None, None return hrp, data[:-6]
[ "def", "bech32_decode", "(", "bech", ")", ":", "if", "(", "(", "any", "(", "ord", "(", "x", ")", "<", "33", "or", "ord", "(", "x", ")", ">", "126", "for", "x", "in", "bech", ")", ")", "or", "(", "bech", ".", "lower", "(", ")", "!=", "bech",...
Validate a Bech32 string, and determine HRP and data.
[ "Validate", "a", "Bech32", "string", "and", "determine", "HRP", "and", "data", "." ]
8e75c630dacf0f997ed0e0e8739bed428a95d7b1
https://github.com/chainside/btcpy/blob/8e75c630dacf0f997ed0e0e8739bed428a95d7b1/btcpy/lib/bech32.py#L62-L77
24,384
yourlabs/django-session-security
session_security/middleware.py
SessionSecurityMiddleware.process_request
def process_request(self, request): """ Update last activity time or logout. """ if django.VERSION < (1, 10): is_authenticated = request.user.is_authenticated() else: is_authenticated = request.user.is_authenticated if not is_authenticated: return now = datetime.now() if '_session_security' not in request.session: set_last_activity(request.session, now) return delta = now - get_last_activity(request.session) expire_seconds = self.get_expire_seconds(request) if delta >= timedelta(seconds=expire_seconds): logout(request) elif (request.path == reverse('session_security_ping') and 'idleFor' in request.GET): self.update_last_activity(request, now) elif not self.is_passive_request(request): set_last_activity(request.session, now)
python
def process_request(self, request): if django.VERSION < (1, 10): is_authenticated = request.user.is_authenticated() else: is_authenticated = request.user.is_authenticated if not is_authenticated: return now = datetime.now() if '_session_security' not in request.session: set_last_activity(request.session, now) return delta = now - get_last_activity(request.session) expire_seconds = self.get_expire_seconds(request) if delta >= timedelta(seconds=expire_seconds): logout(request) elif (request.path == reverse('session_security_ping') and 'idleFor' in request.GET): self.update_last_activity(request, now) elif not self.is_passive_request(request): set_last_activity(request.session, now)
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "django", ".", "VERSION", "<", "(", "1", ",", "10", ")", ":", "is_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "else", ":", "is_authenticated", "=",...
Update last activity time or logout.
[ "Update", "last", "activity", "time", "or", "logout", "." ]
5845c55f1c4b8cef8362302d64b396fc705e1a10
https://github.com/yourlabs/django-session-security/blob/5845c55f1c4b8cef8362302d64b396fc705e1a10/session_security/middleware.py#L56-L80
24,385
yourlabs/django-session-security
session_security/utils.py
get_last_activity
def get_last_activity(session): """ Get the last activity datetime string from the session and return the python datetime object. """ try: return datetime.strptime(session['_session_security'], '%Y-%m-%dT%H:%M:%S.%f') except AttributeError: ################################################################# # * this is an odd bug in python # bug report: http://bugs.python.org/issue7980 # bug explained here: # http://code-trick.com/python-bug-attribute-error-_strptime/ # * sometimes, in multithreaded enviroments, we get AttributeError # in this case, we just return datetime.now(), # so that we are not logged out # "./session_security/middleware.py", in update_last_activity # last_activity = get_last_activity(request.session) # "./session_security/utils.py", in get_last_activity # '%Y-%m-%dT%H:%M:%S.%f') # AttributeError: _strptime # ################################################################# return datetime.now() except TypeError: return datetime.now()
python
def get_last_activity(session): try: return datetime.strptime(session['_session_security'], '%Y-%m-%dT%H:%M:%S.%f') except AttributeError: ################################################################# # * this is an odd bug in python # bug report: http://bugs.python.org/issue7980 # bug explained here: # http://code-trick.com/python-bug-attribute-error-_strptime/ # * sometimes, in multithreaded enviroments, we get AttributeError # in this case, we just return datetime.now(), # so that we are not logged out # "./session_security/middleware.py", in update_last_activity # last_activity = get_last_activity(request.session) # "./session_security/utils.py", in get_last_activity # '%Y-%m-%dT%H:%M:%S.%f') # AttributeError: _strptime # ################################################################# return datetime.now() except TypeError: return datetime.now()
[ "def", "get_last_activity", "(", "session", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "session", "[", "'_session_security'", "]", ",", "'%Y-%m-%dT%H:%M:%S.%f'", ")", "except", "AttributeError", ":", "##############################################...
Get the last activity datetime string from the session and return the python datetime object.
[ "Get", "the", "last", "activity", "datetime", "string", "from", "the", "session", "and", "return", "the", "python", "datetime", "object", "." ]
5845c55f1c4b8cef8362302d64b396fc705e1a10
https://github.com/yourlabs/django-session-security/blob/5845c55f1c4b8cef8362302d64b396fc705e1a10/session_security/utils.py#L11-L38
24,386
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.name
def name(self): """Get the name associated with these credentials""" return self.inquire(name=True, lifetime=False, usage=False, mechs=False).name
python
def name(self): return self.inquire(name=True, lifetime=False, usage=False, mechs=False).name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "inquire", "(", "name", "=", "True", ",", "lifetime", "=", "False", ",", "usage", "=", "False", ",", "mechs", "=", "False", ")", ".", "name" ]
Get the name associated with these credentials
[ "Get", "the", "name", "associated", "with", "these", "credentials" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L70-L73
24,387
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.acquire
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both', store=None): """Acquire GSSAPI credentials This method acquires credentials. If the `store` argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise, the credentials are acquired from the default store. The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores. Using a non-default store requires support for the credentials store extension. Args: name (Name): the name associated with the credentials, or None for the default name lifetime (int): the desired lifetime of the credentials, or None for indefinite mechs (list): the desired :class:`MechType` OIDs to be used with the credentials, or None for the default set usage (str): the usage for the credentials -- either 'both', 'initiate', or 'accept' store (dict): the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (:requires-ext:`cred_store`) Returns: AcquireCredResult: the acquired credentials and information about them Raises: BadMechanismError BadNameTypeError BadNameError ExpiredCredentialsError MissingCredentialsError """ if store is None: res = rcreds.acquire_cred(name, lifetime, mechs, usage) else: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores") store = _encode_dict(store) res = rcred_cred_store.acquire_cred_from(store, name, lifetime, mechs, usage) return tuples.AcquireCredResult(cls(base=res.creds), res.mechs, res.lifetime)
python
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both', store=None): if store is None: res = rcreds.acquire_cred(name, lifetime, mechs, usage) else: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores") store = _encode_dict(store) res = rcred_cred_store.acquire_cred_from(store, name, lifetime, mechs, usage) return tuples.AcquireCredResult(cls(base=res.creds), res.mechs, res.lifetime)
[ "def", "acquire", "(", "cls", ",", "name", "=", "None", ",", "lifetime", "=", "None", ",", "mechs", "=", "None", ",", "usage", "=", "'both'", ",", "store", "=", "None", ")", ":", "if", "store", "is", "None", ":", "res", "=", "rcreds", ".", "acqui...
Acquire GSSAPI credentials This method acquires credentials. If the `store` argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise, the credentials are acquired from the default store. The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores. Using a non-default store requires support for the credentials store extension. Args: name (Name): the name associated with the credentials, or None for the default name lifetime (int): the desired lifetime of the credentials, or None for indefinite mechs (list): the desired :class:`MechType` OIDs to be used with the credentials, or None for the default set usage (str): the usage for the credentials -- either 'both', 'initiate', or 'accept' store (dict): the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (:requires-ext:`cred_store`) Returns: AcquireCredResult: the acquired credentials and information about them Raises: BadMechanismError BadNameTypeError BadNameError ExpiredCredentialsError MissingCredentialsError
[ "Acquire", "GSSAPI", "credentials" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L94-L151
24,388
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.store
def store(self, store=None, usage='both', mech=None, overwrite=False, set_default=False): """Store these credentials into the given store This method stores the current credentials into the specified credentials store. If the default store is used, support for :rfc:`5588` is required. Otherwise, support for the credentials store extension is required. :requires-ext:`rfc5588` or :requires-ext:`cred_store` Args: store (dict): the store into which to store the credentials, or None for the default store. usage (str): the usage to store the credentials with -- either 'both', 'initiate', or 'accept' mech (OID): the :class:`MechType` to associate with the stored credentials overwrite (bool): whether or not to overwrite existing credentials stored with the same name, etc set_default (bool): whether or not to set these credentials as the default credentials for the given store. Returns: StoreCredResult: the results of the credential storing operation Raises: GSSError ExpiredCredentialsError MissingCredentialsError OperationUnavailableError DuplicateCredentialsElementError """ if store is None: if rcred_rfc5588 is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for RFC 5588") return rcred_rfc5588.store_cred(self, usage, mech, overwrite, set_default) else: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores directly") store = _encode_dict(store) return rcred_cred_store.store_cred_into(store, self, usage, mech, overwrite, set_default)
python
def store(self, store=None, usage='both', mech=None, overwrite=False, set_default=False): if store is None: if rcred_rfc5588 is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for RFC 5588") return rcred_rfc5588.store_cred(self, usage, mech, overwrite, set_default) else: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores directly") store = _encode_dict(store) return rcred_cred_store.store_cred_into(store, self, usage, mech, overwrite, set_default)
[ "def", "store", "(", "self", ",", "store", "=", "None", ",", "usage", "=", "'both'", ",", "mech", "=", "None", ",", "overwrite", "=", "False", ",", "set_default", "=", "False", ")", ":", "if", "store", "is", "None", ":", "if", "rcred_rfc5588", "is", ...
Store these credentials into the given store This method stores the current credentials into the specified credentials store. If the default store is used, support for :rfc:`5588` is required. Otherwise, support for the credentials store extension is required. :requires-ext:`rfc5588` or :requires-ext:`cred_store` Args: store (dict): the store into which to store the credentials, or None for the default store. usage (str): the usage to store the credentials with -- either 'both', 'initiate', or 'accept' mech (OID): the :class:`MechType` to associate with the stored credentials overwrite (bool): whether or not to overwrite existing credentials stored with the same name, etc set_default (bool): whether or not to set these credentials as the default credentials for the given store. Returns: StoreCredResult: the results of the credential storing operation Raises: GSSError ExpiredCredentialsError MissingCredentialsError OperationUnavailableError DuplicateCredentialsElementError
[ "Store", "these", "credentials", "into", "the", "given", "store" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L153-L203
24,389
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.impersonate
def impersonate(self, name=None, lifetime=None, mechs=None, usage='initiate'): """Impersonate a name using the current credentials This method acquires credentials by impersonating another name using the current credentials. :requires-ext:`s4u` Args: name (Name): the name to impersonate lifetime (int): the desired lifetime of the new credentials, or None for indefinite mechs (list): the desired :class:`MechType` OIDs for the new credentials usage (str): the desired usage for the new credentials -- either 'both', 'initiate', or 'accept'. Note that some mechanisms may only support 'initiate'. Returns: Credentials: the new credentials impersonating the given name """ if rcred_s4u is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for S4U") res = rcred_s4u.acquire_cred_impersonate_name(self, name, lifetime, mechs, usage) return type(self)(base=res.creds)
python
def impersonate(self, name=None, lifetime=None, mechs=None, usage='initiate'): if rcred_s4u is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for S4U") res = rcred_s4u.acquire_cred_impersonate_name(self, name, lifetime, mechs, usage) return type(self)(base=res.creds)
[ "def", "impersonate", "(", "self", ",", "name", "=", "None", ",", "lifetime", "=", "None", ",", "mechs", "=", "None", ",", "usage", "=", "'initiate'", ")", ":", "if", "rcred_s4u", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Your GSSAPI imple...
Impersonate a name using the current credentials This method acquires credentials by impersonating another name using the current credentials. :requires-ext:`s4u` Args: name (Name): the name to impersonate lifetime (int): the desired lifetime of the new credentials, or None for indefinite mechs (list): the desired :class:`MechType` OIDs for the new credentials usage (str): the desired usage for the new credentials -- either 'both', 'initiate', or 'accept'. Note that some mechanisms may only support 'initiate'. Returns: Credentials: the new credentials impersonating the given name
[ "Impersonate", "a", "name", "using", "the", "current", "credentials" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L205-L236
24,390
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.inquire
def inquire(self, name=True, lifetime=True, usage=True, mechs=True): """Inspect these credentials for information This method inspects these credentials for information about them. Args: name (bool): get the name associated with the credentials lifetime (bool): get the remaining lifetime for the credentials usage (bool): get the usage for the credentials mechs (bool): get the mechanisms associated with the credentials Returns: InquireCredResult: the information about the credentials, with None used when the corresponding argument was False Raises: MissingCredentialsError InvalidCredentialsError ExpiredCredentialsError """ res = rcreds.inquire_cred(self, name, lifetime, usage, mechs) if res.name is not None: res_name = names.Name(res.name) else: res_name = None return tuples.InquireCredResult(res_name, res.lifetime, res.usage, res.mechs)
python
def inquire(self, name=True, lifetime=True, usage=True, mechs=True): res = rcreds.inquire_cred(self, name, lifetime, usage, mechs) if res.name is not None: res_name = names.Name(res.name) else: res_name = None return tuples.InquireCredResult(res_name, res.lifetime, res.usage, res.mechs)
[ "def", "inquire", "(", "self", ",", "name", "=", "True", ",", "lifetime", "=", "True", ",", "usage", "=", "True", ",", "mechs", "=", "True", ")", ":", "res", "=", "rcreds", ".", "inquire_cred", "(", "self", ",", "name", ",", "lifetime", ",", "usage...
Inspect these credentials for information This method inspects these credentials for information about them. Args: name (bool): get the name associated with the credentials lifetime (bool): get the remaining lifetime for the credentials usage (bool): get the usage for the credentials mechs (bool): get the mechanisms associated with the credentials Returns: InquireCredResult: the information about the credentials, with None used when the corresponding argument was False Raises: MissingCredentialsError InvalidCredentialsError ExpiredCredentialsError
[ "Inspect", "these", "credentials", "for", "information" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L238-L267
24,391
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.inquire_by_mech
def inquire_by_mech(self, mech, name=True, init_lifetime=True, accept_lifetime=True, usage=True): """Inspect these credentials for per-mechanism information This method inspects these credentials for per-mechanism information about them. Args: mech (OID): the mechanism for which to retrive the information name (bool): get the name associated with the credentials init_lifetime (bool): get the remaining initiate lifetime for the credentials accept_lifetime (bool): get the remaining accept lifetime for the credentials usage (bool): get the usage for the credentials Returns: InquireCredByMechResult: the information about the credentials, with None used when the corresponding argument was False """ res = rcreds.inquire_cred_by_mech(self, mech, name, init_lifetime, accept_lifetime, usage) if res.name is not None: res_name = names.Name(res.name) else: res_name = None return tuples.InquireCredByMechResult(res_name, res.init_lifetime, res.accept_lifetime, res.usage)
python
def inquire_by_mech(self, mech, name=True, init_lifetime=True, accept_lifetime=True, usage=True): res = rcreds.inquire_cred_by_mech(self, mech, name, init_lifetime, accept_lifetime, usage) if res.name is not None: res_name = names.Name(res.name) else: res_name = None return tuples.InquireCredByMechResult(res_name, res.init_lifetime, res.accept_lifetime, res.usage)
[ "def", "inquire_by_mech", "(", "self", ",", "mech", ",", "name", "=", "True", ",", "init_lifetime", "=", "True", ",", "accept_lifetime", "=", "True", ",", "usage", "=", "True", ")", ":", "res", "=", "rcreds", ".", "inquire_cred_by_mech", "(", "self", ","...
Inspect these credentials for per-mechanism information This method inspects these credentials for per-mechanism information about them. Args: mech (OID): the mechanism for which to retrive the information name (bool): get the name associated with the credentials init_lifetime (bool): get the remaining initiate lifetime for the credentials accept_lifetime (bool): get the remaining accept lifetime for the credentials usage (bool): get the usage for the credentials Returns: InquireCredByMechResult: the information about the credentials, with None used when the corresponding argument was False
[ "Inspect", "these", "credentials", "for", "per", "-", "mechanism", "information" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L269-L301
24,392
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.add
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): """Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for multiple mechanisms. Unlike :meth:`acquire`, you cannot pass None desired name or mechanism. If the `impersonator` argument is used, the credentials will impersonate the given name using the impersonator credentials (:requires-ext:`s4u`). If the `store` argument is used, the credentials will be acquired from the given credential store (:requires-ext:`cred_store`). Otherwise, the credentials are acquired from the default store. The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores. Note that the `store` argument is not compatible with the `impersonator` argument. Args: name (Name): the name associated with the credentials mech (OID): the desired :class:`MechType` to be used with the credentials usage (str): the usage for the credentials -- either 'both', 'initiate', or 'accept' init_lifetime (int): the desired initiate lifetime of the credentials, or None for indefinite accept_lifetime (int): the desired accept lifetime of the credentials, or None for indefinite impersonator (Credentials): the credentials to use to impersonate the given name, or None to not acquire normally (:requires-ext:`s4u`) store (dict): the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (:requires-ext:`cred_store`) Returns: Credentials: the credentials set containing the current credentials and the newly acquired ones. Raises: BadMechanismError BadNameTypeError BadNameError DuplicateCredentialsElementError ExpiredCredentialsError MissingCredentialsError """ if store is not None and impersonator is not None: raise ValueError('You cannot use both the `impersonator` and ' '`store` arguments at the same time') if store is not None: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores") store = _encode_dict(store) res = rcred_cred_store.add_cred_from(store, self, name, mech, usage, init_lifetime, accept_lifetime) elif impersonator is not None: if rcred_s4u is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for S4U") res = rcred_s4u.add_cred_impersonate_name(self, impersonator, name, mech, usage, init_lifetime, accept_lifetime) else: res = rcreds.add_cred(self, name, mech, usage, init_lifetime, accept_lifetime) return Credentials(res.creds)
python
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): if store is not None and impersonator is not None: raise ValueError('You cannot use both the `impersonator` and ' '`store` arguments at the same time') if store is not None: if rcred_cred_store is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for manipulating " "credential stores") store = _encode_dict(store) res = rcred_cred_store.add_cred_from(store, self, name, mech, usage, init_lifetime, accept_lifetime) elif impersonator is not None: if rcred_s4u is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for S4U") res = rcred_s4u.add_cred_impersonate_name(self, impersonator, name, mech, usage, init_lifetime, accept_lifetime) else: res = rcreds.add_cred(self, name, mech, usage, init_lifetime, accept_lifetime) return Credentials(res.creds)
[ "def", "add", "(", "self", ",", "name", ",", "mech", ",", "usage", "=", "'both'", ",", "init_lifetime", "=", "None", ",", "accept_lifetime", "=", "None", ",", "impersonator", "=", "None", ",", "store", "=", "None", ")", ":", "if", "store", "is", "not...
Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for multiple mechanisms. Unlike :meth:`acquire`, you cannot pass None desired name or mechanism. If the `impersonator` argument is used, the credentials will impersonate the given name using the impersonator credentials (:requires-ext:`s4u`). If the `store` argument is used, the credentials will be acquired from the given credential store (:requires-ext:`cred_store`). Otherwise, the credentials are acquired from the default store. The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores. Note that the `store` argument is not compatible with the `impersonator` argument. Args: name (Name): the name associated with the credentials mech (OID): the desired :class:`MechType` to be used with the credentials usage (str): the usage for the credentials -- either 'both', 'initiate', or 'accept' init_lifetime (int): the desired initiate lifetime of the credentials, or None for indefinite accept_lifetime (int): the desired accept lifetime of the credentials, or None for indefinite impersonator (Credentials): the credentials to use to impersonate the given name, or None to not acquire normally (:requires-ext:`s4u`) store (dict): the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (:requires-ext:`cred_store`) Returns: Credentials: the credentials set containing the current credentials and the newly acquired ones. Raises: BadMechanismError BadNameTypeError BadNameError DuplicateCredentialsElementError ExpiredCredentialsError MissingCredentialsError
[ "Acquire", "more", "credentials", "to", "add", "to", "the", "current", "set" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L303-L386
24,393
pythongssapi/python-gssapi
gssapi/names.py
Name.display_as
def display_as(self, name_type): """ Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfault if the name was not *originally* created with a `name_type` that was not ``None`` (even in cases when a ``name_type`` is later "added", such as via :meth:`canonicalize`). **Do not use this method unless you are sure the above conditions can never happen in your code.** Warning: In addition to the above warning, current versions of MIT krb5 do not actually fully implement this method, and it may return incorrect results in the case of canonicalized names. :requires-ext:`rfc6680` Args: name_type (OID): the :class:`NameType` to use to display the given name Returns: str: the displayed name Raises: OperationUnavailableError """ if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") return rname_rfc6680.display_name_ext(self, name_type).decode( _utils._get_encoding())
python
def display_as(self, name_type): if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") return rname_rfc6680.display_name_ext(self, name_type).decode( _utils._get_encoding())
[ "def", "display_as", "(", "self", ",", "name_type", ")", ":", "if", "rname_rfc6680", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Your GSSAPI implementation does not \"", "\"support RFC 6680 (the GSSAPI naming \"", "\"extensions)\"", ")", "return", "rname_rfc6...
Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfault if the name was not *originally* created with a `name_type` that was not ``None`` (even in cases when a ``name_type`` is later "added", such as via :meth:`canonicalize`). **Do not use this method unless you are sure the above conditions can never happen in your code.** Warning: In addition to the above warning, current versions of MIT krb5 do not actually fully implement this method, and it may return incorrect results in the case of canonicalized names. :requires-ext:`rfc6680` Args: name_type (OID): the :class:`NameType` to use to display the given name Returns: str: the displayed name Raises: OperationUnavailableError
[ "Display", "this", "name", "as", "the", "given", "name", "type", "." ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L125-L165
24,394
pythongssapi/python-gssapi
gssapi/names.py
Name.export
def export(self, composite=False): """Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- :requires-ext:`rfc6680` Returns: bytes: the exported name in token form Raises: MechanismNameRequiredError BadNameTypeError BadNameError """ if composite: if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does " "not support RFC 6680 (the GSSAPI " "naming extensions)") return rname_rfc6680.export_name_composite(self) else: return rname.export_name(self)
python
def export(self, composite=False): if composite: if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does " "not support RFC 6680 (the GSSAPI " "naming extensions)") return rname_rfc6680.export_name_composite(self) else: return rname.export_name(self)
[ "def", "export", "(", "self", ",", "composite", "=", "False", ")", ":", "if", "composite", ":", "if", "rname_rfc6680", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Your GSSAPI implementation does \"", "\"not support RFC 6680 (the GSSAPI \"", "\"naming exte...
Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- :requires-ext:`rfc6680` Returns: bytes: the exported name in token form Raises: MechanismNameRequiredError BadNameTypeError BadNameError
[ "Export", "this", "name", "as", "a", "token", "." ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L188-L215
24,395
pythongssapi/python-gssapi
gssapi/names.py
Name._inquire
def _inquire(self, **kwargs): """Inspect this name for information. This method inspects the name for information. If no keyword arguments are passed, all available information is returned. Otherwise, only the keyword arguments that are passed and set to `True` are returned. Args: mech_name (bool): get whether this is a mechanism name, and, if so, the associated mechanism attrs (bool): get the attributes names for this name Returns: InquireNameResult: the results of the inquiry, with unused fields set to None Raises: GSSError """ if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") if not kwargs: default_val = True else: default_val = False attrs = kwargs.get('attrs', default_val) mech_name = kwargs.get('mech_name', default_val) return rname_rfc6680.inquire_name(self, mech_name=mech_name, attrs=attrs)
python
def _inquire(self, **kwargs): if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") if not kwargs: default_val = True else: default_val = False attrs = kwargs.get('attrs', default_val) mech_name = kwargs.get('mech_name', default_val) return rname_rfc6680.inquire_name(self, mech_name=mech_name, attrs=attrs)
[ "def", "_inquire", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "rname_rfc6680", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Your GSSAPI implementation does not \"", "\"support RFC 6680 (the GSSAPI naming \"", "\"extensions)\"", ")", "if", "not",...
Inspect this name for information. This method inspects the name for information. If no keyword arguments are passed, all available information is returned. Otherwise, only the keyword arguments that are passed and set to `True` are returned. Args: mech_name (bool): get whether this is a mechanism name, and, if so, the associated mechanism attrs (bool): get the attributes names for this name Returns: InquireNameResult: the results of the inquiry, with unused fields set to None Raises: GSSError
[ "Inspect", "this", "name", "for", "information", "." ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L243-L279
24,396
pythongssapi/python-gssapi
gssapi/mechs.py
Mechanism.from_sasl_name
def from_sasl_name(cls, name=None): """ Create a Mechanism from its SASL name Args: name (str): SASL name of the desired mechanism Returns: Mechanism: the desired mechanism Raises: GSSError :requires-ext:`rfc5801` """ if rfc5801 is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for RFC 5801") if isinstance(name, six.text_type): name = name.encode(_utils._get_encoding()) m = rfc5801.inquire_mech_for_saslname(name) return cls(m)
python
def from_sasl_name(cls, name=None): if rfc5801 is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for RFC 5801") if isinstance(name, six.text_type): name = name.encode(_utils._get_encoding()) m = rfc5801.inquire_mech_for_saslname(name) return cls(m)
[ "def", "from_sasl_name", "(", "cls", ",", "name", "=", "None", ")", ":", "if", "rfc5801", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Your GSSAPI implementation does not \"", "\"have support for RFC 5801\"", ")", "if", "isinstance", "(", "name", ",", ...
Create a Mechanism from its SASL name Args: name (str): SASL name of the desired mechanism Returns: Mechanism: the desired mechanism Raises: GSSError :requires-ext:`rfc5801`
[ "Create", "a", "Mechanism", "from", "its", "SASL", "name" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/mechs.py#L141-L164
24,397
pythongssapi/python-gssapi
gssapi/_utils.py
import_gssapi_extension
def import_gssapi_extension(name): """Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extension is not available, the method retuns None. Args: name (str): the name of the extension Returns: module: Either the extension module or None """ try: path = 'gssapi.raw.ext_{0}'.format(name) __import__(path) return sys.modules[path] except ImportError: return None
python
def import_gssapi_extension(name): try: path = 'gssapi.raw.ext_{0}'.format(name) __import__(path) return sys.modules[path] except ImportError: return None
[ "def", "import_gssapi_extension", "(", "name", ")", ":", "try", ":", "path", "=", "'gssapi.raw.ext_{0}'", ".", "format", "(", "name", ")", "__import__", "(", "path", ")", "return", "sys", ".", "modules", "[", "path", "]", "except", "ImportError", ":", "ret...
Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extension is not available, the method retuns None. Args: name (str): the name of the extension Returns: module: Either the extension module or None
[ "Import", "a", "GSSAPI", "extension", "module" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L10-L30
24,398
pythongssapi/python-gssapi
gssapi/_utils.py
inquire_property
def inquire_property(name, doc=None): """Creates a property based on an inquire result This method creates a property that calls the :python:`_inquire` method, and return the value of the requested information. Args: name (str): the name of the 'inquire' result information Returns: property: the created property """ def inquire_property(self): if not self._started: msg = ("Cannot read {0} from a security context whose " "establishment has not yet been started.") raise AttributeError(msg) return getattr(self._inquire(**{name: True}), name) return property(inquire_property, doc=doc)
python
def inquire_property(name, doc=None): def inquire_property(self): if not self._started: msg = ("Cannot read {0} from a security context whose " "establishment has not yet been started.") raise AttributeError(msg) return getattr(self._inquire(**{name: True}), name) return property(inquire_property, doc=doc)
[ "def", "inquire_property", "(", "name", ",", "doc", "=", "None", ")", ":", "def", "inquire_property", "(", "self", ")", ":", "if", "not", "self", ".", "_started", ":", "msg", "=", "(", "\"Cannot read {0} from a security context whose \"", "\"establishment has not ...
Creates a property based on an inquire result This method creates a property that calls the :python:`_inquire` method, and return the value of the requested information. Args: name (str): the name of the 'inquire' result information Returns: property: the created property
[ "Creates", "a", "property", "based", "on", "an", "inquire", "result" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L46-L68
24,399
pythongssapi/python-gssapi
gssapi/_utils.py
_encode_dict
def _encode_dict(d): """Encodes any relevant strings in a dict""" def enc(x): if isinstance(x, six.text_type): return x.encode(_ENCODING) else: return x return dict((enc(k), enc(v)) for k, v in six.iteritems(d))
python
def _encode_dict(d): def enc(x): if isinstance(x, six.text_type): return x.encode(_ENCODING) else: return x return dict((enc(k), enc(v)) for k, v in six.iteritems(d))
[ "def", "_encode_dict", "(", "d", ")", ":", "def", "enc", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "six", ".", "text_type", ")", ":", "return", "x", ".", "encode", "(", "_ENCODING", ")", "else", ":", "return", "x", "return", "dict", ...
Encodes any relevant strings in a dict
[ "Encodes", "any", "relevant", "strings", "in", "a", "dict" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L101-L109