text:
<?php

namespace Utipd\CurrencyLib;

use Exception;

/*
* CurrencyUtil
*/
class CurrencyUtil
{

    const SATOSHI = 100000000;

    ////////////////////////////////////////////////////////////////////////

    public static function numberToSatoshis($number) {
        return intval(round($number * self::SATOSHI));
    }

    public static function satoshisToNumber($satoshis, $places=null) {
        if (!strlen($satoshis)) { return $satoshis; }
        if ($places === null) { $places = 8; }
        $out = number_format($satoshis / self::SATOSHI, $places);
        if (strpos($out, '.') !== false) {
            $out = rtrim($out, '0');
            $out = rtrim($out, '.');
        }

        return $out;
    }

    public static function satoshisToUnFormattedNumber($satoshis, $places=null) {
        if ($places === null) { $places = 8; }
        $out = round($satoshis / self::SATOSHI, $places);
        return $out;
    }

    public static function addTwigFilters($twig) {
        $filter = new \Twig_SimpleFilter('to_currency', function ($satoshis) {
            return CurrencyUtil::satoshisToNumber($satoshis);
        });
        $twig->addFilter($filter);

        return $twig;
    }

    ////////////////////////////////////////////////////////////////////////

}

redpajama_set_name: RedPajamaGithub


text:
package project

import (
	"golang.org/x/net/context"

	"github.com/docker/libcompose/project/events"
)

// Stop stops the specified services (like docker stop).
func (p *Project) Stop(ctx context.Context, timeout int, services ...string) error {
	return p.perform(events.ProjectStopStart, events.ProjectStopDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
		wrapper.Do(nil, events.ServiceStopStart, events.ServiceStop, func(service Service) error {
			return service.Stop(ctx, timeout)
		})
	}), nil)
}


text:
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/cloudfront/model/DistributionList.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace CloudFront
{
namespace Model
{
  /**
   * The returned result of the corresponding request.

See Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDFRONT_API ListDistributions2016_01_28Result
  {
  public:
    ListDistributions2016_01_28Result();
    ListDistributions2016_01_28Result(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    ListDistributions2016_01_28Result& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     * The DistributionList type.
     */
    inline const DistributionList& GetDistributionList() const{ return m_distributionList; }

    /**
     * The DistributionList type.
     */
    inline void SetDistributionList(const DistributionList& value) { m_distributionList = value; }

    /**
     * The DistributionList type.
     */
    inline void SetDistributionList(DistributionList&& value) { m_distributionList = std::move(value); }

    /**
     * The DistributionList type.
     */
    inline ListDistributions2016_01_28Result& WithDistributionList(const DistributionList& value) { SetDistributionList(value); return *this;}

    /**
     * The DistributionList type.
     */
    inline ListDistributions2016_01_28Result& WithDistributionList(DistributionList&& value) { SetDistributionList(std::move(value)); return *this;}

  private:
    DistributionList m_distributionList;
  };

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
package org.apache.isis.viewer.scimpi.dispatcher.view.action;

import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.profiles.Localization;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.consent.Consent;
import org.apache.isis.core.metamodel.facets.object.parseable.ParseableFacet;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.viewer.scimpi.dispatcher.AbstractElementProcessor;
import org.apache.isis.viewer.scimpi.dispatcher.context.RequestContext;
import org.apache.isis.viewer.scimpi.dispatcher.context.RequestContext.Scope;
import org.apache.isis.viewer.scimpi.dispatcher.processor.Request;
import org.apache.isis.viewer.scimpi.dispatcher.util.MethodsUtils;
import org.apache.isis.viewer.scimpi.dispatcher.view.HelpLink;

public class ActionButton extends AbstractElementProcessor {
    private static final Logger LOG = LoggerFactory.getLogger(ActionButton.class);

    // REVIEW: should provide this rendering context, rather than hardcoding.
    // the net effect currently is that class members annotated with
    // @Hidden(where=Where.ANYWHERE) or @Disabled(where=Where.ANYWHERE) will indeed
    // be hidden/disabled, but will be visible/enabled (perhaps incorrectly)
    // for any other value for Where
    private final static Where where = Where.ANYWHERE;

    @Override
    public void process(final Request request) {
        final String objectId = request.getOptionalProperty(OBJECT);
        final String methodName = request.getRequiredProperty(METHOD);
        final String forwardResultTo = request.getOptionalProperty(VIEW);
        final String forwardVoidTo = request.getOptionalProperty(VOID);
        final String forwardErrorTo = request.getOptionalProperty(ERROR);
        final String variable = request.getOptionalProperty(RESULT_NAME);
        final String scope = request.getOptionalProperty(SCOPE);
        final String buttonTitle = request.getOptionalProperty(BUTTON_TITLE);
        String resultOverride = request.getOptionalProperty(RESULT_OVERRIDE);
        final String idName = request.getOptionalProperty(ID, methodName);
        final String className = request.getOptionalProperty(CLASS);
        final boolean showMessage = request.isRequested(SHOW_MESSAGE, false);
        final String completionMessage = request.getOptionalProperty(MESSAGE);

        final ObjectAdapter object = MethodsUtils.findObject(request.getContext(), objectId);
        final String version = request.getContext().mapVersion(object);
        final ObjectAction action = MethodsUtils.findAction(object, methodName);

        final ActionContent parameterBlock = new ActionContent(action);
        request.setBlockContent(parameterBlock);
        request.processUtilCloseTag();
        final String[] parameters = parameterBlock.getParameters();
        final ObjectAdapter[] objectParameters;

        final ObjectAdapter target;
        if (false /*action.isContributed()*/) {
//            objectParameters= null;
//            System.arraycopy(parameters, 0, parameters, 1, parameters.length - 1);
//            parameters[0] = request.getContext().mapObject(object, Scope.REQUEST);
//            target =  action.realTarget(object);
//            if (!action.hasReturn() && resultOverride == null) {
//                resultOverride = parameters[0];
//            }
        } else {
            objectParameters = new ObjectAdapter[parameters.length];
            target = object;
            int i = 0;
            for (final ObjectActionParameter spec : action.getParameters()) {
                final ObjectSpecification type = spec.getSpecification();
                if (parameters[i] == null) {
                    objectParameters[i] = null;
                } else if (type.getFacet(ParseableFacet.class) != null) {
                    final ParseableFacet facet = type.getFacet(ParseableFacet.class);
                    Localization localization = IsisContext.getLocalization();
                    objectParameters[i] = facet.parseTextEntry(null, parameters[i], localization);
                } else {
                    objectParameters[i] = MethodsUtils.findObject(request.getContext(), parameters[i]);
                }
                i++;
            }
        }

        if (MethodsUtils.isVisibleAndUsable(object, action, where) && MethodsUtils.canRunMethod(object, action, objectParameters).isAllowed()) {
            // TODO use the form creation mechanism as used in ActionForm
            write(request, target, action, parameters, version, forwardResultTo, forwardVoidTo, forwardErrorTo, variable, scope, buttonTitle, completionMessage, resultOverride, idName, className);
        }

        if (showMessage) {
            final Consent usable = action.isUsable(IsisContext.getAuthenticationSession(), object, where);
            if (usable.isVetoed()) {
                final String notUsable = usable.getReason();
                if (notUsable != null) {
                    String title = buttonTitle == null ? action.getName() : buttonTitle;
                    disabledButton(request, title, notUsable, idName, className);
                }
            } else {
                final Consent valid = action.isProposedArgumentSetValid(object, objectParameters);
                final String notValid = valid.getReason();
                if (notValid != null) {
                    String title = buttonTitle == null ? action.getName() : buttonTitle;
                    disabledButton(request, title, notValid, idName, className);
                }
            }
        }

        request.popBlockContent();
    }

    private void disabledButton(final Request request, final String buttonTitle, String message, String id, String className) {
        if (className == null) {
            className = "access";
        }
        request.appendHtml("
");
        request.appendHtml("
" + buttonTitle);
        request.appendHtml("
");
        request.appendHtml("
");
    }

    public static void write(
            final Request request,
            final ObjectAdapter object,
            final ObjectAction action,
            final String[] parameters,
            final String version,
            String forwardResultTo,
            String forwardVoidTo,
            String forwardErrorTo,
            final String variable,
            final String scope,
            String buttonTitle,
            final String completionMessage,
            final String resultOverride,
            final String idName,
            final String className) {
        final RequestContext context = request.getContext();

        buttonTitle = buttonTitle != null ? buttonTitle : action.getName();

        if (action.isVisible(IsisContext.getAuthenticationSession(), object, where).isVetoed()) {
            LOG.info("action not visible " + action.getName());
            return;
        }
        final Consent usable = action.isUsable(IsisContext.getAuthenticationSession(), object, where);
        if (usable.isVetoed()) {
            LOG.info("action not available: " + usable.getReason());
            return;
        }

        /*
         *
         * TODO this mechanism fails as it tries to process tags - which we dont
         * need! Also it calls action 'edit' (not 'action'). Field[] fields =
         * new Field[0]; HiddenField[] hiddenFields = new HiddenField[] { new
         * HiddenField("service", serviceId), new HiddenField("method",
         * methodName), new HiddenField("view", forwardToView), variable == null
         * ? null : new HiddenField("variable", variable), };
         * Form.createForm(request, buttonTitle, fields, hiddenFields, false);
         */

        final String objectId = context.mapObject(object, Scope.INTERACTION);
        final String idSegment = idName == null ? "" : ("id=\"" + idName + "\" ");
        final String classSegment = "class=\"" + (className == null ? "action in-line" : className) + "\"";
        request.appendHtml("\n<form " + idSegment + classSegment + " action=\"action.app\" method=\"post\">\n");
        if (objectId == null) {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + OBJECT + "\" value=\"" + context.getVariable(RequestContext.RESULT) + "\" />\n");
        } else {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + OBJECT + "\" value=\"" +  StringEscapeUtils.escapeHtml(objectId) + "\" />\n");
        }
        request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + VERSION + "\" value=\"" + version + "\" />\n");
        if (scope != null) {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + SCOPE + "\" value=\"" + scope + "\" />\n");
        }
        request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + METHOD + "\" value=\"" + action.getId() + "\" />\n");
        if (forwardResultTo != null) {
            forwardResultTo = context.fullFilePath(forwardResultTo);
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + VIEW + "\" value=\"" + forwardResultTo + "\" />\n");
        }
        if (forwardErrorTo == null) {
            forwardErrorTo = request.getContext().getResourceFile();
        }
        forwardErrorTo = context.fullFilePath(forwardErrorTo);
        request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + ERROR + "\" value=\"" + forwardErrorTo + "\" />\n");
        if (forwardVoidTo == null) {
            forwardVoidTo = request.getContext().getResourceFile();
        }
        forwardVoidTo = context.fullFilePath(forwardVoidTo);
        request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + VOID + "\" value=\"" + forwardVoidTo + "\" />\n");
        if (variable != null) {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + RESULT_NAME + "\" value=\"" + variable + "\" />\n");
        }
        if (resultOverride != null) {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + RESULT_OVERRIDE + "\" value=\"" + resultOverride + "\" />\n");
        }
        if (completionMessage != null) {
            request.appendHtml("  <input type=\"hidden\" name=\"" + "_" + MESSAGE + "\" value=\"" + completionMessage + "\" />\n");
        }

        for (int i = 0; i < parameters.length; i++) {
            request.appendHtml("  <input type=\"hidden\" name=\"param" + (i + 1) + "\" value=\"" + parameters[i] + "\" />\n");
        }
        request.appendHtml(request.getContext().interactionFields());
        request.appendHtml("  <input class=\"button\" type=\"submit\" value=\"" + buttonTitle + "\" name=\"execute\" title=\"" + action.getDescription() + "\" />");
        HelpLink.append(request, action.getDescription(), action.getHelp());
        request.appendHtml("\n</form>\n");
    }

    @Override
    public String getName() {
        return "action-button";
    }

}


