report on guard duty enablement by account
422190
def report(config, tags, accounts, master, debug, region):
    """"""
    accounts_config, master_info, executor = guardian_init(
        config, debug, master, accounts, tags)

    session = get_session(
        master_info.get('role'), 'c7n-guardian',
        master_info.get('profile'),
        region)

    client = session.client('guardduty')
    detector_id = get_or_create_detector_id(client)

    members = {m['AccountId']: m for m in
               client.list_members(DetectorId=detector_id).get('Members')}

    accounts_report = []
    for a in accounts_config['accounts']:
        ar = dict(a)
        accounts_report.append(ar)
        ar.pop('tags', None)
        ar.pop('role')
        ar.pop('regions', None)
        if a['account_id'] not in members:
            ar['member'] = False
            ar['status'] = None
            ar['invited'] = None
            ar['updated'] = datetime.datetime.now().isoformat()
            continue
        m = members[a['account_id']]
        ar['status'] = m['RelationshipStatus']
        ar['member'] = True
        ar['joined'] = m['InvitedAt']
        ar['updated'] = m['UpdatedAt']

    accounts_report.sort(key=operator.itemgetter('updated'), reverse=True)
    print(tabulate(accounts_report, headers=('keys')))
805347
def _enable(name, started, result=True, skip_verify=False, **kwargs):
    '''
    
    '''
    ret = {}

    if not skip_verify:
        # is service available?
        try:
            if not _available(name, ret):
                return ret
        except CommandExecutionError as exc:
            ret['result'] = False
            ret['comment'] = exc.strerror
            return ret

    # Set default expected result
    ret['result'] = result

    # Check to see if this minion supports enable
    if 'service.enable' not in __salt__ or 'service.enabled' not in __salt__:
        if started is True:
            ret['comment'] = ('Enable is not available on this minion,'
                              ' service {0} started').format(name)
        elif started is None:
            ret['comment'] = ('Enable is not available on this minion,'
                              ' service {0} is in the desired state'
                              ).format(name)
        else:
            ret['comment'] = ('Enable is not available on this minion,'
                              ' service {0} is dead').format(name)
        return ret

    # Service can be enabled
    before_toggle_enable_status = __salt__['service.enabled'](name, **kwargs)
    if before_toggle_enable_status:
        # Service is enabled
        if started is True:
            ret['comment'] = ('Service {0} is already enabled,'
                              ' and is running').format(name)
        elif started is None:
            # always be sure in this case to reset the changes dict
            ret['changes'] = {}
            ret['comment'] = ('Service {0} is already enabled,'
                              ' and is in the desired state').format(name)
        else:
            ret['comment'] = ('Service {0} is already enabled,'
                              ' and is dead').format(name)
        return ret

    # Service needs to be enabled
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Service {0} set to be enabled'.format(name)
        return ret

    try:
        if __salt__['service.enable'](name, **kwargs):
            # Service has been enabled
            ret['changes'] = {}
            after_toggle_enable_status = __salt__['service.enabled'](
                name,
                **kwargs)
            # on upstart, certain services like apparmor will always return
            # False, even if correctly activated
            # do not trigger a change
            if before_toggle_enable_status != after_toggle_enable_status:
                ret['changes'][name] = True
            if started is True:
                ret['comment'] = ('Service {0} has been enabled,'
                                  ' and is running').format(name)
            elif started is None:
                ret['comment'] = ('Service {0} has been enabled,'
                                  ' and is in the desired state').format(name)
            else:
                ret['comment'] = ('Service {0} has been enabled,'
                                  ' and is dead').format(name)
            return ret
    except CommandExecutionError as exc:
        enable_error = exc.strerror
    else:
        enable_error = False

    # Service failed to be enabled
    ret['result'] = False
    if started is True:
        ret['comment'] = ('Failed when setting service {0} to start at boot,'
                          ' but the service is running').format(name)
    elif started is None:
        ret['comment'] = ('Failed when setting service {0} to start at boot,'
                          ' but the service was already running').format(name)
    else:
        ret['comment'] = ('Failed when setting service {0} to start at boot,'
                          ' and the service is dead').format(name)

    if enable_error:
        ret['comment'] += '. Additional information follows:\n\n{0}'.format(
            enable_error
        )

    return ret
