_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q229800 | ScriptManager._RunScripts | train | def _RunScripts(self, run_dir=None):
"""Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
"""
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', se... | python | {
"resource": ""
} |
q229801 | InstanceSetup._GetInstanceConfig | train | def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance at... | python | {
"resource": ""
} |
q229802 | InstanceSetup._GenerateSshKey | train | def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type... | python | {
"resource": ""
} |
q229803 | InstanceSetup._StartSshd | train | def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.co... | python | {
"resource": ""
} |
q229804 | InstanceSetup._SetSshHostKeys | train | def _SetSshHostKeys(self, host_key_types=None):
"""Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first t... | python | {
"resource": ""
} |
q229805 | InstanceSetup._SetupBotoConfig | train | def _SetupBotoConfig(self):
"""Set the boto config so GSUtil works with provisioned service accounts."""
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e)) | python | {
"resource": ""
} |
q229806 | ScriptRetriever._DownloadAuthUrl | train | def _DownloadAuthUrl(self, url, dest_dir):
"""Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
... | python | {
"resource": ""
} |
q229807 | ScriptRetriever._DownloadUrl | train | def _DownloadUrl(self, url, dest_dir):
"""Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfil... | python | {
"resource": ""
} |
q229808 | ScriptRetriever._DownloadScript | train | def _DownloadScript(self, url, dest_dir):
"""Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
... | python | {
"resource": ""
} |
q229809 | ScriptRetriever._GetAttributeScripts | train | def _GetAttributeScripts(self, attribute_data, dest_dir):
"""Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping meta... | python | {
"resource": ""
} |
q229810 | ScriptRetriever.GetScripts | train | def GetScripts(self, dest_dir):
"""Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts.
"""
metadata_dict = self.watcher.GetMetadata() or {}
try... | python | {
"resource": ""
} |
q229811 | ScriptExecutor._MakeExecutable | train | def _MakeExecutable(self, metadata_script):
"""Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
"""
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC) | python | {
"resource": ""
} |
q229812 | ScriptExecutor.RunScripts | train | def RunScripts(self, script_dict):
"""Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files.
"""
metadata_types = ['%s-script-url', '%s-script']
metadata_keys = [key % self.script_type for key in metadata... | python | {
"resource": ""
} |
q229813 | ConfigManager._AddHeader | train | def _AddHeader(self, fp):
"""Create a file header in the config.
Args:
fp: int, a file pointer for writing the header.
"""
text = textwrap.wrap(
textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join(['# ' + line for line in text]))
fp.write('\n\n') | python | {
"resource": ""
} |
q229814 | ConfigManager.SetOption | train | def SetOption(self, section, option, value, overwrite=True):
"""Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, Tru... | python | {
"resource": ""
} |
q229815 | ConfigManager.WriteConfig | train | def WriteConfig(self, config_file=None):
"""Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write.
"""
config_file = config_file or self.config_file
config_name = os.path.splitext(os.path.basename(config_file))[0]
config_lock = (... | python | {
"resource": ""
} |
q229816 | Logger | train | def Logger(name, debug=False, facility=None):
"""Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler'... | python | {
"resource": ""
} |
q229817 | AccountsUtils._CreateSudoersGroup | train | def _CreateSudoersGroup(self):
"""Create a Linux group for Google added sudo user accounts."""
if not self._GetGroup(self.google_sudoers_group):
try:
command = self.groupadd_cmd.format(group=self.google_sudoers_group)
subprocess.check_call(command.split(' '))
except subprocess.Called... | python | {
"resource": ""
} |
q229818 | AccountsUtils._AddUser | train | def _AddUser(self, user):
"""Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
"""
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=u... | python | {
"resource": ""
} |
q229819 | AccountsUtils._UpdateUserGroups | train | def _UpdateUserGroups(self, user, groups):
"""Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded.
"""
groups = ','.join(groups)
... | python | {
"resource": ""
} |
q229820 | AccountsUtils._UpdateAuthorizedKeys | train | def _UpdateAuthorizedKeys(self, user, ssh_keys):
"""Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exc... | python | {
"resource": ""
} |
q229821 | AccountsUtils._UpdateSudoer | train | def _UpdateSudoer(self, user, sudoer=False):
"""Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded.
"""
if sudoer:
s... | python | {
"resource": ""
} |
q229822 | AccountsUtils._RemoveAuthorizedKeys | train | def _RemoveAuthorizedKeys(self, user):
"""Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file... | python | {
"resource": ""
} |
q229823 | AccountsUtils.GetConfiguredUsers | train | def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [u... | python | {
"resource": ""
} |
q229824 | AccountsUtils.SetConfiguredUsers | train | def SetConfiguredUsers(self, users):
"""Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts.
"""
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_users:
u... | python | {
"resource": ""
} |
q229825 | AccountsUtils.UpdateUser | train | def UpdateUser(self, user, ssh_keys):
"""Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully.
"""
if not bo... | python | {
"resource": ""
} |
q229826 | AccountsUtils.RemoveUser | train | def RemoveUser(self, user):
"""Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
"""
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
... | python | {
"resource": ""
} |
q229827 | OsLoginUtils._RunOsLoginControl | train | def _RunOsLoginControl(self, params):
"""Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + par... | python | {
"resource": ""
} |
q229828 | OsLoginUtils._GetStatus | train | def _GetStatus(self, two_factor=False):
"""Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed.
"""
params = ['status']
if two_factor:
params += ['--twofactor']
retcode = self._Run... | python | {
"resource": ""
} |
q229829 | OsLoginUtils._RunOsLoginNssCache | train | def _RunOsLoginNssCache(self):
"""Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT])
except OSError as e:
if e.errno == errno.ENOENT:
retu... | python | {
"resource": ""
} |
q229830 | OsLoginUtils._RemoveOsLoginNssCache | train | def _RemoveOsLoginNssCache(self):
"""Remove the OS Login NSS cache file."""
if os.path.exists(constants.OSLOGIN_NSS_CACHE):
try:
os.remove(constants.OSLOGIN_NSS_CACHE)
except OSError as e:
if e.errno != errno.ENOENT:
raise | python | {
"resource": ""
} |
q229831 | OsLoginUtils.UpdateOsLogin | train | def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
"""Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
... | python | {
"resource": ""
} |
q229832 | CallDhclient | train | def CallDhclient(
interfaces, logger, dhclient_script=None):
"""Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient scrip... | python | {
"resource": ""
} |
q229833 | CallHwclock | train | def CallHwclock(logger):
"""Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
command = ['/sbin/hwclock', '--hctosys']
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with hard... | python | {
"resource": ""
} |
q229834 | CallNtpdate | train | def CallNtpdate(logger):
"""Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])
try:
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'stop'])
subprocess.check_call(... | python | {
"resource": ""
} |
q229835 | BotoConfig._GetNumericProjectId | train | def _GetNumericProjectId(self):
"""Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found.
"""
project_id = 'project/numeric-project-id'
return self.watcher.GetMetadata(metadata_key=project_id, recursive=False) | python | {
"resource": ""
} |
q229836 | BotoConfig._CreateConfig | train | def _CreateConfig(self, project_id):
"""Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file.
"""
project_id = project_id or self._GetNumericProjectId()
# Our project doesn't support service accounts.
if not project_id:
... | python | {
"resource": ""
} |
q229837 | IpForwardingUtilsIproute._CreateRouteOptions | train | def _CreateRouteOptions(self, **kwargs):
"""Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command.
"""
options = {
... | python | {
"resource": ""
} |
q229838 | IpForwardingUtilsIproute._RunIpRoute | train | def _RunIpRoute(self, args=None, options=None):
"""Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip ... | python | {
"resource": ""
} |
q229839 | IpForwardingUtilsIfconfig.RemoveForwardedIp | train | def RemoveForwardedIp(self, address, interface):
"""Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use.
"""
ip = netaddr.IPNetwork(address)
self._RunIfconfig(args=[interface, '-alias', str(ip.ip)... | python | {
"resource": ""
} |
q229840 | ComputeAuth._GetGsScopes | train | def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
... | python | {
"resource": ""
} |
q229841 | ComputeAuth._GetAccessToken | train | def _GetAccessToken(self):
"""Return an OAuth 2.0 access token for Google Storage."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
return service_accounts[self.service_account]['token']['access_token']
except KeyError:
return None | python | {
"resource": ""
} |
q229842 | ClockSkewDaemon.HandleClockSync | train | def HandleClockSync(self, response):
"""Called when clock drift token changes.
Args:
response: string, the metadata response with the new drift token value.
"""
self.logger.info('Clock drift token has changed: %s.', response)
self.distro_utils.HandleClockSync(self.logger) | python | {
"resource": ""
} |
q229843 | Utils._DisableNetworkManager | train | def _DisableNetworkManager(self, interfaces, logger):
"""Disable network manager management on a list of network interfaces.
Args:
interfaces: list of string, the output device names enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
... | python | {
"resource": ""
} |
q229844 | Utils._ModifyInterface | train | def _ModifyInterface(
self, interface_config, config_key, config_value, replace=False):
"""Write a value to a config file if not already present.
Args:
interface_config: string, the path to a config file.
config_key: string, the configuration key to set.
config_value: string, the value ... | python | {
"resource": ""
} |
q229845 | AccountsDaemon._HasExpired | train | def _HasExpired(self, key):
"""Check whether an SSH key has expired.
Uses Google-specific semantics of the OpenSSH public key format's comment
field to determine if an SSH key is past its expiration timestamp, and
therefore no longer to be trusted. This format is still subject to change.
Reliance o... | python | {
"resource": ""
} |
q229846 | AccountsDaemon._ParseAccountsData | train | def _ParseAccountsData(self, account_data):
"""Parse the SSH key data into a user map.
Args:
account_data: string, the metadata server SSH key attributes data.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
"""
if not account_data:
return {}
l... | python | {
"resource": ""
} |
q229847 | AccountsDaemon._GetInstanceAndProjectAttributes | train | def _GetInstanceAndProjectAttributes(self, metadata_dict):
"""Get dictionaries for instance and project attributes.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
tuple, two dictionaries for instance and project attributes.
"""
metadata_dict = met... | python | {
"resource": ""
} |
q229848 | AccountsDaemon._GetAccountsData | train | def _GetAccountsData(self, metadata_dict):
"""Get the user accounts specified in metadata server contents.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
"""
instance_data, pro... | python | {
"resource": ""
} |
q229849 | AccountsDaemon._UpdateUsers | train | def _UpdateUsers(self, update_users):
"""Provision and update Linux user accounts based on account metadata.
Args:
update_users: dict, authorized users mapped to their public SSH keys.
"""
for user, ssh_keys in update_users.items():
if not user or user in self.invalid_users:
continu... | python | {
"resource": ""
} |
q229850 | AccountsDaemon._RemoveUsers | train | def _RemoveUsers(self, remove_users):
"""Deprovision Linux user accounts that do not appear in account metadata.
Args:
remove_users: list, the username strings of the Linux accounts to remove.
"""
for username in remove_users:
self.utils.RemoveUser(username)
self.user_ssh_keys.pop(use... | python | {
"resource": ""
} |
q229851 | AccountsDaemon._GetEnableOsLoginValue | train | def _GetEnableOsLoginValue(self, metadata_dict):
"""Get the value of the enable-oslogin metadata key.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
bool, True if OS Login is enabled for VM access.
"""
instance_data, project_data = self._GetInstan... | python | {
"resource": ""
} |
q229852 | AccountsDaemon.HandleAccounts | train | def HandleAccounts(self, result):
"""Called when there are changes to the contents of the metadata server.
Args:
result: json, the deserialized contents of the metadata server.
"""
self.logger.debug('Checking for changes to user accounts.')
configured_users = self.utils.GetConfiguredUsers()
... | python | {
"resource": ""
} |
q229853 | _SetSELinuxContext | train | def _SetSELinuxContext(path):
"""Set the appropriate SELinux context, if SELinux tools are installed.
Calls /sbin/restorecon on the provided path to set the SELinux context as
specified by policy. This call does not operate recursively.
Only some OS configurations use SELinux. It is therefore acceptable for
... | python | {
"resource": ""
} |
q229854 | SetPermissions | train | def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False):
"""Set the permissions and ownership of a path.
Args:
path: string, the path for which owner ID and group ID needs to be setup.
mode: octal string, the permissions to set on the path.
uid: int, the owner ID to be set for the path.
... | python | {
"resource": ""
} |
q229855 | Lock | train | def Lock(fd, path, blocking):
"""Lock the provided file descriptor.
Args:
fd: int, the file descriptor of the file to lock.
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Raises:
IOError, raised from flock while attempting to lock a fi... | python | {
"resource": ""
} |
q229856 | Unlock | train | def Unlock(fd, path):
"""Release the lock on the file.
Args:
fd: int, the file descriptor of the file to unlock.
path: string, the name of the file to lock.
Raises:
IOError, raised from flock while attempting to release a file lock.
"""
try:
fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
e... | python | {
"resource": ""
} |
q229857 | LockFile | train | def LockFile(path, blocking=False):
"""Interface to flock-based file locking to prevent concurrent executions.
Args:
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.
Yields:
None, yields when a lock on the file is obtained.
Raises:
IO... | python | {
"resource": ""
} |
q229858 | RetryOnUnavailable | train | def RetryOnUnavailable(func):
"""Function decorator to retry on a service unavailable exception."""
@functools.wraps(func)
def Wrapper(*args, **kwargs):
while True:
try:
response = func(*args, **kwargs)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
time.... | python | {
"resource": ""
} |
q229859 | MetadataWatcher._GetMetadataRequest | train | def _GetMetadataRequest(self, metadata_url, params=None, timeout=None):
"""Performs a GET request with the metadata headers.
Args:
metadata_url: string, the URL to perform a GET request on.
params: dictionary, the query parameters in the GET request.
timeout: int, timeout in seconds for metad... | python | {
"resource": ""
} |
q229860 | MetadataWatcher._UpdateEtag | train | def _UpdateEtag(self, response):
"""Update the etag from an API response.
Args:
response: HTTP response with a header field.
Returns:
bool, True if the etag in the response header updated.
"""
etag = response.headers.get('etag', self.etag)
etag_updated = self.etag != etag
self.... | python | {
"resource": ""
} |
q229861 | MetadataWatcher._GetMetadataUpdate | train | def _GetMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None):
"""Request the contents of metadata server and deserialize the response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadat... | python | {
"resource": ""
} |
q229862 | MetadataWatcher._HandleMetadataUpdate | train | def _HandleMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None,
retry=True):
"""Wait for a successful metadata response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata change... | python | {
"resource": ""
} |
q229863 | MetadataWatcher.WatchMetadata | train | def WatchMetadata(
self, handler, metadata_key='', recursive=True, timeout=None):
"""Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes.
rec... | python | {
"resource": ""
} |
q229864 | MetadataWatcher.GetMetadata | train | def GetMetadata(
self, metadata_key='', recursive=True, timeout=None, retry=True):
"""Retrieve the contents of metadata server for a metadata key.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
... | python | {
"resource": ""
} |
q229865 | IpForwarding._LogForwardedIpChanges | train | def _LogForwardedIpChanges(
self, configured, desired, to_add, to_remove, interface):
"""Log the planned IP address changes.
Args:
configured: list, the IP address strings already configured.
desired: list, the IP address strings that will be configured.
to_add: list, the forwarded IP a... | python | {
"resource": ""
} |
q229866 | IpForwarding._AddForwardedIps | train | def _AddForwardedIps(self, forwarded_ips, interface):
"""Configure the forwarded IP address on the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to configure.
interface: string, the output device to use.
"""
for address in forwarded_ips:
self.ip_forwar... | python | {
"resource": ""
} |
q229867 | IpForwarding._RemoveForwardedIps | train | def _RemoveForwardedIps(self, forwarded_ips, interface):
"""Remove the forwarded IP addresses from the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to delete.
interface: string, the output device to use.
"""
for address in forwarded_ips:
self.ip_forwa... | python | {
"resource": ""
} |
q229868 | IpForwarding.HandleForwardedIps | train | def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None):
"""Handle changes to the forwarded IPs on a network interface.
Args:
interface: string, the output device to configure.
forwarded_ips: list, the forwarded IP address strings desired.
interface_ip: string, current inter... | python | {
"resource": ""
} |
q229869 | Utils._WriteIfcfg | train | def _WriteIfcfg(self, interfaces, logger):
"""Write ifcfg files for multi-NIC support.
Overwrites the files. This allows us to update ifcfg-* in the future.
Disable the network setup to override this behavior and customize the
configurations.
Args:
interfaces: list of string, the output devi... | python | {
"resource": ""
} |
q229870 | Utils._Ifup | train | def _Ifup(self, interfaces, logger):
"""Activate network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
ifup = ['/usr/sbin/wicked', 'ifup', '--timeout', '1']
try:
subprocess.check... | python | {
"resource": ""
} |
q229871 | NetworkDaemon.HandleNetworkInterfaces | train | def HandleNetworkInterfaces(self, result):
"""Called when network interface metadata changes.
Args:
result: dict, the metadata response with the network interfaces.
"""
network_interfaces = self._ExtractInterfaceMetadata(result)
if self.network_setup_enabled:
self.network_setup.EnableN... | python | {
"resource": ""
} |
q229872 | NetworkDaemon._ExtractInterfaceMetadata | train | def _ExtractInterfaceMetadata(self, metadata):
"""Extracts network interface metadata.
Args:
metadata: dict, the metadata response with the new network interfaces.
Returns:
list, a list of NetworkInterface objects.
"""
interfaces = []
for network_interface in metadata:
mac_ad... | python | {
"resource": ""
} |
q229873 | Client._build_url | train | def _build_url(self, query_params):
"""Build the final URL to be passed to urllib
:param query_params: A dictionary of all the query parameters
:type query_params: dictionary
:return: string
"""
url = ''
count = 0
while count < len(self._url_path):
... | python | {
"resource": ""
} |
q229874 | Client._build_client | train | def _build_client(self, name=None):
"""Make a new Client object
:param name: Name of the url segment
:type name: string
:return: A Client object
"""
url_path = self._url_path + [name] if name else self._url_path
return Client(host=self.host,
... | python | {
"resource": ""
} |
q229875 | Client._make_request | train | def _make_request(self, opener, request, timeout=None):
"""Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: url... | python | {
"resource": ""
} |
q229876 | category | train | def category(msg):
"""Aircraft category number
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: category number
"""
if common.typecode(msg) < 1 or common.typecode(msg) > 4:
raise RuntimeError("%s: Not a identification message" % msg)
msgbin = comm... | python | {
"resource": ""
} |
q229877 | airborne_position | train | def airborne_position(msg0, msg1, t0, t1):
"""Decode airborn position from a pair of even and odd position message
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t... | python | {
"resource": ""
} |
q229878 | airborne_position_with_ref | train | def airborne_position_with_ref(msg, lat_ref, lon_ref):
"""Decode airborne position with only one message,
knowing reference nearby location, such as previously calculated location,
ground station, or airport location, etc. The reference position shall
be with in 180NM of the true position.
Args:
... | python | {
"resource": ""
} |
q229879 | hex2bin | train | def hex2bin(hexstr):
"""Convert a hexdecimal string to binary string, with zero fillings. """
num_of_bits = len(hexstr) * 4
binstr = bin(int(hexstr, 16))[2:].zfill(int(num_of_bits))
return binstr | python | {
"resource": ""
} |
q229880 | icao | train | def icao(msg):
"""Calculate the ICAO address from an Mode-S message
with DF4, DF5, DF20, DF21
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
String: ICAO address in 6 bytes hexadecimal string
"""
DF = df(msg)
if DF in (11, 17, 18):
addr = msg[2:8... | python | {
"resource": ""
} |
q229881 | gray2int | train | def gray2int(graystr):
"""Convert greycode to binary"""
num = bin2int(graystr)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num | python | {
"resource": ""
} |
q229882 | allzeros | train | def allzeros(msg):
"""check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
d = hex2bin(data(msg))
if bin2int(d) > 0:
return False
else:
return True | python | {
"resource": ""
} |
q229883 | wrongstatus | train | def wrongstatus(data, sb, msb, lsb):
"""Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions.
"""
# status bit, most significant bit, least significant bit
status = int(data[sb-1])
value = bin2int(data[msb-1:lsb])
if not status:
... | python | {
"resource": ""
} |
q229884 | version | train | def version(msg):
"""ADS-B Version
Args:
msg (string): 28 bytes hexadecimal message string, TC = 31
Returns:
int: version number
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.h... | python | {
"resource": ""
} |
q229885 | nic_v1 | train | def nic_v1(msg, NICs):
"""Calculate NIC, navigation integrity category, for ADS-B version 1
Args:
msg (string): 28 bytes hexadecimal message string
NICs (int or string): NIC supplement
Returns:
int or string: Horizontal Radius of Containment
int or string: Vertical Protecti... | python | {
"resource": ""
} |
q229886 | nic_v2 | train | def nic_v2(msg, NICa, NICbc):
"""Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizon... | python | {
"resource": ""
} |
q229887 | nic_s | train | def nic_s(msg):
"""Obtain NIC supplement bit, TC=31 message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICs number (0 or 1)
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
... | python | {
"resource": ""
} |
q229888 | nic_b | train | def nic_b(msg):
"""Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1)
"""
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, e... | python | {
"resource": ""
} |
q229889 | nac_p | train | def nac_p(msg):
"""Calculate NACp, Navigation Accuracy Category - Position
Args:
msg (string): 28 bytes hexadecimal message string, TC = 29 or 31
Returns:
int or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty
int or string: 95% vertical accuracy bounds, Vert... | python | {
"resource": ""
} |
q229890 | nac_v | train | def nac_v(msg):
"""Calculate NACv, Navigation Accuracy Category - Velocity
Args:
msg (string): 28 bytes hexadecimal message string, TC = 19
Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds fo... | python | {
"resource": ""
} |
q229891 | sil | train | def sil(msg, version):
"""Calculate SIL, Surveillance Integrity Level
Args:
msg (string): 28 bytes hexadecimal message string with TC = 29, 31
Returns:
int or string: Probability of exceeding Horizontal Radius of Containment RCu
int or string: Probability of exceeding Vertical Inte... | python | {
"resource": ""
} |
q229892 | roll50 | train | def roll50(msg):
"""Roll angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees,
negative->left wing down, positive->right wing down
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
... | python | {
"resource": ""
} |
q229893 | trk50 | train | def trk50(msg):
"""True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360)
"""
d = hex2bin(data(msg))
if d[11] == '0':
return None
sign = int(d[12]) # 1 -> w... | python | {
"resource": ""
} |
q229894 | gs50 | train | def gs50(msg):
"""Ground speed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: ground speed in knots
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
spd = bin2int(d[24:34]) * 2 # kts
return spd | python | {
"resource": ""
} |
q229895 | tas50 | train | def tas50(msg):
"""Aircraft true airspeed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[45] == '0':
return None
tas = bin2int(d[46:56]) * 2 # kts
return t... | python | {
"resource": ""
} |
q229896 | ias53 | train | def ias53(msg):
"""Indicated airspeed, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
int: indicated arispeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # knots
return ias | python | {
"resource": ""
} |
q229897 | mach53 | train | def mach53(msg):
"""MACH number, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: MACH number
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:33]) * 0.008
return round(mach, 3) | python | {
"resource": ""
} |
q229898 | tas53 | train | def tas53(msg):
"""Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[33] == '0':
return None
tas = bin2int(d[34:46]) * 0.5 # kts
return round(tas, 1... | python | {
"resource": ""
} |
q229899 | BaseClient.read_skysense_buffer | train | def read_skysense_buffer(self):
"""Skysense stream format.
::
----------------------------------------------------------------------------------
Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS
--------------------------------------... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.