text:
import uuid

from oslo_log import log as logging
from oslo_utils import units

from cinder import context
from cinder import db
from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder.volume import driver
from cinder.volume.drivers.nexenta.ns5 import jsonrpc
from cinder.volume.drivers.nexenta import options
from cinder.volume.drivers.nexenta import utils

VERSION = '1.1.0'
LOG = logging.getLogger(__name__)
TARGET_GROUP_PREFIX = 'cinder-tg-'

@interface.volumedriver
class NexentaISCSIDriver(driver.ISCSIDriver):
    """Executes volume driver commands on Nexenta Appliance.

    .. code-block:: default

      Version history:
          1.0.0 - Initial driver version.
          1.1.0 - Added HTTPS support.
                  Added use of sessions for REST calls.

    """

    VERSION = VERSION

    # ThirdPartySystems wiki page
    CI_WIKI_NAME = "Nexenta_CI"

    def __init__(self, *args, **kwargs):
        super(NexentaISCSIDriver, self).__init__(*args, **kwargs)
        self.nef = None
        # mapping of targets and groups. Groups are the keys
        self.targets = {}
        # list of volumes in target group. Groups are the keys
        self.volumes = {}
        if self.configuration:
            self.configuration.append_config_values(
                options.NEXENTA_CONNECTION_OPTS)
            self.configuration.append_config_values(
                options.NEXENTA_ISCSI_OPTS)
            self.configuration.append_config_values(
                options.NEXENTA_DATASET_OPTS)
            self.configuration.append_config_values(
                options.NEXENTA_RRMGR_OPTS)
        self.use_https = self.configuration.nexenta_use_https
        self.nef_host = self.configuration.nexenta_host
        self.nef_port = self.configuration.nexenta_rest_port
        self.nef_user = self.configuration.nexenta_user
        self.nef_password = self.configuration.nexenta_password
        self.storage_pool = self.configuration.nexenta_volume
        self.volume_group = self.configuration.nexenta_volume_group
        self.dataset_compression = (
            self.configuration.nexenta_dataset_compression)
        self.dataset_deduplication = self.configuration.nexenta_dataset_dedup
        self.dataset_description = (
            self.configuration.nexenta_dataset_description)
        self.iscsi_target_portal_port = (
            self.configuration.nexenta_iscsi_target_portal_port)

    @property
    def backend_name(self):
        backend_name = None
        if self.configuration:
            backend_name = self.configuration.safe_get('volume_backend_name')
        if not backend_name:
            backend_name = self.__class__.__name__
        return backend_name

    def do_setup(self, context):
        self.nef = jsonrpc.NexentaJSONProxy(
            self.nef_host, self.nef_port, self.nef_user,
            self.nef_password, self.use_https)
        url = 'storage/pools/%s/volumeGroups' % self.storage_pool
        data = {
            'name': self.volume_group,
            'volumeBlockSize': (
                self.configuration.nexenta_ns5_blocksize * units.Ki)
        }
        try:
            self.nef.post(url, data)
        except exception.NexentaException as e:
            if 'EEXIST' in e.args[0]:
                LOG.debug('volumeGroup already exists, skipping')
            else:
                raise

        self._fetch_volumes()

    def _fetch_volumes(self):
        url = 'san/iscsi/targets?fields=alias,name&limit=50000'
        for target in self.nef.get(url)['data']:
            tg_name = target['alias']
            if tg_name.startswith(TARGET_GROUP_PREFIX):
                self.targets[tg_name] = target['name']
                self._fill_volumes(tg_name)

    def check_for_setup_error(self):
        """Verify that the zfs volumes exist.

        :raise: :py:exc:`LookupError`
        """
        url = 'storage/pools/%(pool)s/volumeGroups/%(group)s' % {
            'pool': self.storage_pool,
            'group': self.volume_group,
        }
        try:
            self.nef.get(url)
        except exception.NexentaException:
            raise LookupError(_(
                "Dataset group %s not found at Nexenta SA"), '/'.join(
                [self.storage_pool, self.volume_group]))
        services = self.nef.get('services')
        for service in services['data']:
            if service['name'] == 'iscsit':
                if service['state'] != 'online':
                    raise exception.NexentaException(
                        'iSCSI service is not running on NS appliance')
                break

    def _get_volume_path(self, volume):
        """Return zfs volume name that corresponds given volume name."""
        return '%s/%s/%s' % (self.storage_pool, self.volume_group,
                             volume['name'])

    @staticmethod
    def _get_clone_snapshot_name(volume):
        """Return name for snapshot that will be used to clone the volume."""
        return 'cinder-clone-snapshot-%(id)s' % volume

    def create_volume(self, volume):
        """Create a zfs volume on appliance.

        :param volume: volume reference
        :return: model update dict for volume reference
        """
        url = 'storage/pools/%(pool)s/volumeGroups/%(group)s/volumes' % {
            'pool': self.storage_pool,
            'group': self.volume_group,
        }
        data = {
            'name': volume['name'],
            'volumeSize': volume['size'] * units.Gi,
            'volumeBlockSize': (
                self.configuration.nexenta_ns5_blocksize * units.Ki),
            'sparseVolume': self.configuration.nexenta_sparse
        }
        self.nef.post(url, data)

    def delete_volume(self, volume):
        """Destroy a zfs volume on appliance.

        :param volume: volume reference
        """

        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s'
               '/volumes/%(name)s') % {
            'pool': self.storage_pool,
            'group': self.volume_group,
            'name': volume['name']
        }
        try:
            self.nef.delete(url)
        except exception.NexentaException as exc:
            # We assume that volume is gone
            LOG.warning('Got error trying to delete volume %(volume)s,'
                        ' assuming it is already gone: %(exc)s',
                        {'volume': volume, 'exc': exc})

    def extend_volume(self, volume, new_size):
        """Extend an existing volume.

        :param volume: volume reference
        :param new_size: volume new size in GB
        """
        LOG.info('Extending volume: %(id)s New size: %(size)s GB',
                 {'id': volume['id'], 'size': new_size})
        pool, group, name = self._get_volume_path(volume).split('/')
        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s/'
               'volumes/%(name)s') % {
            'pool': pool,
            'group': group,
            'name': name
        }
        self.nef.put(url, {'volumeSize': new_size * units.Gi})

    def create_snapshot(self, snapshot):
        """Creates a snapshot.

        :param snapshot: snapshot reference
        """
        snapshot_vol = self._get_snapshot_volume(snapshot)
        LOG.info('Creating snapshot %(snap)s of volume %(vol)s', {
            'snap': snapshot['name'],
            'vol': snapshot_vol['name']
        })
        volume_path = self._get_volume_path(snapshot_vol)
        pool, group, volume = volume_path.split('/')
        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s/'
               'volumes/%(volume)s/snapshots') % {
            'pool': pool,
            'group': group,
            'volume': snapshot_vol['name']
        }
        self.nef.post(url, {'name': snapshot['name']})

    def delete_snapshot(self, snapshot):
        """Delete volume's snapshot on appliance.

        :param snapshot: snapshot reference
        """
        LOG.info('Deleting snapshot: %s', snapshot['name'])
        snapshot_vol = self._get_snapshot_volume(snapshot)
        volume_path = self._get_volume_path(snapshot_vol)
        pool, group, volume = volume_path.split('/')
        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s/'
               'volumes/%(volume)s/snapshots/%(snapshot)s') % {
            'pool': pool,
            'group': group,
            'volume': volume,
            'snapshot': snapshot['name']
        }
        try:
            self.nef.delete(url)
        except exception.NexentaException as exc:
            if 'EBUSY' in exc.args[0]:
                LOG.warning(
                    'Could not delete snapshot %s - it has dependencies',
                    snapshot['name'])
            else:
                LOG.warning(exc)

    def create_volume_from_snapshot(self, volume, snapshot):
        """Create new volume from other's snapshot on appliance.

        :param volume: reference of volume to be created
        :param snapshot: reference of source snapshot
        """
        LOG.info('Creating volume from snapshot: %s', snapshot['name'])
        snapshot_vol = self._get_snapshot_volume(snapshot)
        volume_path = self._get_volume_path(snapshot_vol)
        pool, group, snapshot_vol = volume_path.split('/')
        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s/'
               'volumes/%(volume)s/snapshots/%(snapshot)s/clone') % {
            'pool': pool,
            'group': group,
            'volume': snapshot_vol,
            'snapshot': snapshot['name']
        }
        self.nef.post(url, {'targetPath': self._get_volume_path(volume)})
        if (('size' in volume) and (
                volume['size'] > snapshot['volume_size'])):
            self.extend_volume(volume, volume['size'])

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume.

        :param volume: new volume reference
        :param src_vref: source volume reference
        """
        snapshot = {'volume_name': src_vref['name'],
                    'volume_id': src_vref['id'],
                    'volume_size': src_vref['size'],
                    'name': self._get_clone_snapshot_name(volume)}
        LOG.debug('Creating temp snapshot of the original volume: '
                  '%s@%s', snapshot['volume_name'], snapshot['name'])
        self.create_snapshot(snapshot)
        try:
            self.create_volume_from_snapshot(volume, snapshot)
        except exception.NexentaException:
            LOG.error('Volume creation failed, deleting created snapshot %s',
                      '@'.join([snapshot['volume_name'], snapshot['name']]))
            try:
                self.delete_snapshot(snapshot)
            except (exception.NexentaException, exception.SnapshotIsBusy):
                LOG.warning('Failed to delete zfs snapshot %s',
                            '@'.join([snapshot['volume_name'],
                                      snapshot['name']]))
            raise

    def _get_snapshot_volume(self, snapshot):
        ctxt = context.get_admin_context()
        return db.volume_get(ctxt, snapshot['volume_id'])

    def _do_export(self, _ctx, volume):
        """Do all steps to get zfs volume exported at separate target.

        :param volume: reference of volume to be exported
        """
        volume_path = self._get_volume_path(volume)

        # Find out whether the volume is exported
        vol_map_url = 'san/lunMappings?volume=%s&fields=lun' % (
            volume_path.replace('/', '%2F'))
        data = self.nef.get(vol_map_url).get('data')
        if data:
            model_update = {}
        else:
            # Choose the best target group among existing ones
            tg_name = None
            for tg in self.volumes.keys():
                if len(self.volumes[tg]) < 20:
                    tg_name = tg
                    break
            if tg_name:
                target_name = self.targets[tg_name]
            else:
                tg_name = TARGET_GROUP_PREFIX + uuid.uuid4().hex

                # Create new target
                url = 'san/iscsi/targets'
                data = {
                    "portals": [
                        {"address": self.nef_host}
                    ],
                    'alias': tg_name
                }
                self.nef.post(url, data)

                # Get the name of just created target
                data = self.nef.get(
                    '%(url)s?fields=name&alias=%(tg_name)s' % {
                        'url': url,
                        'tg_name': tg_name
                    })['data']
                target_name = data[0]['name']

                self._create_target_group(tg_name, target_name)

                self.targets[tg_name] = target_name
                self.volumes[tg_name] = set()

            # Export the volume
            url = 'san/lunMappings'
            data = {
                "hostGroup": "all",
                "targetGroup": tg_name,
                'volume': volume_path
            }
            try:
                self.nef.post(url, data)
                self.volumes[tg_name].add(volume_path)
            except exception.NexentaException as e:
                if 'No such target group' in e.args[0]:
                    self._create_target_group(tg_name, target_name)
                    self._fill_volumes(tg_name)
                    self.nef.post(url, data)
                else:
                    raise

            # Get LUN of just created volume
            data = self.nef.get(vol_map_url).get('data')
            lun = data[0]['lun']

            provider_location = '%(host)s:%(port)s,1 %(name)s %(lun)s' % {
                'host': self.nef_host,
                'port': self.configuration.nexenta_iscsi_target_portal_port,
                'name': target_name,
                'lun': lun,
            }
            model_update = {'provider_location': provider_location}
        return model_update

    def create_export(self, _ctx, volume, connector):
        """Create new export for zfs volume.

        :param volume: reference of volume to be exported
        :return: iscsiadm-formatted provider location string
        """
        model_update = self._do_export(_ctx, volume)
        return model_update

    def ensure_export(self, _ctx, volume):
        """Recreate parts of export if necessary.

        :param volume: reference of volume to be exported
        """
        self._do_export(_ctx, volume)

    def remove_export(self, _ctx, volume):
        """Destroy all resources created to export zfs volume.

        :param volume: reference of volume to be unexported
        """
        volume_path = self._get_volume_path(volume)

        # Get ID of a LUN mapping if the volume is exported
        url = 'san/lunMappings?volume=%s&fields=id' % (
            volume_path.replace('/', '%2F'))
        data = self.nef.get(url)['data']
        if data:
            url = 'san/lunMappings/%s' % data[0]['id']
            self.nef.delete(url)
        else:
            LOG.debug('LU already deleted from appliance')

        for tg in self.volumes:
            if volume_path in self.volumes[tg]:
                self.volumes[tg].remove(volume_path)
                break

    def get_volume_stats(self, refresh=False):
        """Get volume stats.

        If 'refresh' is True, run update the stats first.
        """
        if refresh:
            self._update_volume_stats()

        return self._stats

    def _update_volume_stats(self):
        """Retrieve stats info for NexentaStor appliance."""
        LOG.debug('Updating volume stats')

        url = ('storage/pools/%(pool)s/volumeGroups/%(group)s'
               '?fields=bytesAvailable,bytesUsed') % {
            'pool': self.storage_pool,
            'group': self.volume_group,
        }
        stats = self.nef.get(url)
        total_amount = utils.str2gib_size(stats['bytesAvailable'])
        free_amount = utils.str2gib_size(
            stats['bytesAvailable'] - stats['bytesUsed'])

        location_info = '%(driver)s:%(host)s:%(pool)s/%(group)s' % {
            'driver': self.__class__.__name__,
            'host': self.nef_host,
            'pool': self.storage_pool,
            'group': self.volume_group,
        }
        self._stats = {
            'vendor_name': 'Nexenta',
            'dedup': self.dataset_deduplication,
            'compression': self.dataset_compression,
            'description': self.dataset_description,
            'driver_version': self.VERSION,
            'storage_protocol': 'iSCSI',
            'total_capacity_gb': total_amount,
            'free_capacity_gb': free_amount,
            'reserved_percentage': self.configuration.reserved_percentage,
            'QoS_support': False,
            'volume_backend_name': self.backend_name,
            'location_info': location_info,
            'iscsi_target_portal_port': self.iscsi_target_portal_port,
            'nef_url': self.nef.url
        }

    def _fill_volumes(self, tg_name):
        url = ('san/lunMappings?targetGroup=%s&fields=volume'
               '&limit=50000' % tg_name)
        self.volumes[tg_name] = {
            mapping['volume'] for mapping in self.nef.get(url)['data']}

    def _create_target_group(self, tg_name, target_name):
        # Create new target group
        url = 'san/targetgroups'
        data = {
            'name': tg_name,
            'members': [target_name]
        }
        self.nef.post(url, data)


text:
topic: "Parse Data Python "
desc: " An Example Script"
---

```python
import urllib

def parseData(fname):
    for l in urllib.urlopen(fname):
        yield eval(l)

print "Reading Data..."
gen = parseData("http://cses.ucsd.edu/spis/reviews_CDs_and_Vinyl_5.json")
data = []
for i in range(5000):
  data.append(gen.next())
print "done"
```


text:
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.checks.coding;

import java.util.ArrayDeque;
import java.util.Deque;

import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck;

/**
 *

 * Restricts the number of return statements in methods, constructors and lambda expressions
 * (2 by default). Ignores specified methods ({@code equals()} by default).
 *

 *

 * Rationale: Too many return points can be indication that code is
 * attempting to do too much or may be difficult to understand.
 *

 *
 * @author Simon Harris
 */
public final class ReturnCountCheck extends AbstractFormatCheck {

    /**
     * A key is pointing to the warning message text in "messages.properties"
     * file.
     */
    public static final String MSG_KEY = "return.count";

    /** Default allowed number of return statements. */
    private static final int DEFAULT_MAX = 2;

    /** Stack of method contexts. */
    private final Deque<Context> contextStack = new ArrayDeque<>();
    /** Maximum allowed number of return stmts. */
    private int max;
    /** Current method context. */
    private Context context;

    /** Creates new instance of the checks. */
    public ReturnCountCheck() {
        super("^equals$");
        max = DEFAULT_MAX;
    }

    @Override
    public int[] getDefaultTokens() {
        return new int[] {
            TokenTypes.CTOR_DEF,
            TokenTypes.METHOD_DEF,
            TokenTypes.LAMBDA,
            TokenTypes.LITERAL_RETURN,
        };
    }

    @Override
    public int[] getRequiredTokens() {
        return new int[]{
            TokenTypes.LITERAL_RETURN,
        };
    }

    @Override
    public int[] getAcceptableTokens() {
        return new int[] {
            TokenTypes.CTOR_DEF,
            TokenTypes.METHOD_DEF,
            TokenTypes.LAMBDA,
            TokenTypes.LITERAL_RETURN,
        };
    }

    /**
     * Getter for max property.
     * @return maximum allowed number of return statements.
     */
    public int getMax() {
        return max;
    }

    /**
     * Setter for max property.
     * @param max maximum allowed number of return statements.
     */
    public void setMax(int max) {
        this.max = max;
    }

    @Override
    public void beginTree(DetailAST rootAST) {
        context = new Context(false);
        contextStack.clear();
    }

    @Override
    public void visitToken(DetailAST ast) {
        switch (ast.getType()) {
            case TokenTypes.CTOR_DEF:
            case TokenTypes.METHOD_DEF:
                visitMethodDef(ast);
                break;
            case TokenTypes.LAMBDA:
                visitLambda();
                break;
            case TokenTypes.LITERAL_RETURN:
                context.visitLiteralReturn();
                break;
            default:
                throw new IllegalStateException(ast.toString());
        }
    }

    @Override
    public void leaveToken(DetailAST ast) {
        switch (ast.getType()) {
            case TokenTypes.CTOR_DEF:
            case TokenTypes.METHOD_DEF:
            case TokenTypes.LAMBDA:
                leave(ast);
                break;
            case TokenTypes.LITERAL_RETURN:
                // Do nothing
                break;
            default:
                throw new IllegalStateException(ast.toString());
        }
    }

    /**
     * Creates new method context and places old one on the stack.
     * @param ast method definition for check.
     */
    private void visitMethodDef(DetailAST ast) {
        contextStack.push(context);
        final DetailAST methodNameAST = ast.findFirstToken(TokenTypes.IDENT);
        final boolean check = !getRegexp().matcher(methodNameAST.getText()).find();
        context = new Context(check);
    }

    /**
     * Checks number of return statements and restore previous context.
     * @param ast node to leave.
     */
    private void leave(DetailAST ast) {
        context.checkCount(ast);
        context = contextStack.pop();
    }

    /**
     * Creates new lambda context and places old one on the stack.
     */
    private void visitLambda() {
        contextStack.push(context);
        context = new Context(true);
    }

    /**
     * Class to encapsulate information about one method.
     * @author Simon Harris
     */
    private class Context {
        /** Whether we should check this method or not. */
        private final boolean checking;
        /** Counter for return statements. */
        private int count;

        /**
         * Creates new method context.
         * @param checking should we check this method or not.
         */
        Context(boolean checking) {
            this.checking = checking;
            count = 0;
        }

        /** Increase number of return statements. */
        public void visitLiteralReturn() {
            ++count;
        }

        /**
         * Checks if number of return statements in method more
         * than allowed.
         * @param ast method def associated with this context.
         */
        public void checkCount(DetailAST ast) {
            if (checking && count > getMax()) {
                log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY,
                    count, getMax());
            }
        }
    }
}


text:
package com.github.seanroy.plugins;

import static com.amazonaws.services.lambda.model.EventSourcePosition.LATEST;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;

import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.services.cloudwatchevents.model.DeleteRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleResult;
import com.amazonaws.services.cloudwatchevents.model.ListRuleNamesByTargetRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleResult;
import com.amazonaws.services.cloudwatchevents.model.PutTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.RemoveTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.Target;
import com.amazonaws.services.dynamodbv2.model.DescribeStreamRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsResult;
import com.amazonaws.services.dynamodbv2.model.Stream;
import com.amazonaws.services.dynamodbv2.model.StreamDescription;
import com.amazonaws.services.lambda.model.AddPermissionRequest;
import com.amazonaws.services.lambda.model.AddPermissionResult;
import com.amazonaws.services.lambda.model.AliasConfiguration;
import com.amazonaws.services.lambda.model.CreateAliasRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.DeleteEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.Environment;
import com.amazonaws.services.lambda.model.EventSourceMappingConfiguration;
import com.amazonaws.services.lambda.model.EventSourcePosition;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.GetFunctionRequest;
import com.amazonaws.services.lambda.model.GetFunctionResult;
import com.amazonaws.services.lambda.model.GetPolicyRequest;
import com.amazonaws.services.lambda.model.GetPolicyResult;
import com.amazonaws.services.lambda.model.ListAliasesRequest;
import com.amazonaws.services.lambda.model.ListAliasesResult;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult;
import com.amazonaws.services.lambda.model.RemovePermissionRequest;
import com.amazonaws.services.lambda.model.ResourceNotFoundException;
import com.amazonaws.services.lambda.model.UpdateAliasRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest;
import com.amazonaws.services.lambda.model.VpcConfig;
import com.amazonaws.services.lambda.model.VpcConfigResponse;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.ListSubscriptionsResult;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.SubscribeResult;
import com.amazonaws.services.sns.model.Subscription;
import com.amazonaws.services.sns.model.UnsubscribeRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.GetQueueUrlResult;
import com.amazonaws.services.sqs.model.QueueAttributeName;

/**
 * I am a deploy mojo responsible to upload and create or update lambda function in AWS.
 *
 * @author Sean N. Roy, Sean Roy 11/08/16.
 */
@Mojo(name = "deploy-lambda")
public class DeployLambdaMojo extends AbstractLambdaMojo {

    @Override
    public void execute() throws MojoExecutionException {
        if(checkSkip()) return;
        super.execute();
        try {
            uploadJarToS3();
            lambdaFunctions.stream().map(f -> {
                getLog().info("---- Create or update " + f.getFunctionName() + " -----");
                return f;
            }).forEach(lf ->
                getFunctionPolicy
                    .andThen(cleanUpOrphans)
                    .andThen(createOrUpdate)
                    .apply(lf));
        } catch (Exception e) {
            getLog().error("Error during processing", e);
            throw new MojoExecutionException(e.getMessage());
        }
    }

    private boolean shouldUpdate(LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult) {
    	if (ObjectUtils.defaultIfNull(forceUpdate, StringUtils.containsIgnoreCase(version, "SNAPSHOT"))) {
            getLog().info("Forcing update for " + lambdaFunction.getFunctionName());
            return true;
        }
        if (isConfigurationChanged(lambdaFunction, getFunctionResult)) {
        	return true;
        }
        getLog().info("Config hasn't changed for " + lambdaFunction.getFunctionName());
        return false;
    }

    /*
     *  Get the existing policy function (on updates) and assign it to the lambdaFunction.
     */
    private Function<LambdaFunction, LambdaFunction> getFunctionPolicy = (LambdaFunction lambdaFunction) -> {
        try {
            lambdaFunction.setExistingPolicy(Policy.fromJson(lambdaClient.getPolicy(new GetPolicyRequest()
                .withFunctionName(lambdaFunction.getFunctionName())
                .withQualifier(lambdaFunction.getQualifier())).getPolicy()));
        } catch (ResourceNotFoundException rnfe3) {
            getLog().debug("Probably creating a new function, policy doesn't exist yet: " + rnfe3.getMessage());
        }

        return lambdaFunction;
    };

    private Function<LambdaFunction, LambdaFunction> updateFunctionConfig = (LambdaFunction lambdaFunction) -> {
        getLog().info("About to update functionConfig for " + lambdaFunction.getFunctionName());
        UpdateFunctionConfigurationRequest updateFunctionRequest = new UpdateFunctionConfigurationRequest()
                .withFunctionName(lambdaFunction.getFunctionName())
                .withDescription(lambdaFunction.getDescription())
                .withHandler(lambdaFunction.getHandler())
                .withRole(lambdaFunction.getLambdaRoleArn())
                .withTimeout(lambdaFunction.getTimeout())
                .withMemorySize(lambdaFunction.getMemorySize())
                .withRuntime(runtime)
                .withVpcConfig(getVpcConfig(lambdaFunction))
                .withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));
        lambdaClient.updateFunctionConfiguration(updateFunctionRequest);
        return lambdaFunction;
    };

    private Function<LambdaFunction, LambdaFunction> createOrUpdateAliases = (LambdaFunction lambdaFunction) -> {
        lambdaFunction.getAliases().forEach(alias -> {
            UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest()
                    .withFunctionName(lambdaFunction.getFunctionName())
                    .withFunctionVersion(lambdaFunction.getVersion())
                    .withName(alias);
            try {
                lambdaClient.updateAlias(updateAliasRequest
                        );
                getLog().info("Alias " + alias + " updated for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
            } catch (ResourceNotFoundException ignored) {
                CreateAliasRequest createAliasRequest = new CreateAliasRequest()
                        .withFunctionName(lambdaFunction.getFunctionName())
                        .withFunctionVersion(lambdaFunction.getVersion())
                        .withName(alias);
                lambdaClient.createAlias(createAliasRequest);
                getLog().info("Alias " + alias + " created for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
            }
        });
        return lambdaFunction;
    };

    private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateSNSTopicSubscription = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getSNSTopic());
        CreateTopicRequest createTopicRequest = new CreateTopicRequest()
                .withName(trigger.getSNSTopic());
        CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
        getLog().info("Topic " + createTopicResult.getTopicArn() + " created");

        SubscribeRequest subscribeRequest = new SubscribeRequest()
                .withTopicArn(createTopicResult.getTopicArn())
                .withEndpoint(lambdaFunction.getUnqualifiedFunctionArn())
                .withProtocol("lambda");
        SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
        getLog().info("Lambda function " + lambdaFunction.getFunctionName() + " subscribed to " + createTopicResult.getTopicArn());
        getLog().info("Created " + trigger.getIntegration() + " trigger " + subscribeResult.getSubscriptionArn());

        Optional<Statement> statementOpt;
        try {
            GetPolicyRequest getPolicyRequest = new GetPolicyRequest()
                    .withFunctionName(lambdaFunction.getFunctionName());
            GetPolicyResult GetPolicyResult = lambdaClient.getPolicy(getPolicyRequest);
            statementOpt = Policy.fromJson(GetPolicyResult.getPolicy()).getStatements().stream()
                                                     .filter(statement -> statement.getActions().stream().anyMatch(e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
                                                             statement.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
                                                             statement.getConditions().stream().anyMatch(condition -> condition.getValues().stream().anyMatch(s -> Objects.equals(createTopicResult.getTopicArn(), s)))
                                                     ).findAny();
        } catch (ResourceNotFoundException ignored) {
            // no policy found
            statementOpt = empty();
        }

        if (!statementOpt.isPresent()) {
            AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
                    .withAction(PERM_LAMBDA_INVOKE)
                    .withPrincipal(PRINCIPAL_SNS)
                    .withSourceArn(createTopicResult.getTopicArn())
                    .withFunctionName(lambdaFunction.getFunctionName())
                    .withStatementId(UUID.randomUUID().toString());
            AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
            getLog().debug("Added permission to lambda function " + addPermissionResult.toString());
        }
        return trigger;
    };

    /**
     * TODO: Much of this code can be factored out into an addPermission function.
     */
    private BiFunction<Trigger, LambdaFunction, Trigger> addAlexaSkillsKitPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
                s.getId().equals(getAlexaPermissionStatementId()))) {
            getLog().info("Granting invoke permission to " + trigger.getIntegration());
            AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
                    .withAction(PERM_LAMBDA_INVOKE)
                    .withPrincipal(PRINCIPAL_ALEXA)
                    .withFunctionName(lambdaFunction.getFunctionName())
                    .withQualifier(lambdaFunction.getQualifier())
                    .withStatementId(getAlexaPermissionStatementId())
                    .withEventSourceToken(trigger.getAlexaSkillId());

            AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
        }

        return trigger;
    };
    private String getAlexaPermissionStatementId() {
        return "lambda-maven-plugin-alexa-" + regionName + "-permission";
    }

    /**
     * TODO: Much of this code can be factored out into an addPermission function.
     */
    private BiFunction<Trigger, LambdaFunction, Trigger> addLexPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
                 s.getId().equals(getLexPermissionStatementId(trigger.getLexBotName())))) {
            getLog().info("Granting invoke permission to Lex bot " + trigger.getLexBotName());
            AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
                .withAction(PERM_LAMBDA_INVOKE)
                .withPrincipal(PRINCIPAL_LEX)
                .withFunctionName(lambdaFunction.getFunctionName())
                .withQualifier(lambdaFunction.getQualifier())
                .withStatementId(getLexPermissionStatementId(trigger.getLexBotName()));

            AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
        }
        return trigger;
    };
    private String getLexPermissionStatementId(String botName) {
        return "lambda-maven-plugin-lex-" + regionName + "-permission-" + botName;
    }

    private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateScheduledRule = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        // TODO: I hate that these checks are done twice, but for the time being it beats updates that just didn't work.
        if ( isScheduleRuleChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction)) {
            getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getRuleName());
            PutRuleRequest putRuleRequest = new PutRuleRequest()
                    .withName(trigger.getRuleName())
                    .withDescription(trigger.getRuleDescription())
                    .withScheduleExpression(trigger.getScheduleExpression());
            PutRuleResult putRuleResult = eventsClient.putRule(putRuleRequest);
            getLog().info("Created " + trigger.getIntegration() + " trigger " + putRuleResult.getRuleArn());

            AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
                    .withAction(PERM_LAMBDA_INVOKE)
                    .withPrincipal(PRINCIPAL_EVENTS)
                    .withSourceArn(putRuleResult.getRuleArn())
                    .withFunctionName(lambdaFunction.getFunctionName())
                    .withStatementId(UUID.randomUUID().toString());
            AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
            getLog().debug("Added permission to lambda function " + addPermissionResult.toString());

            PutTargetsRequest putTargetsRequest = new PutTargetsRequest()
                    .withRule(trigger.getRuleName())
                    .withTargets(new Target().withId("1").withArn(lambdaFunction.getUnqualifiedFunctionArn()));
            eventsClient.putTargets(putTargetsRequest);
        }
        return trigger;
    };

    private Function<LambdaFunction, LambdaFunction> createOrUpdateKeepAlive = (LambdaFunction lambdaFunction) -> {
        if (isKeepAliveChanged(lambdaFunction)) {
            ofNullable(lambdaFunction.getKeepAlive()).flatMap(f -> {
               if ( f > 0 ) {
                   getLog().info("Setting keepAlive to " + f + " minutes.");

                   createOrUpdateScheduledRule.apply(new Trigger()
                       .withIntegration("Function Keep Alive")
                       .withDescription(String.format("This feature pings function %s every %d %s.",
                                                       lambdaFunction.getFunctionName(), f,
                                                       f > 1 ? "minutes" : "minute"))
                       .withRuleName(lambdaFunction.getKeepAliveRuleName())
                       .withScheduleExpression(lambdaFunction.getKeepAliveScheduleExpression()),
                       lambdaFunction);
               }

               return Optional.of(f);
            });
        }
        return lambdaFunction;
    };

    private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateDynamoDBTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getDynamoDBTable());
        ListStreamsRequest listStreamsRequest = new ListStreamsRequest().withTableName(trigger.getDynamoDBTable());
        ListStreamsResult listStreamsResult = dynamoDBStreamsClient.listStreams(listStreamsRequest);

        String streamArn = listStreamsResult.getStreams().stream()
                                            .filter(s -> Objects.equals(trigger.getDynamoDBTable(), s.getTableName()))
                                            .findFirst()
                                            .map(Stream::getStreamArn)
                                            .orElseThrow(() -> new IllegalArgumentException("Unable to find stream for table " + trigger.getDynamoDBTable()));

        return findorUpdateMappingConfiguration(trigger, lambdaFunction, streamArn);
    };

    private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateSQSTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getStandardQueue());
        String queueArn = null;

        Optional<GetQueueUrlResult> getQueueUrlOptionalResult = ofNullable(sqsClient.getQueueUrl(new GetQueueUrlRequest()
    			.withQueueName(trigger.getStandardQueue())));

        if (getQueueUrlOptionalResult.isPresent()) {
        	String queueUrl = getQueueUrlOptionalResult.get().getQueueUrl();
			GetQueueAttributesResult getQueueAttributesResult = sqsClient.getQueueAttributes( new GetQueueAttributesRequest()
	    			.withQueueUrl(queueUrl).withAttributeNames(QueueAttributeName.QueueArn));

	    	queueArn = getQueueAttributesResult.getAttributes().get(QueueAttributeName.QueueArn.name());

        } else {
        	throw new IllegalArgumentException("Unable to find queue " + trigger.getStandardQueue());
        }

        return findorUpdateMappingConfiguration(trigger, lambdaFunction, queueArn);
    };

    private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateKinesisStream = (Trigger trigger, LambdaFunction lambdaFunction) -> {
        getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getKinesisStream());

        try {
            return findorUpdateMappingConfiguration(trigger, lambdaFunction,
                    kinesisClient.describeStream(trigger.getKinesisStream()).getStreamDescription().getStreamARN());
        } catch (Exception rnfe) {
            getLog().info(rnfe.getMessage());
            throw new IllegalArgumentException("Unable to find stream with name " + trigger.getKinesisStream());
        }
    };

    private Trigger findorUpdateMappingConfiguration(Trigger trigger, LambdaFunction lambdaFunction, String streamArn) {
        ListEventSourceMappingsRequest listEventSourceMappingsRequest = new ListEventSourceMappingsRequest()
                .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn());
        ListEventSourceMappingsResult listEventSourceMappingsResult = lambdaClient.listEventSourceMappings(listEventSourceMappingsRequest);

        Optional<EventSourceMappingConfiguration> eventSourceMappingConfiguration = listEventSourceMappingsResult.getEventSourceMappings().stream()
                .filter(stream -> {
                    boolean isSameFunctionArn = Objects.equals(stream.getFunctionArn(), lambdaFunction.getUnqualifiedFunctionArn());
                    boolean isSameSourceArn = Objects.equals(stream.getEventSourceArn(), streamArn);
                    return isSameFunctionArn && isSameSourceArn;
                })
                .findFirst();

        if (eventSourceMappingConfiguration.isPresent()) {
            UpdateEventSourceMappingRequest updateEventSourceMappingRequest = new UpdateEventSourceMappingRequest()
                    .withUUID(eventSourceMappingConfiguration.get().getUUID())
                    .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
                    .withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
                    .withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
            UpdateEventSourceMappingResult updateEventSourceMappingResult = lambdaClient.updateEventSourceMapping(updateEventSourceMappingRequest);
            trigger.withTriggerArn(updateEventSourceMappingResult.getEventSourceArn());
            getLog().info("Updated " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
        } else {

        	CreateEventSourceMappingRequest createEventSourceMappingRequest = new CreateEventSourceMappingRequest()
                    .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
                    .withEventSourceArn(streamArn)
                    .withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
                    .withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
        	// For SQS starting position is not valid
        	if (!streamArn.contains(":sqs:")) {
        		createEventSourceMappingRequest.setStartingPosition(EventSourcePosition.fromValue(ofNullable(trigger.getStartingPosition()).orElse(LATEST.toString())));
        	}

            CreateEventSourceMappingResult createEventSourceMappingResult = lambdaClient.createEventSourceMapping(createEventSourceMappingRequest);
            trigger.withTriggerArn(createEventSourceMappingResult.getEventSourceArn());
            getLog().info("Created " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
        }

        return trigger;
    }

    private Function<LambdaFunction, LambdaFunction> createOrUpdateTriggers = (LambdaFunction lambdaFunction) -> {
        lambdaFunction.getTriggers().forEach(trigger -> {
            if (TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(trigger.getIntegration())) {
                createOrUpdateScheduledRule.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_DYNAMO_DB.equals(trigger.getIntegration())) {
                createOrUpdateDynamoDBTrigger.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_KINESIS.equals(trigger.getIntegration())) {
                createOrUpdateKinesisStream.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_SNS.equals(trigger.getIntegration())) {
                createOrUpdateSNSTopicSubscription.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_ALEXA_SK.equals(trigger.getIntegration())) {
                addAlexaSkillsKitPermission.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_LEX.equals(trigger.getIntegration())) {
                addLexPermission.apply(trigger, lambdaFunction);
            } else if (TRIG_INT_LABEL_SQS.equals(trigger.getIntegration())) {
                createOrUpdateSQSTrigger.apply(trigger, lambdaFunction);
            } else {
                throw new IllegalArgumentException("Unknown integration for trigger " + trigger.getIntegration() + ". Correct your configuration");
            }
        });
        return lambdaFunction;
    };

    private GetFunctionResult getFunction(LambdaFunction lambdaFunction) {
        return lambdaClient.getFunction(new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName()));
    }

    private boolean isConfigurationChanged(LambdaFunction lambdaFunction, GetFunctionResult function) {
        BiPredicate<String, String> isChangeStr = (s0, s1) -> !Objects.equals(s0, s1);
        BiPredicate<Integer, Integer> isChangeInt = (i0, i1) -> !Objects.equals(i0, i1);
        BiPredicate<List<String>, List<String>> isChangeList = (l0, l1) -> !(l0.containsAll(l1) && l1.containsAll(l0));
        return of(function.getConfiguration())
                .map(config -> {
                    VpcConfigResponse vpcConfig = config.getVpcConfig();
                    if (vpcConfig == null) {
                        vpcConfig = new VpcConfigResponse();
                    }
                    boolean isDescriptionChanged = isChangeStr.test(config.getDescription(), lambdaFunction.getDescription());
                    boolean isHandlerChanged = isChangeStr.test(config.getHandler(), lambdaFunction.getHandler());
                    boolean isRoleChanged = isChangeStr.test(config.getRole(), lambdaFunction.getLambdaRoleArn());
                    boolean isTimeoutChanged = isChangeInt.test(config.getTimeout(), lambdaFunction.getTimeout());
                    boolean isMemoryChanged = isChangeInt.test(config.getMemorySize(), lambdaFunction.getMemorySize());
                    boolean isSecurityGroupIdsChanged = isChangeList.test(vpcConfig.getSecurityGroupIds(), lambdaFunction.getSecurityGroupIds());
                    boolean isVpcSubnetIdsChanged = isChangeList.test(vpcConfig.getSubnetIds(), lambdaFunction.getSubnetIds());
                    return isDescriptionChanged || isHandlerChanged || isRoleChanged || isTimeoutChanged || isMemoryChanged ||
                           isSecurityGroupIdsChanged || isVpcSubnetIdsChanged || isAliasesChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction) ||
                           isScheduleRuleChanged(lambdaFunction);
                })
                .orElse(true);
    }

    private boolean isKeepAliveChanged(LambdaFunction lambdaFunction) {
        try {
            return ofNullable(lambdaFunction.getKeepAlive()).map( ka -> {
                DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(lambdaFunction.getKeepAliveRuleName()));
                return !Objects.equals(res.getScheduleExpression(), lambdaFunction.getKeepAliveScheduleExpression());
            }).orElse(false);

        } catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
            return true;
        }
    }

    private boolean isScheduleRuleChanged(LambdaFunction lambdaFunction) {
        try {
            return lambdaFunction.getTriggers().stream().filter(t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).anyMatch(trigger -> {
                DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(trigger.getRuleName()));
                return !(Objects.equals(res.getName(), trigger.getRuleName()) &&
                        Objects.equals(res.getDescription(), trigger.getRuleDescription()) &&
                        Objects.equals(res.getScheduleExpression(), trigger.getScheduleExpression()));
            });
        } catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
            return true;
        }
    }

    private boolean isAliasesChanged(LambdaFunction lambdaFunction) {
        try {
            ListAliasesResult listAliasesResult = lambdaClient.listAliases(new ListAliasesRequest()
                    .withFunctionName(lambdaFunction.getFunctionName()));
            List<String> configuredAliases = listAliasesResult.getAliases().stream()
                                                              .map(AliasConfiguration::getName)
                                                              .collect(toList());
            return !configuredAliases.containsAll(lambdaFunction.getAliases());
        } catch (ResourceNotFoundException ignored) {
            return true;
        }
    }

    private Function<LambdaFunction, LambdaFunction> createFunction = (LambdaFunction lambdaFunction) -> {
        getLog().info("About to create function " + lambdaFunction.getFunctionName());
        CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest()
                .withDescription(lambdaFunction.getDescription())
                .withRole(lambdaFunction.getLambdaRoleArn())
                .withFunctionName(lambdaFunction.getFunctionName())
                .withHandler(lambdaFunction.getHandler())
                .withRuntime(runtime)
                .withTimeout(ofNullable(lambdaFunction.getTimeout()).orElse(timeout))
                .withMemorySize(ofNullable(lambdaFunction.getMemorySize()).orElse(memorySize))
                .withVpcConfig(getVpcConfig(lambdaFunction))
                .withCode(new FunctionCode()
                        .withS3Bucket(s3Bucket)
                        .withS3Key(fileName))
                .withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));

        CreateFunctionResult createFunctionResult = lambdaClient.createFunction(createFunctionRequest);
        lambdaFunction.withVersion(createFunctionResult.getVersion())
                      .withFunctionArn(createFunctionResult.getFunctionArn());
        getLog().info("Function " + createFunctionResult.getFunctionName() + " created. Function Arn: " + createFunctionResult.getFunctionArn());

        return lambdaFunction;
    };

    private VpcConfig getVpcConfig(LambdaFunction lambdaFunction) {
        return new VpcConfig()
                .withSecurityGroupIds(lambdaFunction.getSecurityGroupIds())
                .withSubnetIds(lambdaFunction.getSubnetIds());
    }

    /**
     * Remove orphaned kinesis stream triggers.
     * TODO: Combine with cleanUpOrphanedDynamoDBTriggers.
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedKinesisTriggers = lambdaFunction -> {
        ListEventSourceMappingsResult listEventSourceMappingsResult =
                lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
                        .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));

        List<String> streamNames = new ArrayList<String>();

        // This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
        // and vice versa.  Unfortunately this assumes that stream names won't be the same as table names.
        lambdaFunction.getTriggers().stream().forEach(t -> {
            ofNullable(t.getKinesisStream()).ifPresent(x -> streamNames.add(x));
            ofNullable(t.getDynamoDBTable()).ifPresent(x -> streamNames.add(x));
        });

        listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
            if ( s.getEventSourceArn().contains(":kinesis:") ) {
                if ( ! streamNames.contains(kinesisClient.describeStream(new com.amazonaws.services.kinesis.model.DescribeStreamRequest()
                        .withStreamName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf('/')+1)))
                        .getStreamDescription()
                        .getStreamName()) ){
                    getLog().info("    Removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
                    try {
                        lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
                    } catch(Exception e8) {
                        getLog().error("    Error removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
                    }
                }
            }
        });

        return lambdaFunction;
     };

    /**
     * Removes orphaned sns triggers.
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedSNSTriggers = lambdaFunction -> {

        List<Subscription> subscriptions = new ArrayList<Subscription>();
        ListSubscriptionsResult result = snsClient.listSubscriptions();

        do {
            subscriptions.addAll(result.getSubscriptions().stream().filter( sub -> {
                return sub.getEndpoint().equals(lambdaFunction.getFunctionArn());
            }).collect(Collectors.toList()));

            result = snsClient.listSubscriptions(result.getNextToken());
        } while( result.getNextToken() != null );

        if (subscriptions.size() > 0 ) {
            List<String> snsTopicNames = lambdaFunction.getTriggers().stream().map(t -> {
                return ofNullable(t.getSNSTopic()).orElse("");
            }).collect(Collectors.toList());

            subscriptions.stream().forEach(s -> {
                String topicName = s.getTopicArn().substring(s.getTopicArn().lastIndexOf(":")+1);
                if (!snsTopicNames.contains(topicName)) {
                    getLog().info("    Removing orphaned SNS trigger for topic " + topicName);
                    try {
                        snsClient.unsubscribe(new UnsubscribeRequest().withSubscriptionArn(s.getSubscriptionArn()));

                        ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
                            policy.getStatements().stream()
                                .filter(
                                    stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
                                    stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
                                    stmt.getResources().stream().anyMatch(r -> r.getId().equals(lambdaFunction.getFunctionArn()))
                                ).forEach( st -> {
                                    if( st.getConditions().stream().anyMatch(condition -> condition.getValues().contains(s.getTopicArn())) ) {
                                        getLog().info("      Removing invoke permission for SNS trigger");
                                        try {
                                            lambdaClient.removePermission(new RemovePermissionRequest()
                                                .withFunctionName(lambdaFunction.getFunctionName())
                                                .withQualifier(lambdaFunction.getQualifier())
                                                .withStatementId(st.getId()));
                                        } catch (Exception e7) {
                                            getLog().error("      Error removing invoke permission for SNS trigger");
                                        }
                                    }
                                });
                            return of(policy);
                        });

                    } catch(Exception e5) {
                        getLog().error("    Error removing SNS trigger for topic " + topicName);
                    }
                }
            });
        }

        return lambdaFunction;
    };

    /**
     * Removes orphaned SQS triggers.
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedSQSTriggers = lambdaFunction -> {
        ListEventSourceMappingsResult listEventSourceMappingsResult =
                lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
                        .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));

        List<String> standardQueues = new ArrayList<String>();

        lambdaFunction.getTriggers().stream().forEach(t -> {
            ofNullable(t.getStandardQueue()).ifPresent(x -> standardQueues.add(x));
        });

        listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
            if ( s.getEventSourceArn().contains(":sqs:")) {
            	// This API hit may not required, added here only for double check or cross verification
            	Optional<GetQueueUrlResult> getQueueUrlOptionalResult = ofNullable(sqsClient.getQueueUrl(new GetQueueUrlRequest()
            			.withQueueName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf(':')+1))));

            	getQueueUrlOptionalResult.ifPresent(queue -> {
            			String queueName = queue.getQueueUrl().substring(queue.getQueueUrl().lastIndexOf('/')+1);
	        			if ( ! standardQueues.contains(queueName) ) {
	                        getLog().info("    Removing orphaned SQS trigger for queue " + queueName);
	                        try {
	                            lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
	                        } catch (Exception exp) {
	                            getLog().error("    Error removing SQS trigger for queue " + queueName + ", Error Message :" + exp.getMessage());
	                        }
	                    }
	            	}

            	);
            }
        });

        return lambdaFunction;
     };

    /**
     * Removes orphaned dynamo db triggers.
     * TODO: Combine with cleanUpOrphanedKinesisTriggers
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedDynamoDBTriggers = lambdaFunction -> {
        ListEventSourceMappingsResult listEventSourceMappingsResult =
                lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
                        .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));

        List<String> tableNames = new ArrayList<String>();

        // This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
        // and vice versa.  Unfortunately this assumes that stream names won't be the same as table names.
        lambdaFunction.getTriggers().stream().forEach(t -> {
            ofNullable(t.getKinesisStream()).ifPresent(x -> tableNames.add(x));
            ofNullable(t.getDynamoDBTable()).ifPresent(x -> tableNames.add(x));
        });

        listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
            if ( s.getEventSourceArn().contains(":dynamodb:")) {
                StreamDescription sd = dynamoDBStreamsClient.describeStream(new DescribeStreamRequest()
                    .withStreamArn(s.getEventSourceArn())).getStreamDescription();

                if ( ! tableNames.contains(sd.getTableName()) ) {
                    getLog().info("    Removing orphaned DynamoDB trigger for table " + sd.getTableName());
                    try {
                        lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
                    } catch (Exception e4) {
                        getLog().error("    Error removing DynamoDB trigger for table " + sd.getTableName());
                    }
                }
            }
        });

        return lambdaFunction;
     };

    /**
     * Removes the Alexa permission if it isn't found in the current configuration.
     * TODO: Factor out code common with other orphan clean up functions.
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedAlexaSkillsTriggers = lambdaFunction -> {
        ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
            policy.getStatements().stream()
                .filter(
                    stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
                    stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_ALEXA.equals(principal.getId())) &&
                    !lambdaFunction.getTriggers().stream().anyMatch( t -> t.getIntegration().equals(TRIG_INT_LABEL_ALEXA_SK)))
                .forEach( s -> {
                    try {
                        getLog().info("    Removing orphaned Alexa permission " + s.getId());
                        lambdaClient.removePermission(new RemovePermissionRequest()
                            .withFunctionName(lambdaFunction.getFunctionName())
                            .withQualifier(lambdaFunction.getQualifier())
                            .withStatementId(s.getId()));
                    } catch (ResourceNotFoundException rnfe1) {
                        getLog().error("    Error removing permission for " + s.getId() + ": " + rnfe1.getMessage());
                    }
                });
            return of(policy);
        });

        return lambdaFunction;
    };

    /**
     * Removes any Lex permissions that aren't found in the current configuration.
     * TODO: Factor out code common with other orphan clean up functions.
     */
    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedLexSkillsTriggers = lambdaFunction -> {
        ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
            policy.getStatements().stream()
                .filter(stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
                        stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_LEX.equals(principal.getId())) &&
                        !lambdaFunction.getTriggers().stream().anyMatch( t -> stmt.getId().contains(ofNullable(t.getLexBotName()).orElse(""))))
                .forEach( s -> {
                    try {
                        getLog().info("    Removing orphaned Lex permission " + s.getId());
                        lambdaClient.removePermission(new RemovePermissionRequest()
                            .withFunctionName(lambdaFunction.getFunctionName())
                            .withQualifier(lambdaFunction.getQualifier())
                            .withStatementId(s.getId()));
                    } catch (Exception ign2) {
                        getLog().error("   Error removing permission for " + s.getId() + ign2.getMessage() );
                    }
                });
            return of(policy);
        });

        return lambdaFunction;
    };

    Function<LambdaFunction, LambdaFunction> cleanUpOrphanedCloudWatchEventRules = lambdaFunction -> {
        // Get the list of cloudwatch event rules defined for this function (if any).
        List<String> existingRuleNames = cloudWatchEventsClient.listRuleNamesByTarget(new ListRuleNamesByTargetRequest()
        .withTargetArn(lambdaFunction.getFunctionArn())).getRuleNames();

        // Get the list of cloudwatch event rules to be defined for this function (if any).
        List<String> definedRuleNames = lambdaFunction.getTriggers().stream().filter(
                t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).map(t -> {
                    return t.getRuleName();
                }).collect(toList());

        // Add the keep alive rule name if the user has disabled keep alive for the function.
        ofNullable(lambdaFunction.getKeepAlive()).ifPresent(ka -> {
           if ( ka > 0 ) {
               definedRuleNames.add(lambdaFunction.getKeepAliveRuleName());
           }
        });

        // Remove all of the rules that will be defined from the list of existing rules.
        // The remainder is a set of event rules which should no longer be associated to this
        // function.
        existingRuleNames.removeAll(definedRuleNames);

        // For each remaining rule, remove the function as a target and attempt to delete
        // the rule.
        existingRuleNames.stream().forEach(ern -> {
            getLog().info("    Removing CloudWatch Event Rule: " + ern);
            cloudWatchEventsClient.removeTargets(new RemoveTargetsRequest()
                .withIds("1")
                .withRule(ern));
            try {
                cloudWatchEventsClient.deleteRule(new DeleteRuleRequest().withName(ern));
            } catch (Exception e) {
                getLog().error("    Error removing orphaned rule: " + e.getMessage());
            }
        });

        return lambdaFunction;
    };

    Function<LambdaFunction, LambdaFunction> cleanUpOrphans = lambdaFunction -> {
        try {
            lambdaFunction.setFunctionArn(lambdaClient.getFunction(
                    new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());

            getLog().info("Cleaning up orphaned triggers.");

            // Add clean up orphaned trigger functions for each integration here:
            cleanUpOrphanedCloudWatchEventRules
                .andThen(cleanUpOrphanedDynamoDBTriggers)
                .andThen(cleanUpOrphanedKinesisTriggers)
                .andThen(cleanUpOrphanedSNSTriggers)
                .andThen(cleanUpOrphanedAlexaSkillsTriggers)
                .andThen(cleanUpOrphanedLexSkillsTriggers)
                .andThen(cleanUpOrphanedSQSTriggers)
                .apply(lambdaFunction);

        } catch (ResourceNotFoundException ign1) {
            getLog().debug("Assuming function has no orphan triggers to clean up since it doesn't exist yet.");
        }

        return lambdaFunction;
    };

    Function<LambdaFunction, LambdaFunction> createOrUpdate = lambdaFunction -> {
      try {
          lambdaFunction.setFunctionArn(lambdaClient.getFunction(
                  new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());
          of(getFunction(lambdaFunction))
                  .filter(getFunctionResult -> shouldUpdate(lambdaFunction, getFunctionResult))
                  .map(getFujnctionResult ->
                  updateFunctionCode
                          .andThen(updateFunctionConfig)
                          .andThen(createOrUpdateAliases)
                          .andThen(createOrUpdateTriggers)
                          .andThen(createOrUpdateKeepAlive)
                          .apply(lambdaFunction));
      } catch (ResourceNotFoundException ign) {
          createFunction.andThen(createOrUpdateAliases)
                        .andThen(createOrUpdateTriggers)
                        .apply(lambdaFunction);
      }

      return lambdaFunction;
    };
}


text:
module.exports = {

    data: function () {
        return _.extend({}, window.$data);
    },

    ready: function () {

        UIkit.tab(this.$$.tab, {connect: this.$$.content});
        // this.$set('widget.data', _.defaults({}, this.widget.data, this.type.defaults));

        // set position from get param
        if (!this.widget.id) {
            var match = RegExp('[?&]position=([^&]*)').exec(location.search);
            this.widget.position = (match && decodeURIComponent(match[1].replace(/\+/g, ' '))) || '';
        }
    },

    computed: {

        sections: function () {

            var sections = [];

            _.forIn(this.$options.components, function (component) {
                if (component.options.section) {
                    sections.push(component.options.section);
                }
            });

            return sections;
        },

        positionOptions: function () {
            return [{text: this.$trans('- Assign -'), value: ''}].concat(
                _.map(this.theme.positions, function (position) {
                    return {text: this.$trans(position.label), value: position.name};
                }, this)
            );
        }

    },

    methods: {

        save: function (e) {
            e.preventDefault();

            this.$broadcast('save', {widget: this.widget});
            this.$resource('api/widget/:id').save({id: this.widget.id}, {widget: this.widget}, function (data) {
                this.$dispatch('saved');

                if (!this.widget.id) {
                    window.history.replaceState({}, '', this.$url('admin/widget/edit', {id: data.widget.id}))
                }

                this.$set('widget', data.widget);

                UIkit.notify(data.message);
            }, function (data) {
                UIkit.notify(data, 'danger');
            });
        },

        cancel: function (e) {
            e.preventDefault();

            this.$dispatch('cancel');
        }

    },

    filters: {

        active: function (sections) {
            return sections.filter(function (section) {
                return !section.active || this.widget.type.match(section.active);
            }, this);
        }

    }

};

$(function () {

    (new Widgets(module.exports)).$mount('#widget-edit');

});


text:
event: '2015 OHBM Hackathon (HI)'

title:  'DueCredit: automated collection of citations for software, methods, and data'

author:

- initials: YOH
  surname: Halchenko
  firstname: Yaroslav O.
  email: yoh@onerussian.com
  affiliation: aff1
  corref: aff1
- initials: MVdOC
  surname: Visconti di Oleggio Castello
  firstname: Matteo
  email: matteo.visconti.gr@dartmouth.edu
  affiliation: aff1

affiliations:

- id: aff1
  orgname: 'Department of Pscyhological & Brain Sciences, Dartmouth College'
  street: 6207 Moore Hall
  postcode: 03755
  city: Hanover
  state: New Hampshire
  country: USA

url: https://github.com/duecredit/duecredit

coi: None

acknow: The authors would like to thank the organizers and attendees of the 2015 OHBM Hackathon. This project is supported in part by a grant from the NSF (award 1429999). MVdOC was supported by a Dartmouth Graduate Studies Travel Grant.

contrib: YOH and MVdOC performed the project and wrote the report.

bibliography: brainhack-report

gigascience-ref: \href{http://gigadb.org/dataset/100227}{doi:10.5524/100227}
...

#Introduction
Data analysis software and canonical datasets are the driving force behind many
fields of empirical sciences. Despite being of paramount importance, those
resources are most often not adequately cited. Although some can consider this
a "social" problem, its roots are technical: Users of those resources often are
simply not aware of the underlying computational libraries and methods they
have been using in their research projects. This in-turn fosters inefficient
practices that encourage the development of new projects, instead of
contributing to existing established ones. Some projects (e.g. FSL
\cite{smith2004advances}) facilitate citation of the utilized methods, but such
efforts are not uniform, and the output is rarely in commonly used citation
formats (e.g. BibTeX). DueCredit is a simple framework to embed information
about publications or other references within the original code or dataset
descriptors. References are automatically reported to the user whenever a given
functionality or dataset is being used.

#Approach
DueCredit is currently available for Python, but we envision extending support
to other frameworks (e.g., Matlab, R).  Until DueCredit gets adopted natively by
the projects, it provides the functionality to "inject" references for 3rd
party modules.

For the developer, DueCredit implements a decorator `@due.dcite` that allows to
link a method or class to a set of references that can be specified through a
doi or BibTeX entry. For example (from PyMVPA):

```
@due.dcite(
    Doi('10.1016/j.neuron.2011.08.026'),
    description="Hyperalignment of data to a ...",
    tags=["implementation"])
def train(self, datasets):
    """Derive a common feature space ...
    ....