74980
public static base_response enable(nitro_service client, lbmonitor resource) throws Exception {
		lbmonitor enableresource = new lbmonitor();
		enableresource.servicename = resource.servicename;
		enableresource.servicegroupname = resource.servicegroupname;
		enableresource.monitorname = resource.monitorname;
		return enableresource.perform_operation(client,"enable");
	}
904750
function newService()
    {
        $auths  = \Module\Authorization\Services::ContainerAuthenticators();
        $guards = \Module\Authorization\Services::ContainerGuards();

        $action = new AuthenticatorAction($auths, $guards);
        return $action;
    }
370226
def get_enabled(self) -> List[ScheduledTransaction]:
        
        query = (
            self.query
            .filter(ScheduledTransaction.enabled == True)
        )
        return query.all()
980888
def query_by_account(self, account_id, end_time=None, start_time=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - account_id
        """ID"""
        path["account_id"] = account_id

        # OPTIONAL - start_time
        """The beginning of the time range from which you want events."""
        if start_time is not None:
            params["start_time"] = start_time

        # OPTIONAL - end_time
        """The end of the time range from which you want events."""
        if end_time is not None:
            params["end_time"] = end_time

        self.logger.debug("GET /api/v1/audit/authentication/accounts/{account_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/audit/authentication/accounts/{account_id}".format(**path), data=data, params=params, no_data=True)
855067
def get(self):
        """"""
        _, accounts = BaseAccount.search()

        if ROLE_ADMIN not in session['user'].roles:
            accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))

        if accounts:
            return self.make_response({
                'message': None,
                'accounts': [x.to_json(is_admin=ROLE_ADMIN in session['user'].roles or False) for x in accounts]
            })
        else:
            return self.make_response({
                'message': 'Unable to find any accounts',
                'accounts': None
            }, HTTP.NOT_FOUND)
719350
def select_army(self, shift):
    """"""
    action = sc_pb.Action()
    action.action_ui.select_army.selection_add = shift
    return action
1118979
function getOperationForInsertingLog(tableName, action, item) {
        return api.getMetadata(tableName, action, item).then(function(metadata) {
            return {
                tableName: operationTableName,
                action: 'upsert',
                data: {
                    id: ++maxId,
                    tableName: tableName,
                    action: action,
                    itemId: item[idPropertyName],
                    metadata: metadata
                }
            };
        });
    }
837570
def user_enable_login(attribs, dir_info)
      attribs = user_record_name_alternatives(attribs)

      check_critical_attribute( attribs, :record_name )
      attribs    = tidy_attribs(attribs)

      command = {attribute: 'enableuser', value: nil}
      params  = command.merge(attribs)
      pwpolicy(params, dir_info)
    end
549758
function setAccountQuorum (commandOptions, { accountId, quorum }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'setAccountQuorum',
      {
        accountId,
        quorum
      }
    )
  )
}
419413
@Override
    protected void logIncrementalStatsByAccount(String account, RunStats stats) {
        log.info("Session stats by account (incremental): account={} tasksAdded={}",
                 account, ((BitIntegrityRunStats) stats).getAdded());

    }
1222183
def report(mount):
    '''
    
    '''
    ret = {mount: {}}
    ret[mount]['User Quotas'] = _parse_quota(mount, '-u')
    ret[mount]['Group Quotas'] = _parse_quota(mount, '-g')
    return ret
475043
function _activate_account() {
            if ( $this->is_registered() ) {
                // Already activated.
                return;
            }

            self::_clean_admin_content_section();

            if ( fs_request_is_action( 'activate' ) && fs_request_is_post() ) {
//				check_admin_referer( 'activate_' . $this->_plugin->public_key );

                // Verify matching plugin details.
                if ( $this->_plugin->id != fs_request_get( 'plugin_id' ) || $this->_slug != fs_request_get( 'plugin_slug' ) ) {
                    return;
                }

                $user              = new FS_User();
                $user->id          = fs_request_get( 'user_id' );
                $user->public_key  = fs_request_get( 'user_public_key' );
                $user->secret_key  = fs_request_get( 'user_secret_key' );
                $user->email       = fs_request_get( 'user_email' );
                $user->first       = fs_request_get( 'user_first' );
                $user->last        = fs_request_get( 'user_last' );
                $user->is_verified = fs_request_get_bool( 'user_is_verified' );

                $site             = new FS_Site();
                $site->id         = fs_request_get( 'install_id' );
                $site->public_key = fs_request_get( 'install_public_key' );
                $site->secret_key = fs_request_get( 'install_secret_key' );
                $site->plan_id    = fs_request_get( 'plan_id' );

                $plans      = array();
                $plans_data = json_decode( urldecode( fs_request_get( 'plans' ) ) );
                foreach ( $plans_data as $p ) {
                    $plan = new FS_Plugin_Plan( $p );
                    if ( $site->plan_id == $plan->id ) {
                        $plan->title = fs_request_get( 'plan_title' );
                        $plan->name  = fs_request_get( 'plan_name' );
                    }

                    $plans[] = $plan;
                }

                $this->_set_account( $user, $site, $plans );

                // Reload the page with the keys.
                fs_redirect( $this->_get_admin_page_url() );
            }
        }
