_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q35900
RequiredTagsAuditor.check_required_tags_compliance
train
def check_required_tags_compliance(self, resource): """Check whether a resource is compliance Args: resource: A single resource Returns: `(list, list)` A tuple contains missing tags (if there were any) and notes """ missing_tags = [] ...
python
{ "resource": "" }
q35901
RequiredTagsAuditor.notify
train
def notify(self, notices): """Send notifications to the recipients provided Args: notices (:obj:`dict` of `str`: `list`): A dictionary mapping notification messages to the recipient. Returns: `None` """ tmpl_html = get_template('required_tags_notice.html...
python
{ "resource": "" }
q35902
Enforcement.get_one
train
def get_one(cls, enforcement_id): """ Return the properties of any enforcement action""" qry = db.Enforcements.filter(enforcement_id == Enforcements.enforcement_id) return qry
python
{ "resource": "" }
q35903
Enforcement.get_all
train
def get_all(cls, account_id=None, location=None): """ Return all Enforcements args: `account_id` : Unique Account Identifier `location` : Region associated with the Resource returns: list of enforcement objects """ qry = db.Enforcements.filt...
python
{ "resource": "" }
q35904
Enforcement.create
train
def create(cls, account_id, resource_id, action, timestamp, metrics): """ Set properties for an enforcement action""" enforcement = Enforcements() enforcement.account_id = account_id enforcement.resource_id = resource_id enforcement.action = action enforcement.timestamp ...
python
{ "resource": "" }
q35905
IssueType.get
train
def get(cls, issue_type): """Returns the IssueType object for `issue_type`. If no existing object was found, a new type will be created in the database and returned Args: issue_type (str,int,IssueType): Issue type name, id or class Returns: :obj:`IssueType` ...
python
{ "resource": "" }
q35906
Issue.get
train
def get(issue_id, issue_type_id): """Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None """ return db.Issue.find_one( ...
python
{ "resource": "" }
q35907
EBSAuditor.run
train
def run(self, *args, **kwargs): """Main execution point for the auditor Args: *args: **kwargs: Returns: `None` """ self.log.debug('Starting EBSAuditor') data = self.update_data() notices = defaultdict(list) for accoun...
python
{ "resource": "" }
q35908
EBSAuditor.get_unattached_volumes
train
def get_unattached_volumes(self): """Build a list of all volumes missing tags and not ignored. Returns a `dict` keyed by the issue_id with the volume as the value Returns: :obj:`dict` of `str`: `EBSVolume` """ volumes = {} ignored_tags = dbconfig.get('ignore_...
python
{ "resource": "" }
q35909
EBSAuditor.process_new_issues
train
def process_new_issues(self, volumes, existing_issues): """Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated issues. Args: volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues existing_is...
python
{ "resource": "" }
q35910
EBSAuditor.process_fixed_issues
train
def process_fixed_issues(self, volumes, existing_issues): """Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict...
python
{ "resource": "" }
q35911
EBSAuditor.notify
train
def notify(self, notices): """Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None` """ issues_html = get_template('unattached_ebs_volume.html') i...
python
{ "resource": "" }
q35912
get_local_aws_session
train
def get_local_aws_session(): """Returns a session for the local instance, not for a remote account Returns: :obj:`boto3:boto3.session.Session` """ if not all((app_config.aws_api.access_key, app_config.aws_api.secret_key)): return boto3.session.Session() else: # If we are not...
python
{ "resource": "" }
q35913
get_aws_session
train
def get_aws_session(account): """Function to return a boto3 Session based on the account passed in the first argument. Args: account (:obj:`Account`): Account to create the session object for Returns: :obj:`boto3:boto3.session.Session` """ from cloud_inquisitor.config import dbconf...
python
{ "resource": "" }
q35914
get_aws_regions
train
def get_aws_regions(*, force=False): """Load a list of AWS regions from the AWS static data. Args: force (`bool`): Force fetch list of regions even if we already have a cached version Returns: :obj:`list` of `str` """ from cloud_inquisitor.config import dbconfig global __region...
python
{ "resource": "" }
q35915
AccountList.get
train
def get(self): """List all accounts""" _, 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({ ...
python
{ "resource": "" }
q35916
AccountDetail.get
train
def get(self, accountId): """Fetch a single account""" account = BaseAccount.get(accountId) if account: return self.make_response({ 'message': None, 'account': account.to_json(is_admin=True) }) else: return self.make_res...
python
{ "resource": "" }
q35917
AccountDetail.put
train
def put(self, accountId): """Update an account""" self.reqparse.add_argument('accountName', type=str, required=True) self.reqparse.add_argument('accountType', type=str, required=True) self.reqparse.add_argument('contacts', type=dict, required=True, action='append') self.reqparse....
python
{ "resource": "" }
q35918
AccountDetail.delete
train
def delete(self, accountId): """Delete an account""" acct = BaseAccount.get(accountId) if not acct: raise Exception('No such account found') acct.delete() auditlog(event='account.delete', actor=session['user'].username, data={'accountId': accountId}) return ...
python
{ "resource": "" }
q35919
AWSAccountCollector.__get_distribution_tags
train
def __get_distribution_tags(self, client, arn): """Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict` ...
python
{ "resource": "" }
q35920
AWSAccountCollector.__fetch_route53_zones
train
def __fetch_route53_zones(self): """Return a list of all DNS zones hosted in Route53 Returns: :obj:`list` of `dict` """ done = False marker = None zones = {} route53 = self.session.client('route53') try: while not done: ...
python
{ "resource": "" }
q35921
AWSAccountCollector.__fetch_route53_zone_records
train
def __fetch_route53_zone_records(self, zone_id): """Return all resource records for a specific Route53 zone Args: zone_id (`str`): Name / ID of the hosted zone Returns: `dict` """ route53 = self.session.client('route53') done = False nex...
python
{ "resource": "" }
q35922
AWSAccountCollector.__fetch_route53_zone_tags
train
def __fetch_route53_zone_tags(self, zone_id): """Return a dict with the tags for the zone Args: zone_id (`str`): ID of the hosted zone Returns: :obj:`dict` of `str`: `str` """ route53 = self.session.client('route53') try: return { ...
python
{ "resource": "" }
q35923
AWSAccountCollector._get_resource_hash
train
def _get_resource_hash(zone_name, record): """Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique resource IDs Args: zone_name (`str`): The name of the DNS Zone the record belongs to record (`dict`): A record dict to gen...
python
{ "resource": "" }
q35924
AWSAccountCollector._get_bucket_statistics
train
def _get_bucket_statistics(self, bucket_name, bucket_region, storage_type, statistic, days): """ Returns datapoints from cloudwatch for bucket statistics. Args: bucket_name `(str)`: The name of the bucket statistic `(str)`: The statistic you want to fetch from days `...
python
{ "resource": "" }
q35925
ResourceType.get
train
def get(cls, resource_type): """Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType` """ ...
python
{ "resource": "" }
q35926
Account.get
train
def get(account_id, account_type_id=None): """Return account by ID and type Args: account_id (`int`, `str`): Unique Account identifier account_type_id (str): Type of account to get Returns: :obj:`Account`: Returns an Account object if found, else None ...
python
{ "resource": "" }
q35927
Account.user_has_access
train
def user_has_access(self, user): """Check if a user has access to view information for the account Args: user (:obj:`User`): User object to check Returns: True if user has access to the account, else false """ if ROLE_ADMIN in user.roles: ret...
python
{ "resource": "" }
q35928
BaseScheduler.load_plugins
train
def load_plugins(self): """Refresh the list of available collectors and auditors Returns: `None` """ for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.collectors']['plugins']: cls = entry_point.load() if cls.enabled(): self.log...
python
{ "resource": "" }
q35929
BaseSchedulerCommand.load_scheduler_plugins
train
def load_scheduler_plugins(self): """Refresh the list of available schedulers Returns: `list` of :obj:`BaseScheduler` """ if not self.scheduler_plugins: for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.schedulers']['plugins']: cls = entry...
python
{ "resource": "" }
q35930
Scheduler.run
train
def run(self, **kwargs): """Execute the scheduler. Returns: `None` """ if not super().run(**kwargs): return if kwargs['list']: self.log.info('--- List of Scheduler Modules ---') for name, scheduler in list(self.scheduler_plugins.i...
python
{ "resource": "" }
q35931
Worker.run
train
def run(self, **kwargs): """Execute the worker thread. Returns: `None` """ super().run(**kwargs) scheduler = self.scheduler_plugins[self.active_scheduler]() if not kwargs['no_daemon']: self.log.info('Starting {} worker with {} threads checking fo...
python
{ "resource": "" }
q35932
TemplateList.post
train
def post(self): """Create a new template""" self.reqparse.add_argument('templateName', type=str, required=True) self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=args['templateName']) ...
python
{ "resource": "" }
q35933
TemplateList.put
train
def put(self): """Re-import all templates, overwriting any local changes made""" try: _import_templates(force=True) return self.make_response('Imported templates') except: self.log.exception('Failed importing templates') return self.make_response('...
python
{ "resource": "" }
q35934
TemplateGet.get
train
def get(self, template_name): """Get a specific template""" template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) return self.make_response({'template': template})
python
{ "resource": "" }
q35935
TemplateGet.put
train
def put(self, template_name): """Update a template""" self.reqparse.add_argument('template', type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such t...
python
{ "resource": "" }
q35936
TemplateGet.delete
train
def delete(self, template_name): """Delete a template""" template = db.Template.find_one(template_name=template_name) if not template: return self.make_response('No such template found', HTTP.NOT_FOUND) db.session.delete(template) db.session.commit() auditlog...
python
{ "resource": "" }
q35937
process_action
train
def process_action(resource, action, action_issuer='unknown'): """Process an audit action for a resource, if possible Args: resource (:obj:`Resource`): A resource object to perform the action on action (`str`): Type of action to perform (`kill` or `stop`) action_issuer (`str`): The issu...
python
{ "resource": "" }
q35938
stop_ec2_instance
train
def stop_ec2_instance(client, resource): """Stop an EC2 Instance This function will attempt to stop a running instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to stop Returns: `ActionStatus` ...
python
{ "resource": "" }
q35939
terminate_ec2_instance
train
def terminate_ec2_instance(client, resource): """Terminate an EC2 Instance This function will terminate an EC2 Instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatu...
python
{ "resource": "" }
q35940
stop_s3_bucket
train
def stop_s3_bucket(client, resource): """ Stop an S3 bucket from being used This function will try to 1. Add lifecycle policy to make sure objects inside it will expire 2. Block certain access to the bucket """ bucket_policy = { 'Version': '2012-10-17', 'Id': 'PutOb...
python
{ "resource": "" }
q35941
delete_s3_bucket
train
def delete_s3_bucket(client, resource): """Delete an S3 bucket This function will try to delete an S3 bucket Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus` """ ...
python
{ "resource": "" }
q35942
BaseResource.get
train
def get(cls, resource_id): """Returns the class object identified by `resource_id` Args: resource_id (str): Unique EC2 Instance ID to load from database Returns: EC2 Instance object if found, else None """ res = Resource.get(resource_id) return c...
python
{ "resource": "" }
q35943
BaseResource.create
train
def create(cls, resource_id, *, account_id, properties=None, tags=None, location=None, auto_add=True, auto_commit=False): """Creates a new Resource object with the properties and tags provided Args: resource_id (str): Unique identifier for the resource object acco...
python
{ "resource": "" }
q35944
BaseResource.get_all
train
def get_all(cls, account=None, location=None, include_disabled=False): """Returns a list of all resources for a given account, location and resource type. Attributes: account (:obj:`Account`): Account owning the resources location (`str`): Location of the resources to return (re...
python
{ "resource": "" }
q35945
BaseResource.search
train
def search(cls, *, limit=100, page=1, accounts=None, locations=None, resources=None, properties=None, include_disabled=False, return_query=False): """Search for resources based on the provided filters. If `return_query` a sub-class of `sqlalchemy.orm.Query` is returned instead of the reso...
python
{ "resource": "" }
q35946
BaseResource.get_owner_emails
train
def get_owner_emails(self, partial_owner_match=True): """Return a list of email addresses associated with the instance, based on tags Returns: List of email addresses if any, else None """ for tag in self.tags: if tag.key.lower() == 'owner': rgx =...
python
{ "resource": "" }
q35947
BaseResource.get_property
train
def get_property(self, name): """Return a named property for a resource, if available. Will raise an `AttributeError` if the property does not exist Args: name (str): Name of the property to return Returns: `ResourceProperty` """ for prop in self...
python
{ "resource": "" }
q35948
BaseResource.set_property
train
def set_property(self, name, value, update_session=True): """Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if there were no changes to the value of the property. Args: name (str): Name of the property to create or update ...
python
{ "resource": "" }
q35949
BaseResource.get_tag
train
def get_tag(self, key, *, case_sensitive=True): """Return a tag by key, if found Args: key (str): Name/key of the tag to locate case_sensitive (bool): Should tag keys be treated case-sensitive (default: true) Returns: `Tag`,`None` """ key = k...
python
{ "resource": "" }
q35950
BaseResource.set_tag
train
def set_tag(self, key, value, update_session=True): """Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or `False` if there were no changes to be made. Args: key (str): Key of the tag value (str): Value of the tag...
python
{ "resource": "" }
q35951
BaseResource.delete_tag
train
def delete_tag(self, key, update_session=True): """Removes a tag from a resource based on the tag key. Returns `True` if the tag was removed or `False` if the tag didn't exist Args: key (str): Key of the tag to delete update_session (bool): Automatically add the change t...
python
{ "resource": "" }
q35952
BaseResource.save
train
def save(self, *, auto_commit=False): """Save the resource to the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None` """ try: db.session.add(self.resource) if auto_commit: ...
python
{ "resource": "" }
q35953
BaseResource.delete
train
def delete(self, *, auto_commit=False): """Removes a resource from the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None` """ try: db.session.delete(self.resource) if auto_com...
python
{ "resource": "" }
q35954
BaseResource.to_json
train
def to_json(self): """Return a `dict` representation of the resource, including all properties and tags Returns: `dict` """ return { 'resourceType': self.resource.resource_type_id, 'resourceId': self.id, 'accountId': self.resource.account_...
python
{ "resource": "" }
q35955
EC2Instance.volumes
train
def volumes(self): """Returns a list of the volumes attached to the instance Returns: `list` of `EBSVolume` """ return [ EBSVolume(res) for res in db.Resource.join( ResourceProperty, Resource.resource_id == ResourceProperty.resource_id ...
python
{ "resource": "" }
q35956
EC2Instance.get_name_or_instance_id
train
def get_name_or_instance_id(self, with_id=False): """Returns the name of an instance if existant, else return the instance id Args: with_id (bool): Include the instance ID even if the name is found (default: False) Returns: Name and/or instance ID of the instance object...
python
{ "resource": "" }
q35957
EC2Instance.search_by_age
train
def search_by_age(cls, *, limit=100, page=1, accounts=None, locations=None, age=720, properties=None, include_disabled=False): """Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`):...
python
{ "resource": "" }
q35958
EC2Instance.to_json
train
def to_json(self, with_volumes=True): """Augment the base `to_json` function, adding information about volumes Returns: `dict` """ data = super().to_json() if with_volumes: data['volumes'] = [ { 'volumeId': vol.id, ...
python
{ "resource": "" }
q35959
DNSZone.delete_record
train
def delete_record(self, record): """Remove a DNSRecord Args: record (:obj:`DNSRecord`): :obj:`DNSRecord` to remove Returns: `None` """ self.children.remove(record.resource) record.delete()
python
{ "resource": "" }
q35960
ConfigList.get
train
def get(self): """List existing config namespaces and their items""" namespaces = db.ConfigNamespace.order_by( ConfigNamespace.sort_order, ConfigNamespace.name ).all() return self.make_response({ 'message': None, 'namespaces': namespaces ...
python
{ "resource": "" }
q35961
ConfigList.post
train
def post(self): """Create a new config item""" self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('description', type=str, required=True) self.reqparse.add_argument('key', type=str, required=True) self.reqparse.add_argument('value', ...
python
{ "resource": "" }
q35962
ConfigGet.get
train
def get(self, namespace, key): """Get a specific configuration item""" cfg = self.dbconfig.get(key, namespace, as_object=True) return self.make_response({ 'message': None, 'config': cfg })
python
{ "resource": "" }
q35963
ConfigGet.put
train
def put(self, namespace, key): """Update a single configuration item""" args = request.json if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) if (args['type'] == 'choice' and ...
python
{ "resource": "" }
q35964
ConfigGet.delete
train
def delete(self, namespace, key): """Delete a specific configuration item""" if not self.dbconfig.key_exists(namespace, key): return self.make_response('No such config entry exists: {}/{}'.format(namespace, key), HTTP.BAD_REQUEST) self.dbconfig.delete(namespace, key) auditlo...
python
{ "resource": "" }
q35965
NamespaceGet.get
train
def get(self, namespacePrefix): """Get a specific configuration namespace""" ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) return sel...
python
{ "resource": "" }
q35966
NamespaceGet.put
train
def put(self, namespacePrefix): """Update a specific configuration namespace""" self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.parse_args() ns = db.ConfigNamespace.find_one(ConfigN...
python
{ "resource": "" }
q35967
NamespaceGet.delete
train
def delete(self, namespacePrefix): """Delete a specific configuration namespace""" ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix) if not ns: return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND) db.s...
python
{ "resource": "" }
q35968
Namespaces.post
train
def post(self): """Create a new configuration namespace""" self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('sortOrder', type=int, required=True) args = self.reqparse.pars...
python
{ "resource": "" }
q35969
_get_syslog_format
train
def _get_syslog_format(event_type): """Take an event type argument and return a python logging format In order to properly format the syslog messages to current standard, load the template and perform necessary replacements and return the string. Args: event_type (str): Event type name Re...
python
{ "resource": "" }
q35970
setup_logging
train
def setup_logging(): """Utility function to setup the logging systems based on the `logging.json` configuration file""" config = json.load(open(os.path.join(config_path, 'logging.json'))) # If syslogging is disabled, set the pipeline handler to NullHandler if dbconfig.get('enable_syslog_forwarding', NS...
python
{ "resource": "" }
q35971
DBLogger.emit
train
def emit(self, record): """Persist a record into the database Args: record (`logging.Record`): The logging.Record object to store Returns: `None` """ # Skip records less than min_level if record.levelno < logging.getLevelName(self.min_level): ...
python
{ "resource": "" }
q35972
ConfigItem.get
train
def get(cls, ns, key): """Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None` """ return getattr(db, cls.__name__).find_one( ...
python
{ "resource": "" }
q35973
User.add_role
train
def add_role(user, roles): """Map roles for user in database Args: user (User): User to add roles to roles ([Role]): List of roles to add Returns: None """ def _add_role(role): user_role = UserRole() user_role.user_id ...
python
{ "resource": "" }
q35974
DBConfig.reload_data
train
def reload_data(self): """Reloads the configuration from the database Returns: `None` """ # We must force a rollback here to ensure that we are working on a fresh session, without any cache db.session.rollback() self.__data = {} try: for ...
python
{ "resource": "" }
q35975
DBConfig.key_exists
train
def key_exists(self, namespace, key): """Checks a namespace for the existence of a specific key Args: namespace (str): Namespace to check in key (str): Name of the key to check for Returns: `True` if key exists in the namespace, else `False` """ ...
python
{ "resource": "" }
q35976
DBConfig.delete
train
def delete(self, namespace, key): """Remove a configuration item from the database Args: namespace (`str`): Namespace of the config item key (`str`): Key to delete Returns: `None` """ if self.key_exists(namespace, key): obj = db.C...
python
{ "resource": "" }
q35977
RoleList.post
train
def post(self): """Create a new role""" self.reqparse.add_argument('name', type=str, required=True) self.reqparse.add_argument('color', type=str, required=True) args = self.reqparse.parse_args() role = Role() role.name = args['name'] role.color = args['color'] ...
python
{ "resource": "" }
q35978
RoleGet.get
train
def get(self, roleId): """Get a specific role information""" role = db.Role.find_one(Role.role_id == roleId) if not role: return self.make_response('No such role found', HTTP.NOT_FOUND) return self.make_response({'role': role})
python
{ "resource": "" }
q35979
RoleGet.delete
train
def delete(self, roleId): """Delete a user role""" role = db.Role.find_one(Role.role_id == roleId) if not role: return self.make_response('No such role found', HTTP.NOT_FOUND) if role.name in ('User', 'Admin'): return self.make_response('Cannot delete the built-i...
python
{ "resource": "" }
q35980
EmailNotifier.__send_ses_email
train
def __send_ses_email(self, recipients, subject, body_html, body_text): """Send an email using SES Args: recipients (`1ist` of `str`): List of recipient email addresses subject (str): Subject of the email body_html (str): HTML body of the email body_text (...
python
{ "resource": "" }
q35981
EmailNotifier.__send_smtp_email
train
def __send_smtp_email(self, recipients, subject, html_body, text_body): """Send an email using SMTP Args: recipients (`list` of `str`): List of recipient email addresses subject (str): Subject of the email html_body (str): HTML body of the email text_body...
python
{ "resource": "" }
q35982
InquisitorJSONEncoder.default
train
def default(self, obj): """Default object encoder function Args: obj (:obj:`Any`): Object to be serialized Returns: JSON string """ if isinstance(obj, datetime): return obj.isoformat() if issubclass(obj.__class__, Enum.__class__): ...
python
{ "resource": "" }
q35983
is_truthy
train
def is_truthy(value, default=False): """Evaluate a value for truthiness >>> is_truthy('Yes') True >>> is_truthy('False') False >>> is_truthy(1) True Args: value (Any): Value to evaluate default (bool): Optional default value, if the input does not match the true or fals...
python
{ "resource": "" }
q35984
validate_email
train
def validate_email(email, partial_match=False): """Perform email address validation >>> validate_email('akjaer@riotgames.com') True >>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com') False >>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com', partial_match=True) True Args: ...
python
{ "resource": "" }
q35985
get_template
train
def get_template(template): """Return a Jinja2 template by filename Args: template (str): Name of the template to return Returns: A Jinja2 Template object """ from cloud_inquisitor.database import db tmpl = db.Template.find_one(template_name=template) if not tmpl: ...
python
{ "resource": "" }
q35986
to_utc_date
train
def to_utc_date(date): """Convert a datetime object from local to UTC format >>> import datetime >>> d = datetime.datetime(2017, 8, 15, 18, 24, 31) >>> to_utc_date(d) datetime.datetime(2017, 8, 16, 1, 24, 31) Args: date (`datetime`): Input datetime object Returns: `datetim...
python
{ "resource": "" }
q35987
generate_password
train
def generate_password(length=32): """Generate a cryptographically secure random string to use for passwords Args: length (int): Length of password, defaults to 32 characters Returns: Randomly generated string """ return ''.join(random.SystemRandom().choice(string.ascii_letters + '!...
python
{ "resource": "" }
q35988
get_jwt_key_data
train
def get_jwt_key_data(): """Returns the data for the JWT private key used for encrypting the user login token as a string object Returns: `str` """ global __jwt_data if __jwt_data: return __jwt_data from cloud_inquisitor import config_path from cloud_inquisitor.config impor...
python
{ "resource": "" }
q35989
has_access
train
def has_access(user, required_roles, match_all=True): """Check if the user meets the role requirements. If mode is set to AND, all the provided roles must apply Args: user (:obj:`User`): User object required_roles (`list` of `str`): List of roles that the user must have applied match_al...
python
{ "resource": "" }
q35990
merge_lists
train
def merge_lists(*args): """Merge an arbitrary number of lists into a single list and dedupe it Args: *args: Two or more lists Returns: A deduped merged list of all the provided lists as a single list """ out = {} for contacts in filter(None, args): for contact in conta...
python
{ "resource": "" }
q35991
get_resource_id
train
def get_resource_id(prefix, *data): """Returns a unique ID based on the SHA256 hash of the provided data. The input data is flattened and sorted to ensure identical hashes are generated regardless of the order of the input. Values must be of types `str`, `int` or `float`, any other input type will raise a `...
python
{ "resource": "" }
q35992
parse_date
train
def parse_date(date_string, ignoretz=True): """Parse a string as a date. If the string fails to parse, `None` will be returned instead >>> parse_date('2017-08-15T18:24:31') datetime.datetime(2017, 8, 15, 18, 24, 31) Args: date_string (`str`): Date in string format to parse ignoretz (`b...
python
{ "resource": "" }
q35993
get_user_data_configuration
train
def get_user_data_configuration(): """Retrieve and update the application configuration with information from the user-data Returns: `None` """ from cloud_inquisitor import get_local_aws_session, app_config kms_region = app_config.kms_region session = get_local_aws_session() if se...
python
{ "resource": "" }
q35994
flatten
train
def flatten(data): """Returns a flattened version of a list. Courtesy of https://stackoverflow.com/a/12472564 Args: data (`tuple` or `list`): Input data Returns: `list` """ if not data: return data if type(data[0]) in (list, tuple): return list(flatten(dat...
python
{ "resource": "" }
q35995
diff
train
def diff(a, b): """Return the difference between two strings Will return a human-readable difference between two strings. See https://docs.python.org/3/library/difflib.html#difflib.Differ for more information about the output format Args: a (str): Original string b (str): New string ...
python
{ "resource": "" }
q35996
build
train
def build(bucket_name, version, force, verbose): """Build and upload a new tarball Args: bucket_name (str): Name of the bucket to upload to version (str): Override build version. Defaults to using SCM based versioning (git tags) force (bool): Overwrite existing files in S3, if present ...
python
{ "resource": "" }
q35997
BaseIssue.get
train
def get(cls, issue_id): """Returns the class object identified by `issue_id` Args: issue_id (str): Unique EC2 Instance ID to load from database Returns: EC2 Instance object if found, else None """ res = Issue.get(issue_id, IssueType.get(cls.issue_type).i...
python
{ "resource": "" }
q35998
BaseIssue.create
train
def create(cls, issue_id, *, properties=None, auto_commit=False): """Creates a new Issue object with the properties and tags provided Attributes: issue_id (str): Unique identifier for the issue object account (:obj:`Account`): Account which owns the issue properties ...
python
{ "resource": "" }
q35999
BaseIssue.get_all
train
def get_all(cls): """Returns a list of all issues of a given type Returns: list of issue objects """ issues = db.Issue.find( Issue.issue_type_id == IssueType.get(cls.issue_type).issue_type_id ) return {res.issue_id: cls(res) for res in issues}
python
{ "resource": "" }