```

The end-user simply needs to run the script loading the `duecredit`
module. For example, with the following minimal script

```
# A tiny analysis script to demonstrate duecredit
#
# Import of duecredit is not necessary if you just run
# this script with
#    python -m duecredit
# import duecredit  # Just to enable duecredit
from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import pdist
from sklearn.datasets import make_blobs

print("I: Simulating 4 blobs")
data, true_label = make_blobs(centers=4)

dist = pdist(data, metric='euclidean')

Z = linkage(dist, method='single')
print("I: Done clustering 4 blobs")
```

by running it with `python -m duecredit`, we get a summary of the packages
and methods used

```
$python -m duecredit example_scipy.py
I: Simulating 4 blobs
I: Done clustering 4 blobs
DueCredit Report:
- Scientific tools library / numpy (v 1.10.4) [1]
- Scientific tools library / scipy (v 0.17) [2]
  - Single linkage hierarchical clustering ... [3]
- Machine Learning library / sklearn ... [4]

3 packages cited
0 modules cited
1 functions cited

References
----------

[1] Van Der Walt, S., Colbert, S.C. & ...
structure for efficient numerical comp...
Engineering, 13(2), pp.22–30.
[2] Jones, E. et al., 2001. SciPy: Open ...
[3] Sibson, R., 1973. SLINK: an optimall...
single-link cluster method. The Computer...
[4] Pedregosa, F. et al., 2011. Scikit-l...
Journal of Machine Learning Research, 12...
```

The references can then be easily converted into BibTeX format by using
`duecredit summary --format bibtex` in the command line.

```
$duecredit summary --format bibtex
@Misc{JOP+01,
author = {Eric Jones and Travis Oliphant ...}
title = {{SciPy}: Open source scientific ...}
year = {2001--},
url = "http://www.scipy.org/",
note = {[Online; accessed 2015-07-13]}
}
...
```

#Results
The initial release of DueCredit (0.1.0) was implemented during the OHBM 2015
hackathon and uploaded to pypi and is freely available. DueCredit provides a
concise API to associate a publication reference with any given module or
function. For example: To provide a reference for an entire module the cite
function can be used, while functions and methods can be conveniently decorated
using dcite. DueCredit comes with a simple demo code which demonstrates its
utility. Running a sample analysis produces a summary of references. At each
run, the information is stored in a pickled file, and incremental runs update
that file. Thus, DueCredit summary can be used to show that information again
or export it as a BibTeX file ready for reuse.

# Conclusions
DueCredit is in its early stages of development, but two days of team
development at the OHBM hackathon were sufficient to establish a usable
prototype implementation.  Since then, the code-base was further improved and
multiple beta-releases followed, expanding the coverage of citable resources
(e.g., within scipy, sklearn modules via injections and PyMVPA natively).


text:
<title>META_PIE</title>

NAME

META_PIE

NEAREST API CALL

#include <windows.h>

BOOL32 Pie
(
    HDC32 hdc,
    INT32 left,
    INT32 top,
    INT32 right,
    INT32 bottom,
    INT32 xstart,
    INT32 ystart,
    INT32 xend,
    INT32 yend
);

DESCRIPTION

U16 array no	Value

0	 yend, y of endpoint

 1	 xend, x of endpoint

 2	 ystart, y of endpoint

 3	xstart, x of endpoint

 4	bottom, bottom of bounding box

 5	right, right of bounding box

 6	top, top of bounding box

 7	left, left of bounding box

left, right, top and bottom are the extents of the ellipse of
which the pie is a part

xstart,ystart define a point from which you draw an imaginary line
between it and the center of the ellipse, where that line intersects the
ellipse is the starting part of the arc

xend,yend similiarly define the end of the arc.

This is quite different from how X, and other drawing lib's define an Arc,
and its somewhat awkward to convert from it to X's mechanism, see the
X bindings for libwmf for into on that.

back


text:
<?php

class BMBtnSkillRandomBMFixedTest extends PHPUnit_Framework_TestCase {
    /**
     * @var BMBtnSkillRandomBMFixed
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new BMBtnSkillRandomBMFixed;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers BMBtnSkillRandomBMFixed::specify_recipes
     */
    public function testSpecify_recipes_valid_args() {
        global $BM_RAND_VALS;

        $button = new BMButton;
        $args = array('button' => $button);
        $this->assertNull($button->hasAlteredRecipe);
        $this->assertEmpty($button->recipe);

        // choose dice with 6, 20, 10, 12, 6 sides
        // and then choose 'f' on the third die and 'c' on the fifth die
        $BM_RAND_VALS = array(1, 5, 3, 4, 1,    // die sizes
                              1,                // choose focus skill
                              2, 0);            // dice that have skill

        $retval = BMBtnSkillRandomBMFixed::specify_recipes($args);
        $this->assertTrue($retval);
        $this->assertTrue($button->hasAlteredRecipe);
        $this->assertNotEmpty($button->recipe);
        $this->assertEquals('f(6) (6) f(10) (12) (20)', $button->recipe);
    }

    /**
     * @covers BMBtnSkillRandomBMFixed::specify_recipes
     */
    public function testSpecify_recipes_valid_args_already_specified() {
        $button = new BMButton;
        $button->recipe = '(4) (X)';
        $args = array('button' => $button);
        $retval = BMBtnSkillRandomBMFixed::specify_recipes($args);
        $this->assertFalse($retval);
        $this->assertNull($button->hasAlteredRecipe);
        $this->assertEquals('(4) (X)', $button->recipe);
    }
}


text:
{% extends "browse_base.html" %}
{% load static from staticfiles %}
{% load tags %}
{% block extra_browse_css %}
<link href="{% static 'browse/css/study.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'libs/jquery/jquery.modal.css' %}" type="text/css" media="screen"/>
{% endblock %}
{% block extra_browse_script %}

{% endblock %}
{% block title %}BII | Study{% endblock %}
{% block browse_content %}

Are you sure you want to delete this study?

YesNo

Publications

        Link to publication

        Link to publication

Contacts

Assays

            {% for assay in study.s_assays %}

                        {{assay.assay_type_count}}

                                {{assay.measurement}}

                                {{assay.technology}}

            {% endfor %}

Study Groups

        {% for group in study.s_groups %}

                        {{group.study_group}}

                            Count
                            {{group.member_count}}

                        {% for member in group.members %}

                            GSM
                                {{member}}

                                {% endif %}

                        {% endfor %}

        {% endfor %}

{% endblock %}


text:
<!--Copyright 2017 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.-->

<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
    </style>
</resources>


text:
class AddGroupToEvent < ActiveRecord::Migration
  def change
    add_column :events, :group_id, :integer
  end
end