1036322
function report(type, state, params)
{
  var reporter = defaultReporter;

  // get rest of arguments
  params  = Array.prototype.slice.call(arguments, 1);

  // `init` and `done` types don't have command associated with them
  if (['init', 'done'].indexOf(type) == -1)
  {
    // second (1) position is for command
    // if command present get string representation of it
    params[1] = stringifyCommand(state, params[1]);
  }

  if (state && state.options && state.options.reporter)
  {
    reporter = state.options.reporter;
  }

  reporter[type].apply(null, params);
}
484425
def audit_1_1(self):
        """"""
        for row in self.credential_report:
            if row["user"] == "<root_account>":
                for field in "password_last_used", "access_key_1_last_used_date", "access_key_2_last_used_date":
                    if row[field] != "N/A" and self.parse_date(row[field]) > datetime.now(tzutc()) - timedelta(days=1):
                        raise Exception("Root account last used less than a day ago ({})".format(field))
1268273
public boolean checkPermission(Principal user, int operation) 
  {  
    if (tc.isEntryEnabled()) 
      SibTr.entry(tc, "checkPermission", new Object[]{user, new Integer(operation)});
    boolean allowed = false;
    
    if(operation == 1) // a publish operation
    {
      // check whether permission has been granted to special group Everyone. 
      // We can do this before we check whether the user is authenticated
      if(accumGroupAllowedToPublish.size() > 0
         && accumGroupAllowedToPublish.contains(everyone))
      {
        allowed = true;
      }
      // Now check whether the user is authenticated, ie we have a username
      else if (user.getName() != null 
               && user.getName().length() > 0)
      {
        // User is authenticated
                  
        // Check user list next
        if(accumUsersAllowedToPublish.size() > 0 &&
            accumUsersAllowedToPublish.contains(user))
        {
          allowed = true;
        }
        else // Now check the groups
        {
          if(accumGroupAllowedToPublish.size() > 0)
          {
            // user hasn't been granted access directly, check the groups
            // check for AllAuthenticated first     
            if (accumGroupAllowedToPublish.contains(allAuthenticated))
            {
              allowed = true;
            }
            else
            {              
              Iterator itr = accumGroupAllowedToPublish.iterator();
              while (itr.hasNext())
              {
                Group group = (Group)itr.next();
                if(group.isMember(user))
                {
                  allowed = true;
                  break;
                }
              } // eof while
            }
          }
        } 
      }
    }
    else // a subscribe operation
    {
      // check whether permission has been granted to special group Everyone. 
      // We can do this before we check whether the user is authenticated
      if(accumGroupAllowedToSubscribe.size() > 0
         && accumGroupAllowedToSubscribe.contains(everyone))
      {
        allowed = true;
      }
      // Now check whether the user is authenticated, ie we have a username
      else if (user.getName() != null 
               && user.getName().length() > 0)
      {
        // User is authenticated
                  
        // Check user list next        
        if(accumUsersAllowedToSubscribe.size() > 0 &&
           accumUsersAllowedToSubscribe.contains(user))
        {
          allowed = true;
        }
        else // Now check the groups
        {
          if(accumGroupAllowedToSubscribe.size() > 0)
          {
            // user hasn't been granted access directly, check the groups
            // check for AllAuthenticated first     
            if (accumGroupAllowedToSubscribe.contains(allAuthenticated))
            {
              allowed = true;
            }
            else
            {                       
              Iterator itr = accumGroupAllowedToSubscribe.iterator();
           
              while (itr.hasNext())
              {
                Group group = (Group)itr.next();
                if(group.isMember(user))
                {
                  allowed = true;
                  break;
                }
              }
            }
          } 
        } 
      }       
    }
    if (tc.isEntryEnabled()) SibTr.exit(tc, "checkPermission", new Boolean(allowed));
    return allowed;
  }