Create an |EnclavePermissions| object from an |Enclave| object.

        :param enclave: the Enclave object
        :return: an EnclavePermissions object
773557
def from_enclave(cls, enclave):
        

        return EnclavePermissions(id=enclave.id,
                                  name=enclave.name,
                                  type=enclave.type)
1356020
def create_instance(host, ami_spec, subnet_id)
      amitype = host['vmname'] || host['platform']
      amisize = host['amisize'] || 'm1.small'
      vpc_id = host['vpc_id'] || @options['vpc_id'] || nil
      host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
      sg_cidr_ips = host['sg_cidr_ips'].split(',')
      assoc_pub_ip_addr = host['associate_public_ip_address']

      if vpc_id && !subnet_id
        raise RuntimeError, "A subnet_id must be provided with a vpc_id"
      end
      
      if assoc_pub_ip_addr && !subnet_id
        raise RuntimeError, "A subnet_id must be provided when configuring assoc_pub_ip_addr"
      end

      # Use snapshot provided for this host
      image_type = host['snapshot']
      raise RuntimeError, "No snapshot/image_type provided for EC2 provisioning" unless image_type

      ami = ami_spec[amitype]
      ami_region = ami[:region]

      # Main region object for ec2 operations
      region = ami_region

      # If we haven't defined a vpc_id then we use the default vpc for the provided region
      unless vpc_id
        @logger.notify("aws-sdk: filtering available vpcs in region by 'isDefault'")

        default_vpcs = client(region).describe_vpcs(:filters => [{:name => 'isDefault', :values => ['true']}])
        vpc_id = if default_vpcs.vpcs.empty?
                   nil
                 else
                   default_vpcs.vpcs.first.vpc_id
                 end
      end

      # Grab the vpc object based upon provided id
      vpc = vpc_id ? client(region).describe_vpcs(:vpc_ids => [vpc_id]).vpcs.first : nil

      # Grab image object
      image_id = ami[:image][image_type.to_sym]
      @logger.notify("aws-sdk: Checking image #{image_id} exists and getting its root device")
      image = client(region).describe_images(:image_ids => [image_id]).images.first
      raise RuntimeError, "Image not found: #{image_id}" if image.nil?

      @logger.notify("Image Storage Type: #{image.root_device_type}")

      # Transform the images block_device_mappings output into a format
      # ready for a create.
      block_device_mappings = []
      if image.root_device_type == :ebs
        orig_bdm = image.block_device_mappings
        @logger.notify("aws-sdk: Image block_device_mappings: #{orig_bdm}")
        orig_bdm.each do |block_device|
          block_device_mappings << {
            :device_name => block_device.device_name,
            :ebs => {
              # Change the default size of the root volume.
              :volume_size => host['volume_size'] || block_device.ebs.volume_size,
              # This is required to override the images default for
              # delete_on_termination, forcing all volumes to be deleted once the
              # instance is terminated.
              :delete_on_termination => true,
            }
          }
        end
      end

      security_group = ensure_group(vpc || region, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
      #check if ping is enabled
      ping_security_group = ensure_ping_group(vpc || region, sg_cidr_ips)

      msg = "aws-sdk: launching %p on %p using %p/%p%s" %
            [host.name, amitype, amisize, image_type,
             subnet_id ? ("in %p" % subnet_id) : '']
      @logger.notify(msg)
      config = {
        :max_count  => 1,
        :min_count  => 1,
        :image_id   => image_id,
        :monitoring => {
          :enabled => true,
        },
        :key_name => ensure_key_pair(region).key_pairs.first.key_name,
        :instance_type => amisize,
        :disable_api_termination => false,
        :instance_initiated_shutdown_behavior => "terminate",
      }
      if assoc_pub_ip_addr
        # this never gets created, so they end up with
        # default security group which only allows for
        # ssh access from outside world which
        # doesn't work well with remote devices etc.
        config[:network_interfaces] = [{
          :subnet_id => subnet_id,
          :groups => [security_group.group_id, ping_security_group.group_id],
          :device_index => 0,
          :associate_public_ip_address => assoc_pub_ip_addr,
        }]
      else
        config[:subnet_id] = subnet_id
      end
      config[:block_device_mappings] = block_device_mappings if image.root_device_type == :ebs
      reservation = client(region).run_instances(config)
      reservation.instances.first
    end
52927
def create_perm(self, using=None, *args, **kwargs):
        
        from django.conf import settings
        from django.contrib.auth.models import Permission
        from django.contrib.contenttypes.models import ContentType

        constance_dbs = getattr(settings, 'CONSTANCE_DBS', None)
        if constance_dbs is not None and using not in constance_dbs:
            return
        if ContentType._meta.installed and Permission._meta.installed:
            content_type, created = ContentType.objects.using(using).get_or_create(
                app_label='constance',
                model='config',
            )

            permission, created = Permission.objects.using(using).get_or_create(
                content_type=content_type,
                codename='change_config',
                defaults={'name': 'Can change config'})
315071
private Assignment createAssignment(
            IPermission permission, IAuthorizationPrincipal authP, boolean inherited) {

        Assignment rslt = null;

        try {

            // Owner
            IPermissionOwner owner = permissionOwnerDao.getPermissionOwner(permission.getOwner());
            Owner ownerImpl = new OwnerImpl(permission.getOwner(), owner.getName());

            // Activity
            IPermissionActivity activity =
                    permissionOwnerDao.getPermissionActivity(
                            permission.getOwner(), permission.getActivity());
            Activity activityImpl = new ActivityImpl(permission.getActivity(), activity.getName());

            // Principal
            Principal principalImpl = new PrincipalImpl(authP.getKey(), authP.getPrincipalString());

            // Target
            Target targetImpl = null; // default
            IPermissionTargetProvider targetProvider =
                    targetProviderRegistry.getTargetProvider(activity.getTargetProviderKey());
            IPermissionTarget target = targetProvider.getTarget(permission.getTarget());
            if (target != null) {
                targetImpl = new TargetImpl(permission.getTarget(), target.getName());
            }

            rslt =
                    new AssignmentImpl(
                            ownerImpl, activityImpl, principalImpl, targetImpl, inherited);

        } catch (Exception e) {
            log.warn("Exception while adding permission", e);
        }

        return rslt;
    }
1058210
def create_badge_blueprint(allowed_types):
    
    from invenio_formatter.context_processors.badges import \
        generate_badge_png, generate_badge_svg

    blueprint = Blueprint(
        'invenio_formatter_badges',
        __name__,
        template_folder='templates',
    )

    @blueprint.route(
        '/badge/<any({0}):title>/<path:value>.<any(svg, png):ext>'.format(
            ', '.join(allowed_types)))
    def badge(title, value, ext='svg'):
        """Generate a badge response."""
        if ext == 'svg':
            generator = generate_badge_svg
            mimetype = 'image/svg+xml'
        elif ext == 'png':
            generator = generate_badge_png
            mimetype = 'image/png'

        badge_title_mapping = \
            current_app.config['FORMATTER_BADGES_TITLE_MAPPING'].get(
                title, title)
        response = Response(generator(badge_title_mapping, value),
                            mimetype=mimetype)
        # Generate Etag from badge title and value.
        hashable_badge = "{0}.{1}".format(badge_title_mapping,
                                          value).encode('utf-8')
        response.set_etag(hashlib.sha1(hashable_badge).hexdigest())
        # Add headers to prevent caching.
        response.headers["Pragma"] = "no-cache"
        response.cache_control.no_cache = True
        response.cache_control.max_age = \
            current_app.config['FORMATTER_BADGES_MAX_CACHE_AGE']
        response.last_modified = dt.utcnow()
        extra = timedelta(
            seconds=current_app.config['FORMATTER_BADGES_MAX_CACHE_AGE'])
        response.expires = response.last_modified + extra
        return response.make_conditional(request)

    return blueprint
74452
def ensure_permissions(mode_flags=stat.S_IWUSR):
    

    def decorator(f):
        def modify(filename, *args, **kwargs):
            m = chmod_perms(filename) if exists(filename) else mode_flags
            if not m & mode_flags:
                os.chmod(filename, m | mode_flags)
            try:
                return f(filename, *args, **kwargs)
            finally:
                # restore original permissions
                if not m & mode_flags:
                    os.chmod(filename, m)
        return modify

    return decorator
133916
function buildBastionSecurityGroup(sourceIp = '0.0.0.0/0', { name = 'BastionSecurityGroup' } = {}) {
  return {
    [name]: {
      Type: 'AWS::EC2::SecurityGroup',
      Properties: {
        GroupDescription: 'Bastion Host',
        VpcId: {
          Ref: 'VPC',
        },
        SecurityGroupIngress: [
          {
            Description: 'Allow inbound SSH access to the bastion host',
            IpProtocol: 'tcp',
            FromPort: 22,
            ToPort: 22,
            CidrIp: sourceIp,
          },
          {
            Description: 'Allow inbound ICMP to the bastion host',
            IpProtocol: 'icmp',
            FromPort: -1,
            ToPort: -1,
            CidrIp: sourceIp,
          },
        ],
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'bastion',
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
975426
def create_iam_role(self, account):
        
        try:
            iam = self.session.client('iam')
            trust = get_template('vpc_flow_logs_iam_role_trust.json').render()
            policy = get_template('vpc_flow_logs_role_policy.json').render()

            newrole = iam.create_role(
                Path='/',
                RoleName=self.role_name,
                AssumeRolePolicyDocument=trust
            )['Role']['Arn']

            # Attach an inline policy to the role to avoid conflicts or hitting the Managed Policy Limit
            iam.put_role_policy(
                RoleName=self.role_name,
                PolicyName='VpcFlowPolicy',
                PolicyDocument=policy
            )

            self.log.debug('Created VPC Flow Logs role & policy for {}'.format(account.account_name))
            auditlog(
                event='vpc_flow_logs.create_iam_role',
                actor=self.ns,
                data={
                    'account': account.account_name,
                    'roleName': self.role_name,
                    'trustRelationship': trust,
                    'inlinePolicy': policy
                }
            )
            return newrole

        except Exception:
            self.log.exception('Failed creating the VPC Flow Logs role for {}.'.format(account))
309385
def create(cls, name, sandbox_data_center, portal_username=None, comment=None):
        
        json = {
            'name': name,
            'sandbox_data_center': element_resolver(sandbox_data_center),
            'portal_username': portal_username if portal_username else '',
            'comment': comment}
        return ElementCreator(cls, json)
418940
def _create_security_group(self, ingress):
        
        template_kwargs = {
            'app': self.app_name,
            'env': self.env,
            'region': self.region,
            'vpc': get_vpc_id(self.env, self.region),
            'description': self.properties['security_group']['description'],
            'ingress': ingress,
        }

        secgroup_json = get_template(
            template_file='infrastructure/securitygroup_data.json.j2', formats=self.generated, **template_kwargs)

        wait_for_task(secgroup_json)
        return True
349347
def _create_svc_vm_hosting_devices(self, context, num, template):
        
        hosting_devices = []
        template_id = template['id']
        credentials_id = template['default_credentials_id']
        plugging_drv = self.get_hosting_device_plugging_driver(context,
                                                               template_id)
        hosting_device_drv = self.get_hosting_device_driver(context,
                                                            template_id)
        if plugging_drv is None or hosting_device_drv is None or num <= 0:
            return hosting_devices
        #TODO(bobmel): Determine value for max_hosted properly
        max_hosted = 1  # template['slot_capacity']
        dev_data, mgmt_context = self._get_resources_properties_for_hd(
            template, credentials_id)
        credentials_info = self._credentials.get(credentials_id)
        if credentials_info is None:
            LOG.error('Could not find credentials for hosting device'
                      'template %s. Aborting VM hosting device creation.',
                      template_id)
            return hosting_devices
        connectivity_info = self._get_mgmt_connectivity_info(
            context, self.mgmt_subnet_id())
        for i in range(num):
            complementary_id = uuidutils.generate_uuid()
            res = plugging_drv.create_hosting_device_resources(
                context, complementary_id, self.l3_tenant_id(), mgmt_context,
                max_hosted)
            if res.get('mgmt_port') is None:
                # Required ports could not be created
                return hosting_devices
            connectivity_info['mgmt_port'] = res['mgmt_port']
            vm_instance = self.svc_vm_mgr.dispatch_service_vm(
                context, template['name'] + '_nrouter', template['image'],
                template['flavor'], hosting_device_drv, credentials_info,
                connectivity_info, res.get('ports'))
            if vm_instance is not None:
                dev_data.update(
                    {'id': vm_instance['id'],
                     'complementary_id': complementary_id,
                     'management_ip_address': res['mgmt_port'][
                         'fixed_ips'][0]['ip_address'],
                     'management_port_id': res['mgmt_port']['id']})
                self.create_hosting_device(context,
                                           {'hosting_device': dev_data})
                hosting_devices.append(vm_instance)
            else:
                # Fundamental error like could not contact Nova
                # Cleanup anything we created
                plugging_drv.delete_hosting_device_resources(
                    context, self.l3_tenant_id(), **res)
                break
        LOG.info('Created %(num)d hosting device VMs based on template '
                 '%(t_id)s', {'num': len(hosting_devices),
                              't_id': template_id})
        return hosting_devices
63564
def create_default_access_for(permission_template:, workflow:)
        permission_template.access_grants.create(agent_type: 'group', agent_id: ::Ability.registered_group_name, access: Hyrax::PermissionTemplateAccess::DEPOSIT)
        deposit = Sipity::Role[Hyrax::RoleRegistry::DEPOSITING]
        workflow.update_responsibilities(role: deposit, agents: Hyrax::Group.new('registered'))
      end
186680
def create_stack_template(  self,
                                lambda_arn,
                                lambda_name,
                                api_key_required,
                                iam_authorization,
                                authorizer,
                                cors_options=None,
                                description=None,
                                endpoint_configuration=None
                            ):
        

        auth_type = "NONE"
        if iam_authorization and authorizer:
            logger.warn("Both IAM Authorization and Authorizer are specified, this is not possible. "
                        "Setting Auth method to IAM Authorization")
            authorizer = None
            auth_type = "AWS_IAM"
        elif iam_authorization:
            auth_type = "AWS_IAM"
        elif authorizer:
            auth_type = authorizer.get("type", "CUSTOM")

        # build a fresh template
        self.cf_template = troposphere.Template()
        self.cf_template.add_description('Automatically generated with Zappa')
        self.cf_api_resources = []
        self.cf_parameters = {}

        restapi = self.create_api_gateway_routes(
                                            lambda_arn,
                                            api_name=lambda_name,
                                            api_key_required=api_key_required,
                                            authorization_type=auth_type,
                                            authorizer=authorizer,
                                            cors_options=cors_options,
                                            description=description,
                                            endpoint_configuration=endpoint_configuration
                                        )
        return self.cf_template
1094355
def from_dict(cls, enclave):
        

        return Enclave(id=enclave.get('id'),
                       name=enclave.get('name'),
                       type=EnclaveType.from_string(enclave.get('type')))
193101
def from_dict(cls, data):
        
        auth_info = _AuthenticationInformation.from_dict(data.get("auth_info"))
        instance = cls(auth_info=auth_info)
        instance.user_id_hash_type = data.get("hash_type")
        instance.attributes = data.get("attributes", {})
        instance.user_id = data.get("user_id")
        instance.requester = data.get("requester")
        return instance
900393
def create(self, cidr_mask, description, **kwargs):
        
        return self._instance._client.acls.create(
            self._instance.name,
            cidr_mask,
            description,
            **kwargs
        )
223961
def create_event_permission(self, lambda_name, principal, source_arn):
        
        logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name))
        permission_response = self.lambda_client.add_permission(
            FunctionName=lambda_name,
            StatementId=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
            Action='lambda:InvokeFunction',
            Principal=principal,
            SourceArn=source_arn,
        )

        if permission_response['ResponseMetadata']['HTTPStatusCode'] != 201:
            print('Problem creating permission to invoke Lambda function')
            return None  # XXX: Raise?

        return permission_response