text:
unless defined? $__rq_qdb__
  module RQ
#--{{{
    LIBDIR = File::dirname(File::expand_path(__FILE__)) + File::SEPARATOR unless
      defined? LIBDIR

    require 'arrayfields'

    require LIBDIR + 'util'
    require LIBDIR + 'logging'
    require LIBDIR + 'sleepcycle'
    require LIBDIR + 'refresher'

    #
    # the QDB class is the low level access point to the actual sqlite database.
    # the primary function if performs is to serialize access to the queue db
    # via the locking protocol
    #
    class  QDB
#--{{{
      include Util
      include Logging

      class RollbackTransactionError < StandardError; end
      class AbortedTransactionError < StandardError; end

      FIELDS =
#--{{{
      %w(
        jid priority state
        submitted started finished elapsed
        submitter runner
        stdin stdout stderr data
        pid exit_status
        tag restartable command
      )
#--}}}

      PRAGMAS =
#--{{{
        <<-sql
          PRAGMA default_synchronous = FULL;
        sql
#--}}}

      SCHEMA =
#--{{{
        <<-sql
          create table jobs
          (
            jid integer primary key,
            #{ FIELDS[1..-1].join ",\n          " }
          );
          create table attributes
          (
            key,
            value,
            primary key (key)
          );
        sql
#--}}}

      DEFAULT_LOGGER                         = Logger::new(STDERR)
      DEFAULT_SQL_DEBUG                      = false
      DEFAULT_TRANSACTION_RETRIES            = 4
      DEFAULT_AQUIRE_LOCK_SC                 = SleepCycle::new(2, 16, 2)
      DEFAULT_TRANSACTION_RETRIES_SC         = SleepCycle::new(8, 24, 8)
      DEFAULT_ATTEMPT_LOCKD_RECOVERY         = true
      DEFAULT_LOCKD_RECOVER_WAIT             = 3600  # 1 hr
      DEFAULT_AQUIRE_LOCK_LOCKFILE_STALE_AGE = 21600 # 6 hrs
      DEFAULT_AQUIRE_LOCK_REFRESH_RATE       = 30

      class << self
#--{{{
        attr :sql_debug, true
        attr :transaction_retries, true
        attr :aquire_lock_sc, true
        attr :transaction_retries_sc, true
        attr :attempt_lockd_recovery, true
        attr :lockd_recover_wait, true
        attr :aquire_lock_lockfile_stale_age, true
        attr :aquire_lock_refresh_rate, true

        def fields
#--{{{
          FIELDS
#--}}}
        end
        def integrity_check dbpath
#--{{{
          ret = false
          tuple = nil
          begin
            db =
              begin
                SQLite::Database::new dbpath, 0
              rescue
                SQLite::Database::new dbpath
              end
            opened = true
            db.use_array = true rescue nil
            tuple = db.execute 'PRAGMA integrity_check;'
            ret = (tuple and tuple.first and (tuple.first["integrity_check"] =~ /^\s*ok\s*$/io))
          ensure
            db.close if opened
            db = nil
          end
          ret
#--}}}
        end
        def t2h tuple
#--{{{
          h = {}
          FIELDS.each_with_index{|f,i| h[f] = tuple[i]}
          h
#--}}}
        end
        def h2t h
#--{{{
          t = tuple
          FIELDS.each{|f| t[f] = h[f]}
          t
#--}}}
        end
        def tuple
#--{{{
          t = Array::new FIELDS.size
          t.fields = FIELDS
          t
#--}}}
        end
        def q tuple
#--{{{
          [ tuple ].flatten.map do |f|
            if f and not f.to_s.empty?
              "'" << Util.escape(f,"'","'") << "'"
            else
              'NULL'
            end
          end
#--}}}
        end
        def create path, opts = {}
#--{{{
          qdb = new path, opts
          FileUtils::touch qdb.lockfile
          create_schema qdb.schema
          qdb.transaction do
            qdb.execute PRAGMAS
            qdb.execute SCHEMA
          end
          qdb
#--}}}
        end
        def create_schema path
#--{{{
          tmp = "#{ path }.tmp"
          open(tmp,'w') do |f|
            f.puts PRAGMAS
            f.puts SCHEMA
          end
          FileUtils::mv tmp, path
#--}}}
        end
#--}}}
      end

      attr :path
      attr :opts
      attr :dirname
      attr :schema
      attr :fields
      attr :mutex
      attr :lockfile
      attr :sql_debug, true
      attr :transaction_retries, true
      attr :aquire_lock_sc, true
      attr :transaction_retries_sc, true
      attr :attempt_lockd_recovery, true
      attr :lockd_recover_wait, true
      attr :aquire_lock_lockfile_stale_age, true
      attr :aquire_lock_refresh_rate, true

      def initialize path, opts = {}
#--{{{
        @path = path
        @opts = opts

        @logger =
          Util::getopt('logger', @opts) ||
          klass.logger ||
          DEFAULT_LOGGER

        @sql_debug =
          Util::getopt('sql_debug', @opts) ||
          klass.sql_debug ||
          ENV['RQ_SQL_DEBUG'] ||
          DEFAULT_SQL_DEBUG

        @transaction_retries =
          Util::getopt('transaction_retries', @opts) ||
          klass.transaction_retries ||
          DEFAULT_TRANSACTION_RETRIES

        @aquire_lock_sc =
          Util::getopt('aquire_lock_sc', @opts) ||
          klass.aquire_lock_sc ||
          DEFAULT_AQUIRE_LOCK_SC

        @transaction_retries_sc =
          Util::getopt('transaction_retries_sc', @opts) ||
          klass.transaction_retries_sc ||
          DEFAULT_TRANSACTION_RETRIES_SC

        @attempt_lockd_recovery =
          Util::getopt('attempt_lockd_recovery', @opts) ||
          klass.attempt_lockd_recovery ||
          DEFAULT_ATTEMPT_LOCKD_RECOVERY

        @lockd_recover_wait =
          Util::getopt('lockd_recover_wait', @opts) ||
          klass.lockd_recover_wait ||
          DEFAULT_LOCKD_RECOVER_WAIT

        @aquire_lock_lockfile_stale_age =
          Util::getopt('aquire_lock_lockfile_stale_age', @opts) ||
          klass.aquire_lock_lockfile_stale_age ||
          DEFAULT_AQUIRE_LOCK_LOCKFILE_STALE_AGE

        @aquire_lock_refresh_rate =
          Util::getopt('aquire_lock_refresh_rate', @opts) ||
          klass.aquire_lock_refresh_rate ||
          DEFAULT_AQUIRE_LOCK_REFRESH_RATE

        @schema = "#{ @path }.schema"
        @dirname = File::dirname(path).gsub(%r|/+\s*$|,'')
        @basename = File::basename(path)
        @waiting_w = File::join(@dirname, "#{ Util::hostname }.#{ $$ }.waiting.w")
        @waiting_r = File::join(@dirname, "#{ Util::hostname }.#{ $$ }.waiting.r")
        @lock_w = File::join(@dirname, "#{ Util::hostname }.#{ $$ }.lock.w")
        @lock_r = File::join(@dirname, "#{ Util::hostname }.#{ $$ }.lock.r")
        @lockfile = File::join(@dirname, 'lock')
        @lockf = Lockfile::new("#{ @path }.lock")
        @fields = FIELDS
        @in_transaction = false
        @in_ro_transaction = false
        @db = nil

        @lockd_recover = "#{ @dirname }.lockd_recover"
        @lockd_recover_lockf = Lockfile::new "#{ @lockd_recover }.lock"
        @lockd_recovered = false
#--}}}
      end
      def ro_transaction(opts = {}, &block)
#--{{{
        opts['read_only'] = true
        transaction(opts, &block)
#--}}}
      end
      def transaction opts = {}
#--{{{
        raise 'nested transaction' if @in_transaction
        ro = Util::getopt 'read_only', opts
        ret = nil
        begin
          @in_transaction = true
          lockd_recover_wrap(opts) do
            transaction_wrap(opts) do
              aquire_lock(opts) do
                #sillyclean(opts) do
                  connect do
                    execute 'begin' unless ro
                    ret = yield
                    execute 'commit' unless ro
                  end
                #end
              end
            end
          end
        ensure
          @in_transaction = false
        end
        ret
#--}}}
      end
if false
      def ro_transaction(opts = {}, &block)
#--{{{
        opts['read_only'] = true
        transaction(opts, &block)
#--}}}
      end
      def transaction opts = {}
#--{{{
        ro = Util::getopt 'read_only', opts
        ret = nil
        if @in_transaction
      STDERR.puts 'continuing transaction...'
          ret = yield
        else
          begin
      STDERR.puts 'starting transaction...'
            @in_transaction = true
            lockd_recover_wrap(opts) do
              transaction_wrap(opts) do
                aquire_lock(opts) do
                  #sillyclean(opts) do
                    connect do
                      execute 'begin' unless ro
                      ret = yield
                      execute 'commit' unless ro
                    end
                  #end
                end
              end
            end
          ensure
            @in_transaction = false
          end
        end
        ret
#--}}}
      end
end
      def lockd_recover_wrap opts = {}
#--{{{
        ret = nil
        try_again = false
        begin
          begin
            @lockd_recovered = false
            old_mtime =
              begin
                Util::uncache @lockd_recover rescue nil
                File::stat(@lockd_recover).mtime
              rescue
                Time::now
              end
            ret = yield
          ensure
            new_mtime =
              begin
                Util::uncache @lockd_recover rescue nil
                File::stat(@lockd_recover).mtime
              rescue
                old_mtime
              end

            if new_mtime and old_mtime and new_mtime > old_mtime and not @lockd_recovered
              try_again = true
            end
          end
        rescue
          if try_again
            warn{ "a remote lockd recovery has invalidated this transaction!" }
            warn{ "retrying..."}
            sleep 120
            retry
          else
            raise
          end
        end
        ret
#--}}}
      end
#
# TODO - perhaps should not retry on SQLException??  yet errors seem to map to
# this exception even when the sql is fine... safest (and most anoying) is to
# simply retry.
#
      def transaction_wrap opts = {}
#--{{{
        ro = Util::getopt 'read_only', opts
        ret = nil
        if ro
          ret = yield
        else
          errors = []
          @transaction_retries_sc.reset
          begin
            ret = yield
          rescue => e
          #rescue SQLite::DatabaseException, SQLite::SQLException, SystemCallError => e
            case e
              when AbortedTransactionError
                raise
              when RollbackTransactionError
                raise
              else
                if @transaction_retries == 0
                  raise
                elsif errors.size >= @transaction_retries
                  error{ "MAXIMUM TRANSACTION RETRIES SURPASSED" }
                  raise
                else
                  warn{ e } if(errors.empty? or not Util::erreq(errors[-1], e))
                  errors << e
                  warn{ "retry <#{ errors.size }>..." }
                end
                sleep @transaction_retries_sc.next
                retry
              end
          end
        end
        ret
#--}}}
      end
      def abort_transaction(*a)
#--{{{
        raise AbortedTransactionError, *a
#--}}}
      end
      def rollback_transaction(*a)
#--{{{
        raise RollbackTransactionError, *a
#--}}}
      end
      def sillyclean opts = {}
#--{{{
        ro = Util::getopt 'read_only', opts
        ret = nil
        if ro
          ret = yield
        else
          glob = File::join @dirname,'.nfs*'
          orgsilly = Dir[glob]
          ret = yield
          newsilly = Dir[glob]
          silly = newsilly - orgsilly
          silly.each{|path| FileUtils::rm_rf path}
        end
        ret
#--}}}
      end
      def aquire_lock opts = {}
#--{{{
        ro = Util::getopt 'read_only', opts
        ret = nil

        @aquire_lock_sc.reset

        waiting, ltype, lfile =
          if ro
            [@waiting_r, File::LOCK_SH | File::LOCK_NB, @lock_r]
          else
            [@waiting_w, File::LOCK_EX | File::LOCK_NB, @lock_w]
          end

        ltype_s = (ltype == File::LOCK_EX ? 'write' : 'read')
        ltype ||= File::LOCK_NB

        aquired = false

        until aquired
          begin
            debug{ "aquiring lock" }
            #@lockf.lock unless ro

            open(@lockfile, 'a+') do |lf|

              locked = false
              refresher = nil
              sc = nil

              begin
                FileUtils::touch waiting
                # poll
                42.times do
                  locked = lf.posixlock(ltype | File::LOCK_NB)
                  break if locked
                  sleep rand
                end

                if locked
                  aquired = true
                  refresher = Refresher::new @lockfile, @aquire_lock_refresh_rate
                  debug{ "refresher pid <#{ refresher.pid }> refresh_rate <#{ @aquire_lock_refresh_rate }>" }
                  FileUtils::rm_f waiting rescue nil
                  FileUtils::touch lfile rescue nil
                  debug{ "aquired lock" }
                  ret = yield
                  debug{ "released lock" }
                else
                  aquired = false
                  stat = File::stat @lockfile
                  mtime = stat.mtime
                  stale = mtime < (Time::now - @aquire_lock_lockfile_stale_age)
                  if stale
                    Util::uncache @lockfile rescue nil
                    stat = File::stat @lockfile
                    mtime = stat.mtime
                    stale = mtime < (Time::now - @aquire_lock_lockfile_stale_age)
                    if stale
                      warn{ "detected stale lockfile of mtime <#{ mtime }>" }
                      lockd_recover if @attempt_lockd_recovery
                    end
                  end
                  sc = @aquire_lock_sc.next
                  debug{ "failed to aquire lock - sleep(#{ sc })" }
                  sleep sc
                end

              ensure
                if locked
                  unlocked = false
                  begin
                    42.times do
                      unlocked = lf.posixlock(File::LOCK_UN | File::LOCK_NB)
                      break if unlocked
                      sleep rand
                    end
                  ensure
                    lf.posixlock File::LOCK_UN unless unlocked
                  end
                end
                refresher.kill if refresher
                FileUtils::rm_f waiting rescue nil
                FileUtils::rm_f lfile rescue nil
              end
            end
          ensure
            #@lockf.unlock rescue nil unless read_only
          end
        end
        ret
#--}}}
      end
      def connect
#--{{{
        ret = nil
        opened = nil
        begin
          raise 'db has no schema' unless test ?e, @schema
          debug{"connecting to db <#{ @path }>..."}
          $db = @db =
            begin
              SQLite::Database::new(@path, 0)
            rescue
              SQLite::Database::new(@path)
            end
          debug{"connected."}
          opened = true
          @db.use_array = true rescue nil
          ret = yield @db
        ensure
          @db.close if opened
          $db = @db = nil
          debug{"disconnected from db <#{ @path }>"}
        end
        ret
#--}}}
      end
      def execute sql, &block
#--{{{
        raise 'not in transaction' unless @in_transaction
        if @sql_debug
          logger << "SQL:\n#{ sql }\n"
        end
        #ret = retry_if_locked{ @db.execute sql, &block }
        ret = @db.execute sql, &block
        if @sql_debug and ret and Array === ret and ret.first
          logger << "RESULT:\n#{ ret.first.inspect }\n...\n"
        end
        ret
#--}}}
      end
#
# TODO - add sleep cycle if this ends up getting used
#
      def retry_if_locked
#--{{{
        ret = nil
        begin
          ret = yield
        rescue SQLite::BusyException
          warn{ "database locked - waiting(1.0) and retrying" }
          sleep 1.0
          retry
        end
        ret
#--}}}
      end
      def vacuum
#--{{{
        raise 'nested transaction' if @in_transaction
        begin
          @in_transaction = true
          connect{ execute 'vacuum' }
        ensure
          @in_transaction = false
        end
        self
#--}}}
      end
      def recover!
#--{{{
        raise 'nested transaction' if @in_transaction
        begin
          @in_transaction = true
          connect{ execute 'vacuum' }
          require 'timeout'
          Timeout::timeout(60){ system "sqlite #{ @path } .tables >/dev/null 2>&1" }
        ensure
          @in_transaction = false
        end
        integrity_check
#--}}}
      end
      def lockd_recover
#--{{{
        return nil unless @attempt_lockd_recovery
        warn{ "attempting lockd recovery" }
        time = Time::now
        ret = nil

        @lockd_recover_lockf.lock do
          Util::uncache @dirname rescue nil
          Util::uncache @path rescue nil
          Util::uncache @lockfile rescue nil
          Util::uncache @lockd_recover rescue nil
          mtime = File::stat(@lockd_recover).mtime rescue time

          if mtime > time
            warn{ "skipping lockd recovery (another node has already recovered)" }
            ret = true
          else
            moved = false
            begin
              FileUtils::touch @lockd_recover
              @lockd_recovered = false

              begin
                report = <<-msg
                  hostname : #{ Util::hostname }
                  pid      : #{ Process.pid }
                  time     : #{ Time::now }
                  q        :
                    path : #{ @dirname }
                    stat : #{ File::stat(@dirname).inspect }
                  db       :
                    path : #{ @path }
                    stat : #{ File::stat(@path).inspect }
                  lockfile :
                    path : #{ @lockfile }
                    stat : #{ File::stat(@lockfile).inspect }
                msg
                info{ "LOCKD RECOVERY REPORT" }
                logger << report
                cmd = "mail -s LOCKD_RECOVERY ara.t.howard@noaa.gov <<eof\n#{ report }\neof"
                Util::system cmd
              rescue
                nil
              end

              warn{ "sleeping #{ @lockd_recover_wait }s before continuing..." }
              sleep @lockd_recover_wait

              tmp = "#{ @dirname }.tmp"
              FileUtils::rm_rf tmp
              FileUtils::mv @dirname, tmp
              moved = true

              rfiles = [@path, @lockfile].map{|f| File::join(tmp,File::basename(f))}
              rfiles.each do |f|
                ftmp = "#{ f }.tmp"
                FileUtils::rm_rf ftmp
                FileUtils::cp f, ftmp
                FileUtils::rm f
                FileUtils::mv ftmp, f
              end

              dbtmp = File::join(tmp,File::basename(@path))

              if integrity_check(dbtmp)
                FileUtils::mv tmp, @dirname
                FileUtils::cp @lockd_recover_lockf.path, @lockd_recover
                @lockd_recovered = true
                Util::uncache @dirname rescue nil
                Util::uncache @path rescue nil
                Util::uncache @lockfile rescue nil
                Util::uncache @lockd_recover rescue nil
                warn{ "lockd recovery complete" }
              else
                FileUtils::mv tmp, @dirname
                @lockd_recovered = false
                error{ "lockd recovery failed" }
              end

              ret = @lockd_recovered
            ensure
              if moved and not @lockd_recovered and tmp and test(?d, tmp)
                FileUtils::mv tmp, @dirname
              end
            end
          end
        end
        ret
#--}}}
      end
      def integrity_check path = @path
#--{{{
        debug{ "running integrity_check on <#{ path }>" }
        klass.integrity_check(path)
#--}}}
      end
      def lock opts = {}
#--{{{
        ret = nil
        lockd_recover_wrap do
          aquire_lock(opts) do
            ret = yield
          end
        end
        ret
#--}}}
      end
      alias write_lock lock
      alias wlock write_lock
      def read_lock(opts = {}, &block)
#--{{{
        opts['read_only'] = true
        lock opts, &block
#--}}}
      end
      alias rlock read_lock
#--}}}
    end # class QDB
#--}}}
  end # module RQ
$__rq_qdb__ = __FILE__
end


text:
#include <stdio.h>
#include <stdlib.h>
#include <vicNl.h>

#define MAX_CHANGE 0.9

static char vcid[] = "$Id$";

double snow_density(snow_data_struct *snow, double new_snow, double sswq, double Tgrnd, double Tair, double dt)
{
/**********************************************************************
  snow_density		Keith Cherkauer		May 28, 1997

  This subroutine computes the snow density based on swe and snow metamorphism.

  One of two algorithms may be used, depending on the value of options.SNOW_DENSITY:

    DENS_SNTHRM = Algorithm is taken from SNTHERM89, adjusted for an essentially
		  single-layer model.

      UNITS:
	new_snow	mm	new snow
	sswq		m	initial snow pack snow water equivalent (before adding new snowfall)
	Tgrnd		C	ground temperature
	Tair		C	air temperature
	dt		h	time step length
	density		kg/m^3	snow density

    DENS_BRAS   = Original algorithm, originally based on a plot of seasonal
		  variation of typical snow densities found in Bras (figure 6.10,
		  p 258).  Because this equation was developed by regression
		  against data from Southern Manitoba, it therefore is limited
		  in applicability to other regions.

      UNITS:
	new_snow	         mm	new snow
	air_temp	         C	current air temperature
	swq		m	snow water equivalent
	depth		m	snow pack depth
	density            kg/m^3   snow density

  Modified:
  08-19-99 Added check to make sure that the change in snowpack depth
           due to new snow does not exceed the actual depth of the
	   pack.							Bart
  06-30-03 Added check to keep compression from aging from exceeding
           the actual depth of the snowpack.				KAC
  08-Oct-03 Modified the checks on delta_depth (mentioned above)
	    so that the condition is delta_depth > MAX_CHANGE*depth.	TJB
  08-Oct-03 Modified compression due to aging to only be calculated
	    if depth > 0.						TJB
  2008-Feb-17 Moved parameters related to snow densification to
	      snow.h.							TJB
  2008-Feb-17 Replaced previous algorithm with one based on SNTHERM89
	      adjusted for an essentially single-layer model.		KMA via TJB
  2008-Apr-21 Added option to use previous algorithm for backwards
	      compatibility.  DENS_BRAS = original algorithm; DENS_SNTHRM
	      = SNTHERM89.						TJB

**********************************************************************/

  extern option_struct   options;
  double density_new;
  double density;
  double depth;
  double swq;
  double CR; /* compaction rate */
  double dexpf;
  double ddz1; /* rate of settling of snowpack due to destructive metamorphism */
  double ddz2; /* rate of compaction of snowpack due to overburden */
  double Tavg; /* average snowpack temperature */
  double c3,c4; /* snow densification factors */
  double dm; /* upper snow density limit for the settling process */
  double Ps; /* snow load pressure (N/m^2) */
  double f; /* effective compaction coefficient */
  double overburden;
  double viscosity;
  double delta_depth;
  double depth_new;

  density = 0.0;

  /* Estimate density of new snow based on air temperature */
  if (new_snow > 0.)
    density_new = new_snow_density(Tair);
  else
    density_new = 0.0;

  /* Estimate average snowpack temperature */
//  Tavg = (snow->surf_temp+Tgrnd)/2.0+KELVIN;
  Tavg = snow->surf_temp+KELVIN;

  if (options.SNOW_DENSITY == DENS_SNTHRM) {

    if (new_snow > 0.) {
      if (snow->depth>0.0)
        density = snow->density;
      else
        density = density_new;
    }
    else {
      density = snow->density;
    }

    dexpf = exp(-SNDENS_C1*(KELVIN-Tavg));

    /* Settling due to destructive metamorphism */
    if (new_snow>0.0 && density_new>0.0)
      dm = (SNDENS_DMLIMIT > 1.15*density_new) ? SNDENS_DMLIMIT : 1.15*density_new;
    else
      dm = SNDENS_DMLIMIT;

    if (density <= dm) {
      c3 = 1.0;
      c4 = 1.0;
    }
    else {
      c3 = exp(-0.046*(density-dm));
      c4 = 1.0;
    }
    if ((snow->surf_water+snow->pack_water)/snow->depth > 0.01)
      c4 = 2.0; /* presence of wet snow */

    ddz1 = -SNDENS_C2 * c3* c4 * dexpf;

    /* Compaction due to overburden */
    // swq in this context is the amount of snow whose weight contributes to compaction
//    f = sswq/80. * exp(-sswq/100.);
    f = SNDENS_F;
    swq = new_snow/1000. + f*sswq; /* Currently VIC essentially has only one layer of snow, so compaction due to overburden will come mostly from new snowfall. */

    if (new_snow > 0.0) {
      Ps = 0.5*G*RHO_W*swq;
      ddz2 = -Ps / SNDENS_ETA0 * exp(-(-SNDENS_C5*(Tavg-KELVIN) + SNDENS_C6*density));
    }
    else {
      ddz2 = 0.0;
    }

    /* Calculate compaction rate and new snow density */
    CR = -ddz1-ddz2;
    density = density*(1+CR*dt*SECPHOUR);

  }

  else if (options.SNOW_DENSITY == DENS_BRAS) {

    depth = snow->depth;
    swq = sswq;

    /** Compaction of snow pack by new snow fall **/
    /** Bras pg. 257 **/

    if ( new_snow > 0 ) {

      if ( depth > 0. ) {

        /* Compact current snowpack by weight of new snowfall */
        delta_depth = ( ((new_snow / 25.4) * (depth / 0.0254)) / (swq / 0.0254)
                      * pow( (depth / 0.0254) / 10., 0.35) ) * 0.0254;
        if (delta_depth > MAX_CHANGE * depth) delta_depth = MAX_CHANGE * depth;
        depth_new = new_snow / density_new;
        depth = depth - delta_depth + depth_new;
        swq += new_snow / 1000.;
        density = 1000. * swq / depth;

      }
      else {

        /* no snowpack present, so snow density equals that of new snow */
        density  = density_new;
        swq     += new_snow / 1000.;
        depth    = 1000. * swq / density;

      }

    }
    else density = 1000. * swq / snow->depth;

    /** Densification of the snow pack due to aging **/
    /** based on SNTHRM89 R. Jordan 1991 - used in Bart's DHSVM code **/
    if ( depth > 0. ) {

      overburden  = 0.5 * G * RHO_W * swq;
      viscosity   = SNDENS_ETA0 * exp(-SNDENS_C5*(Tavg-KELVIN) + SNDENS_C6*density);
      delta_depth = overburden / viscosity * depth * dt * SECPHOUR;
      if (delta_depth > MAX_CHANGE * depth) delta_depth = MAX_CHANGE * depth;
      depth      -= delta_depth;
      density     = 1000. * swq / depth;

    }

  }

  return (density);

}

double new_snow_density(double air_temp) {
/**********************************************************************
  new_snow_density		Keith Cherkauer		May 28, 1997

  This routine estimates the density of new snow.

  Modified:
  2008-Feb-17 Modified to use the algorithm of Lundberg and
	      Pomeroy (1998).						KMA via TJB
  2008-Apr-21 Added option to use previous algorithm for backwards
	      compatibility.  DENS_BRAS = original algorithm; DENS_SNTHRM
	      = Lundberg and Pomeroy (1998).				TJB
**********************************************************************/
  extern option_struct   options;
  double density_new;

  density_new = 0.0;

  if (options.SNOW_DENSITY == DENS_SNTHRM) {
    density_new = 67.9 + 51.3 * exp(air_temp/2.6);
  }
  else if (options.SNOW_DENSITY == DENS_BRAS) {
    air_temp = air_temp * 9. / 5. + 32.;
    if(air_temp > 0) density_new = (double)NEW_SNOW_DENSITY + 1000.
		     * (air_temp / 100.) * (air_temp / 100.);
    else density_new = (double)NEW_SNOW_DENSITY;
  }

  return (density_new);

}

double snow_albedo(double new_snow,
                   double swq,
                   double depth,
                   double albedo,
                   double cold_content,
                   double dt,
                   int    last_snow,
		   char   MELTING) {
/**********************************************************************
  snow_albedo		Keith Cherkauer		June 10, 1997

  This subroutine computes the snow pack surface albedo.  Original version
  computed albedo as a function of snow age and season, based on the algorithm
  of the US Army Corps of Engineers.  More recently, added the option to
  use the algorithm of Sun et al., 1999, which depends only on snow age and
  cold content (independent of time of year).

  Modified:
  06-15-02 Added MELTING flag which tells the algorithm whether or not
           the pack was melting previously.  This locks the albedo
           onto the lower ablation albedo curve until a sufficiently
           large new snow event resets the surface albedo.       KAC
  2008-Apr-21 Added flag to include new albedo calculation based on
	      albedo algorithm described in Sun, S., J. Jin, and Y. Xue,
	      A simple snow-atmosphere-soil transfer model, J. Geophys. Res.,
	      104 (D16), 19,587-19,597, 1999.				KAC via TJB
**********************************************************************/

  extern option_struct   options;

  /** New Snow **/
  if(new_snow > TraceSnow  && cold_content < 0.0 ) albedo = NEW_SNOW_ALB;

  /** Aged Snow **/
  else if(swq > 0.0) {

    /* Accumulation season */
    if ( cold_content < 0.0 && !MELTING )
      albedo = NEW_SNOW_ALB*pow(SNOW_ALB_ACCUM_A,
			  pow((double)last_snow * dt / 24.,
			      SNOW_ALB_ACCUM_B));

    /* Melt Season */
    else
      albedo = NEW_SNOW_ALB*pow(SNOW_ALB_THAW_A,
			  pow((double)last_snow * dt / 24.,
			      SNOW_ALB_THAW_B));
  }

  else
    /* No snow falling or present */
    albedo = 0;

  return(albedo);

}

redpajama_set_name: RedPajamaGithub


text:
package lambda

import (
	"io"
	"sync"
	"time"

	"github.com/awslabs/aws-sdk-go/aws"
)

var oprw sync.Mutex

// AddPermissionRequest generates a request for the AddPermission operation.
func (c *Lambda) AddPermissionRequest(input *AddPermissionInput) (req *aws.Request, output *AddPermissionOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opAddPermission == nil {
		opAddPermission = &aws.Operation{
			Name:       "AddPermission",
			HTTPMethod: "POST",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/policy",
		}
	}

	if input == nil {
		input = &AddPermissionInput{}
	}

	req = c.newRequest(opAddPermission, input, output)
	output = &AddPermissionOutput{}
	req.Data = output
	return
}

// Adds a permission to the access policy associated with the specified AWS
// Lambda function. In a "push event" model, the access policy attached to the
// Lambda function grants Amazon S3 or a user application permission for the
// Lambda lambda:Invoke action. For information about the push model, see AWS
// Lambda: How it Works (http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html).
// Each Lambda function has one access policy associated with it. You can use
// the AddPermission API to add a permission to the policy. You have one access
// policy but it can have multiple permission statements.
//
// This operation requires permission for the lambda:AddPermission action.
func (c *Lambda) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) {
	req, out := c.AddPermissionRequest(input)
	err := req.Send()
	return out, err
}

var opAddPermission *aws.Operation

// CreateEventSourceMappingRequest generates a request for the CreateEventSourceMapping operation.
func (c *Lambda) CreateEventSourceMappingRequest(input *CreateEventSourceMappingInput) (req *aws.Request, output *EventSourceMappingConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opCreateEventSourceMapping == nil {
		opCreateEventSourceMapping = &aws.Operation{
			Name:       "CreateEventSourceMapping",
			HTTPMethod: "POST",
			HTTPPath:   "/2015-03-31/event-source-mappings/",
		}
	}

	if input == nil {
		input = &CreateEventSourceMappingInput{}
	}

	req = c.newRequest(opCreateEventSourceMapping, input, output)
	output = &EventSourceMappingConfiguration{}
	req.Data = output
	return
}

// Identifies a stream as an event source for a Lambda function. It can be either
// an Amazon Kinesis stream or an Amazon DynamoDB stream. AWS Lambda invokes
// the specified function when records are posted to the stream.
//
// This is the pull model, where AWS Lambda invokes the function. For more
// information, go to AWS Lambda: How it Works (http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html)
// in the AWS Lambda Developer Guide.
//
// This association between an Amazon Kinesis stream and a Lambda function
// is called the event source mapping. You provide the configuration information
// (for example, which stream to read from and which Lambda function to invoke)
// for the event source mapping in the request body.
//
//  Each event source, such as an Amazon Kinesis or a DynamoDB stream, can
// be associated with multiple AWS Lambda function. A given Lambda function
// can be associated with multiple AWS event sources.
//
// This operation requires permission for the lambda:CreateEventSourceMapping
// action.
func (c *Lambda) CreateEventSourceMapping(input *CreateEventSourceMappingInput) (*EventSourceMappingConfiguration, error) {
	req, out := c.CreateEventSourceMappingRequest(input)
	err := req.Send()
	return out, err
}

var opCreateEventSourceMapping *aws.Operation

// CreateFunctionRequest generates a request for the CreateFunction operation.
func (c *Lambda) CreateFunctionRequest(input *CreateFunctionInput) (req *aws.Request, output *FunctionConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opCreateFunction == nil {
		opCreateFunction = &aws.Operation{
			Name:       "CreateFunction",
			HTTPMethod: "POST",
			HTTPPath:   "/2015-03-31/functions",
		}
	}

	if input == nil {
		input = &CreateFunctionInput{}
	}

	req = c.newRequest(opCreateFunction, input, output)
	output = &FunctionConfiguration{}
	req.Data = output
	return
}

// Creates a new Lambda function. The function metadata is created from the
// request parameters, and the code for the function is provided by a .zip file
// in the request body. If the function name already exists, the operation will
// fail. Note that the function name is case-sensitive.
//
// This operation requires permission for the lambda:CreateFunction action.
func (c *Lambda) CreateFunction(input *CreateFunctionInput) (*FunctionConfiguration, error) {
	req, out := c.CreateFunctionRequest(input)
	err := req.Send()
	return out, err
}

var opCreateFunction *aws.Operation

// DeleteEventSourceMappingRequest generates a request for the DeleteEventSourceMapping operation.
func (c *Lambda) DeleteEventSourceMappingRequest(input *DeleteEventSourceMappingInput) (req *aws.Request, output *EventSourceMappingConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opDeleteEventSourceMapping == nil {
		opDeleteEventSourceMapping = &aws.Operation{
			Name:       "DeleteEventSourceMapping",
			HTTPMethod: "DELETE",
			HTTPPath:   "/2015-03-31/event-source-mappings/{UUID}",
		}
	}

	if input == nil {
		input = &DeleteEventSourceMappingInput{}
	}

	req = c.newRequest(opDeleteEventSourceMapping, input, output)
	output = &EventSourceMappingConfiguration{}
	req.Data = output
	return
}

// Removes an event source mapping. This means AWS Lambda will no longer invoke
// the function for events in the associated source.
//
// This operation requires permission for the lambda:DeleteEventSourceMapping
// action.
func (c *Lambda) DeleteEventSourceMapping(input *DeleteEventSourceMappingInput) (*EventSourceMappingConfiguration, error) {
	req, out := c.DeleteEventSourceMappingRequest(input)
	err := req.Send()
	return out, err
}

var opDeleteEventSourceMapping *aws.Operation

// DeleteFunctionRequest generates a request for the DeleteFunction operation.
func (c *Lambda) DeleteFunctionRequest(input *DeleteFunctionInput) (req *aws.Request, output *DeleteFunctionOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opDeleteFunction == nil {
		opDeleteFunction = &aws.Operation{
			Name:       "DeleteFunction",
			HTTPMethod: "DELETE",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}",
		}
	}

	if input == nil {
		input = &DeleteFunctionInput{}
	}

	req = c.newRequest(opDeleteFunction, input, output)
	output = &DeleteFunctionOutput{}
	req.Data = output
	return
}

// Deletes the specified Lambda function code and configuration.
//
// When you delete a function the associated access policy is also deleted.
// You will need to delete the event source mappings explicitly.
//
// This operation requires permission for the lambda:DeleteFunction action.
func (c *Lambda) DeleteFunction(input *DeleteFunctionInput) (*DeleteFunctionOutput, error) {
	req, out := c.DeleteFunctionRequest(input)
	err := req.Send()
	return out, err
}

var opDeleteFunction *aws.Operation

// GetEventSourceMappingRequest generates a request for the GetEventSourceMapping operation.
func (c *Lambda) GetEventSourceMappingRequest(input *GetEventSourceMappingInput) (req *aws.Request, output *EventSourceMappingConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opGetEventSourceMapping == nil {
		opGetEventSourceMapping = &aws.Operation{
			Name:       "GetEventSourceMapping",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/event-source-mappings/{UUID}",
		}
	}

	if input == nil {
		input = &GetEventSourceMappingInput{}
	}

	req = c.newRequest(opGetEventSourceMapping, input, output)
	output = &EventSourceMappingConfiguration{}
	req.Data = output
	return
}

// Returns configuration information for the specified event source mapping
// (see CreateEventSourceMapping).
//
// This operation requires permission for the lambda:GetEventSourceMapping
// action.
func (c *Lambda) GetEventSourceMapping(input *GetEventSourceMappingInput) (*EventSourceMappingConfiguration, error) {
	req, out := c.GetEventSourceMappingRequest(input)
	err := req.Send()
	return out, err
}

var opGetEventSourceMapping *aws.Operation

// GetFunctionRequest generates a request for the GetFunction operation.
func (c *Lambda) GetFunctionRequest(input *GetFunctionInput) (req *aws.Request, output *GetFunctionOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opGetFunction == nil {
		opGetFunction = &aws.Operation{
			Name:       "GetFunction",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD",
		}
	}

	if input == nil {
		input = &GetFunctionInput{}
	}

	req = c.newRequest(opGetFunction, input, output)
	output = &GetFunctionOutput{}
	req.Data = output
	return
}

// Returns the configuration information of the Lambda function and a presigned
// URL link to the .zip file you uploaded with CreateFunction so you can download
// the .zip file. Note that the URL is valid for up to 10 minutes. The configuration
// information is the same information you provided as parameters when uploading
// the function.
//
// This operation requires permission for the lambda:GetFunction action.
func (c *Lambda) GetFunction(input *GetFunctionInput) (*GetFunctionOutput, error) {
	req, out := c.GetFunctionRequest(input)
	err := req.Send()
	return out, err
}

var opGetFunction *aws.Operation

// GetFunctionConfigurationRequest generates a request for the GetFunctionConfiguration operation.
func (c *Lambda) GetFunctionConfigurationRequest(input *GetFunctionConfigurationInput) (req *aws.Request, output *FunctionConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opGetFunctionConfiguration == nil {
		opGetFunctionConfiguration = &aws.Operation{
			Name:       "GetFunctionConfiguration",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/configuration",
		}
	}

	if input == nil {
		input = &GetFunctionConfigurationInput{}
	}

	req = c.newRequest(opGetFunctionConfiguration, input, output)
	output = &FunctionConfiguration{}
	req.Data = output
	return
}

// Returns the configuration information of the Lambda function. This the same
// information you provided as parameters when uploading the function by using
// CreateFunction.
//
// This operation requires permission for the lambda:GetFunctionConfiguration
// operation.
func (c *Lambda) GetFunctionConfiguration(input *GetFunctionConfigurationInput) (*FunctionConfiguration, error) {
	req, out := c.GetFunctionConfigurationRequest(input)
	err := req.Send()
	return out, err
}

var opGetFunctionConfiguration *aws.Operation

// GetPolicyRequest generates a request for the GetPolicy operation.
func (c *Lambda) GetPolicyRequest(input *GetPolicyInput) (req *aws.Request, output *GetPolicyOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opGetPolicy == nil {
		opGetPolicy = &aws.Operation{
			Name:       "GetPolicy",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/policy",
		}
	}

	if input == nil {
		input = &GetPolicyInput{}
	}

	req = c.newRequest(opGetPolicy, input, output)
	output = &GetPolicyOutput{}
	req.Data = output
	return
}

// Returns the access policy, containing a list of permissions granted via the
// AddPermission API, associated with the specified bucket.
//
// You need permission for the lambda:GetPolicy action.
func (c *Lambda) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) {
	req, out := c.GetPolicyRequest(input)
	err := req.Send()
	return out, err
}

var opGetPolicy *aws.Operation

// InvokeRequest generates a request for the Invoke operation.
func (c *Lambda) InvokeRequest(input *InvokeInput) (req *aws.Request, output *InvokeOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opInvoke == nil {
		opInvoke = &aws.Operation{
			Name:       "Invoke",
			HTTPMethod: "POST",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/invocations",
		}
	}

	if input == nil {
		input = &InvokeInput{}
	}

	req = c.newRequest(opInvoke, input, output)
	output = &InvokeOutput{}
	req.Data = output
	return
}

// Invokes a specified Lambda function.
//
// This operation requires permission for the lambda:InvokeFunction action.
func (c *Lambda) Invoke(input *InvokeInput) (*InvokeOutput, error) {
	req, out := c.InvokeRequest(input)
	err := req.Send()
	return out, err
}

var opInvoke *aws.Operation

// InvokeAsyncRequest generates a request for the InvokeAsync operation.
func (c *Lambda) InvokeAsyncRequest(input *InvokeAsyncInput) (req *aws.Request, output *InvokeAsyncOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opInvokeAsync == nil {
		opInvokeAsync = &aws.Operation{
			Name:       "InvokeAsync",
			HTTPMethod: "POST",
			HTTPPath:   "/2014-11-13/functions/{FunctionName}/invoke-async/",
		}
	}

	if input == nil {
		input = &InvokeAsyncInput{}
	}

	req = c.newRequest(opInvokeAsync, input, output)
	output = &InvokeAsyncOutput{}
	req.Data = output
	return
}

// This API is deprecated. We recommend you use Invoke API (see Invoke). Submits
// an invocation request to AWS Lambda. Upon receiving the request, Lambda executes
// the specified function asynchronously. To see the logs generated by the Lambda
// function execution, see the CloudWatch logs console.
//
// This operation requires permission for the lambda:InvokeFunction action.
func (c *Lambda) InvokeAsync(input *InvokeAsyncInput) (*InvokeAsyncOutput, error) {
	req, out := c.InvokeAsyncRequest(input)
	err := req.Send()
	return out, err
}

var opInvokeAsync *aws.Operation

// ListEventSourceMappingsRequest generates a request for the ListEventSourceMappings operation.
func (c *Lambda) ListEventSourceMappingsRequest(input *ListEventSourceMappingsInput) (req *aws.Request, output *ListEventSourceMappingsOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opListEventSourceMappings == nil {
		opListEventSourceMappings = &aws.Operation{
			Name:       "ListEventSourceMappings",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/event-source-mappings/",
		}
	}

	if input == nil {
		input = &ListEventSourceMappingsInput{}
	}

	req = c.newRequest(opListEventSourceMappings, input, output)
	output = &ListEventSourceMappingsOutput{}
	req.Data = output
	return
}

// Returns a list of event source mappings you created using the CreateEventSourceMapping
// (see CreateEventSourceMapping), where you identify a stream as an event source.
// This list does not include Amazon S3 event sources.
//
// For each mapping, the API returns configuration information. You can optionally
// specify filters to retrieve specific event source mappings.
//
// This operation requires permission for the lambda:ListEventSourceMappings
// action.
func (c *Lambda) ListEventSourceMappings(input *ListEventSourceMappingsInput) (*ListEventSourceMappingsOutput, error) {
	req, out := c.ListEventSourceMappingsRequest(input)
	err := req.Send()
	return out, err
}

var opListEventSourceMappings *aws.Operation

// ListFunctionsRequest generates a request for the ListFunctions operation.
func (c *Lambda) ListFunctionsRequest(input *ListFunctionsInput) (req *aws.Request, output *ListFunctionsOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opListFunctions == nil {
		opListFunctions = &aws.Operation{
			Name:       "ListFunctions",
			HTTPMethod: "GET",
			HTTPPath:   "/2015-03-31/functions/",
		}
	}

	if input == nil {
		input = &ListFunctionsInput{}
	}

	req = c.newRequest(opListFunctions, input, output)
	output = &ListFunctionsOutput{}
	req.Data = output
	return
}

// Returns a list of your Lambda functions. For each function, the response
// includes the function configuration information. You must use GetFunction
// to retrieve the code for your function.
//
// This operation requires permission for the lambda:ListFunctions action.
func (c *Lambda) ListFunctions(input *ListFunctionsInput) (*ListFunctionsOutput, error) {
	req, out := c.ListFunctionsRequest(input)
	err := req.Send()
	return out, err
}

var opListFunctions *aws.Operation

// RemovePermissionRequest generates a request for the RemovePermission operation.
func (c *Lambda) RemovePermissionRequest(input *RemovePermissionInput) (req *aws.Request, output *RemovePermissionOutput) {
	oprw.Lock()
	defer oprw.Unlock()

	if opRemovePermission == nil {
		opRemovePermission = &aws.Operation{
			Name:       "RemovePermission",
			HTTPMethod: "DELETE",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/policy/{StatementId}",
		}
	}

	if input == nil {
		input = &RemovePermissionInput{}
	}

	req = c.newRequest(opRemovePermission, input, output)
	output = &RemovePermissionOutput{}
	req.Data = output
	return
}

// You can remove individual permissions from an access policy associated with
// a Lambda function by providing a Statement ID.
//
// Note that removal of a permission will cause an active event source to lose
// permission to the function.
//
// You need permission for the lambda:RemovePermission action.
func (c *Lambda) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) {
	req, out := c.RemovePermissionRequest(input)
	err := req.Send()
	return out, err
}

var opRemovePermission *aws.Operation

// UpdateEventSourceMappingRequest generates a request for the UpdateEventSourceMapping operation.
func (c *Lambda) UpdateEventSourceMappingRequest(input *UpdateEventSourceMappingInput) (req *aws.Request, output *EventSourceMappingConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opUpdateEventSourceMapping == nil {
		opUpdateEventSourceMapping = &aws.Operation{
			Name:       "UpdateEventSourceMapping",
			HTTPMethod: "PUT",
			HTTPPath:   "/2015-03-31/event-source-mappings/{UUID}",
		}
	}

	if input == nil {
		input = &UpdateEventSourceMappingInput{}
	}

	req = c.newRequest(opUpdateEventSourceMapping, input, output)
	output = &EventSourceMappingConfiguration{}
	req.Data = output
	return
}

// You can update an event source mapping. This is useful if you want to change
// the parameters of the existing mapping without losing your position in the
// stream. You can change which function will receive the stream records, but
// to change the stream itself, you must create a new mapping.
//
// This operation requires permission for the lambda:UpdateEventSourceMapping
// action.
func (c *Lambda) UpdateEventSourceMapping(input *UpdateEventSourceMappingInput) (*EventSourceMappingConfiguration, error) {
	req, out := c.UpdateEventSourceMappingRequest(input)
	err := req.Send()
	return out, err
}

var opUpdateEventSourceMapping *aws.Operation

// UpdateFunctionCodeRequest generates a request for the UpdateFunctionCode operation.
func (c *Lambda) UpdateFunctionCodeRequest(input *UpdateFunctionCodeInput) (req *aws.Request, output *FunctionConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opUpdateFunctionCode == nil {
		opUpdateFunctionCode = &aws.Operation{
			Name:       "UpdateFunctionCode",
			HTTPMethod: "PUT",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/code",
		}
	}

	if input == nil {
		input = &UpdateFunctionCodeInput{}
	}

	req = c.newRequest(opUpdateFunctionCode, input, output)
	output = &FunctionConfiguration{}
	req.Data = output
	return
}

// Updates the code for the specified Lambda function. This operation must only
// be used on an existing Lambda function and cannot be used to update the function
// configuration.
//
// This operation requires permission for the lambda:UpdateFunctionCode action.
func (c *Lambda) UpdateFunctionCode(input *UpdateFunctionCodeInput) (*FunctionConfiguration, error) {
	req, out := c.UpdateFunctionCodeRequest(input)
	err := req.Send()
	return out, err
}

var opUpdateFunctionCode *aws.Operation

// UpdateFunctionConfigurationRequest generates a request for the UpdateFunctionConfiguration operation.
func (c *Lambda) UpdateFunctionConfigurationRequest(input *UpdateFunctionConfigurationInput) (req *aws.Request, output *FunctionConfiguration) {
	oprw.Lock()
	defer oprw.Unlock()

	if opUpdateFunctionConfiguration == nil {
		opUpdateFunctionConfiguration = &aws.Operation{
			Name:       "UpdateFunctionConfiguration",
			HTTPMethod: "PUT",
			HTTPPath:   "/2015-03-31/functions/{FunctionName}/versions/HEAD/configuration",
		}
	}

	if input == nil {
		input = &UpdateFunctionConfigurationInput{}
	}

	req = c.newRequest(opUpdateFunctionConfiguration, input, output)
	output = &FunctionConfiguration{}
	req.Data = output
	return
}

// Updates the configuration parameters for the specified Lambda function by
// using the values provided in the request. You provide only the parameters
// you want to change. This operation must only be used on an existing Lambda
// function and cannot be used to update the function's code.
//
// This operation requires permission for the lambda:UpdateFunctionConfiguration
// action.
func (c *Lambda) UpdateFunctionConfiguration(input *UpdateFunctionConfigurationInput) (*FunctionConfiguration, error) {
	req, out := c.UpdateFunctionConfigurationRequest(input)
	err := req.Send()
	return out, err
}

var opUpdateFunctionConfiguration *aws.Operation

type AddPermissionInput struct {
	// The AWS Lambda action you want to allow in this statement. Each Lambda action
	// is a string starting with "lambda:" followed by the API name (see Operations).
	// For example, "lambda:CreateFunction". You can use wildcard ("lambda:*") to
	// grant permission for all AWS Lambda actions.
	Action *string `type:"string" required:"true"`

	// Name of the Lambda function whose access policy you are updating by adding
	// a new permission.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// The principal who is getting this permission. It can be Amazon S3 service
	// Principal ("s3.amazonaws.com") if you want Amazon S3 to invoke the function,
	// an AWS account ID if you are granting cross-account permission, or any valid
	// AWS service principal such as "sns.amazonaws.com". For example, you might
	// want to allow a custom application in another AWS account to push events
	// to AWS Lambda by invoking your function.
	Principal *string `type:"string" required:"true"`

	// This is optional; however, when granting Amazon S3 permission to invoke your
	// function, you should specify this field with the bucket Amazon Resource Name
	// (ARN) as its value. This ensures that only events generated from the specified
	// bucket can invoke the function.
	//
	// If you add a permission for the Amazon S3 principal without providing the
	// source ARN, any AWS account that creates a mapping to your function ARN can
	// send events to invoke your Lambda function from Amazon S3.
	SourceARN *string `locationName:"SourceArn" type:"string"`

	// The AWS account ID (without a hyphen) of the source owner. If the SourceArn
	// identifies a bucket, then this is the bucket owner's account ID. You can
	// use this additional condition to ensure the bucket you specify is owned by
	// a specific account (it is possible the bucket owner deleted the bucket and
	// some other AWS account created the bucket). You can also use this condition
	// to specify all sources (that is, you don't specify the SourceArn) owned by
	// a specific account.
	SourceAccount *string `type:"string"`

	// A unique statement identifier.
	StatementID *string `locationName:"StatementId" type:"string" required:"true"`

	metadataAddPermissionInput `json:"-" xml:"-"`
}

type metadataAddPermissionInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type AddPermissionOutput struct {
	// The permission statement you specified in the request. The response returns
	// the same as a string using "\" as an escape character in the JSON.
	Statement *string `type:"string"`

	metadataAddPermissionOutput `json:"-" xml:"-"`
}

type metadataAddPermissionOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type CreateEventSourceMappingInput struct {
	// The largest number of records that AWS Lambda will retrieve from your event
	// source at the time of invoking your function. Your function receives an event
	// with all the retrieved records. The default is 100 records.
	BatchSize *int64 `type:"integer"`

	// Indicates whether AWS Lambda should begin polling the event source.
	Enabled *bool `type:"boolean"`

	// The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the event
	// source. Any record added to this stream could cause AWS Lambda to invoke
	// your Lambda function, it depends on the BatchSize. AWS Lambda POSTs the Amazon
	// Kinesis event, containing records, to your Lambda function as JSON.
	EventSourceARN *string `locationName:"EventSourceArn" type:"string" required:"true"`

	// The Lambda function to invoke when AWS Lambda detects an event on the stream.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `type:"string" required:"true"`

	// The position in the stream where AWS Lambda should start reading. For more
	// information, go to ShardIteratorType (http://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html#Kinesis-GetShardIterator-request-ShardIteratorType)
	// in the Amazon Kinesis API Reference.
	StartingPosition *string `type:"string" required:"true"`

	metadataCreateEventSourceMappingInput `json:"-" xml:"-"`
}

type metadataCreateEventSourceMappingInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type CreateFunctionInput struct {
	// A structure that includes ZipFile.
	Code *FunctionCode `type:"structure" required:"true"`

	// A short, user-defined function description. Lambda does not use this value.
	// Assign a meaningful description as you see fit.
	Description *string `type:"string"`

	// The name you want to assign to the function you are uploading. You can specify
	// an unqualified function name (for example, "Thumbnail") or you can specify
	// Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail").
	// AWS Lambda also allows you to specify only the account ID qualifier (for
	// example, "account-id:Thumbnail"). Note that the length constraint applies
	// only to the ARN. If you specify only the function name, it is limited to
	// 64 character in length. The function names appear in the console and are
	// returned in the ListFunctions API. Function names are used to specify functions
	// to other AWS Lambda APIs, such as Invoke.
	FunctionName *string `type:"string" required:"true"`

	// The function within your code that Lambda calls to begin execution. For Node.js,
	// it is the module-name.export value in your function.
	Handler *string `type:"string" required:"true"`

	// The amount of memory, in MB, your Lambda function is given. Lambda uses this
	// memory size to infer the amount of CPU and memory allocated to your function.
	// Your function use-case determines your CPU and memory requirements. For example,
	// a database operation might need less memory compared to an image processing
	// function. The default value is 128 MB. The value must be a multiple of 64
	// MB.
	MemorySize *int64 `type:"integer"`

	// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it
	// executes your function to access any other Amazon Web Services (AWS) resources.
	// For more information, see AWS Lambda: How it Works (http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html)
	Role *string `type:"string" required:"true"`

	// The runtime environment for the Lambda function you are uploading. Currently,
	// Lambda supports only "nodejs" as the runtime.
	Runtime *string `type:"string" required:"true"`

	// The function execution time at which Lambda should terminate the function.
	// Because the execution time has cost implications, we recommend you set this
	// value based on your expected execution time. The default is 3 seconds.
	Timeout *int64 `type:"integer"`

	metadataCreateFunctionInput `json:"-" xml:"-"`
}

type metadataCreateFunctionInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type DeleteEventSourceMappingInput struct {
	// The event source mapping ID.
	UUID *string `location:"uri" locationName:"UUID" type:"string" required:"true"`

	metadataDeleteEventSourceMappingInput `json:"-" xml:"-"`
}

type metadataDeleteEventSourceMappingInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type DeleteFunctionInput struct {
	// The Lambda function to delete.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	metadataDeleteFunctionInput `json:"-" xml:"-"`
}

type metadataDeleteFunctionInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type DeleteFunctionOutput struct {
	metadataDeleteFunctionOutput `json:"-" xml:"-"`
}

type metadataDeleteFunctionOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

// Describes mapping between an Amazon Kinesis stream and a Lambda function.
type EventSourceMappingConfiguration struct {
	// The largest number of records that AWS Lambda will retrieve from your event
	// source at the time of invoking your function. Your function receives an event
	// with all the retrieved records.
	BatchSize *int64 `type:"integer"`

	// The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source
	// of events.
	EventSourceARN *string `locationName:"EventSourceArn" type:"string"`

	// The Lambda function to invoke when AWS Lambda detects an event on the stream.
	FunctionARN *string `locationName:"FunctionArn" type:"string"`

	// The UTC time string indicating the last time the event mapping was updated.
	LastModified *time.Time `type:"timestamp" timestampFormat:"unix"`

	// The result of the last AWS Lambda invocation of your Lambda function.
	LastProcessingResult *string `type:"string"`

	// The state of the event source mapping. It can be "Creating", "Enabled", "Disabled",
	// "Enabling", "Disabling", "Updating", or "Deleting".
	State *string `type:"string"`

	// The reason the event source mapping is in its current state. It is either
	// user-requested or an AWS Lambda-initiated state transition.
	StateTransitionReason *string `type:"string"`

	// The AWS Lambda assigned opaque identifier for the mapping.
	UUID *string `type:"string"`

	metadataEventSourceMappingConfiguration `json:"-" xml:"-"`
}

type metadataEventSourceMappingConfiguration struct {
	SDKShapeTraits bool `type:"structure"`
}

// The code for the Lambda function.
type FunctionCode struct {
	// A base64-encoded .zip file containing your packaged source code. For more
	// information about creating a .zip file, go to Execution Permissions (http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html)
	// in the AWS Lambda Developer Guide.
	ZipFile []byte `type:"blob"`

	metadataFunctionCode `json:"-" xml:"-"`
}

type metadataFunctionCode struct {
	SDKShapeTraits bool `type:"structure"`
}

// The object for the Lambda function location.
type FunctionCodeLocation struct {
	// The presigned URL you can use to download the function's .zip file that you
	// previously uploaded. The URL is valid for up to 10 minutes.
	Location *string `type:"string"`

	// The repository from which you can download the function.
	RepositoryType *string `type:"string"`

	metadataFunctionCodeLocation `json:"-" xml:"-"`
}

type metadataFunctionCodeLocation struct {
	SDKShapeTraits bool `type:"structure"`
}

// A complex type that describes function metadata.
type FunctionConfiguration struct {
	// The size, in bytes, of the function .zip file you uploaded.
	CodeSize *int64 `type:"long"`

	// The user-provided description.
	Description *string `type:"string"`

	// The Amazon Resource Name (ARN) assigned to the function.
	FunctionARN *string `locationName:"FunctionArn" type:"string"`

	// The name of the function.
	FunctionName *string `type:"string"`

	// The function Lambda calls to begin executing your function.
	Handler *string `type:"string"`

	// The timestamp of the last time you updated the function.
	LastModified *string `type:"string"`

	// The memory size, in MB, you configured for the function. Must be a multiple
	// of 64 MB.
	MemorySize *int64 `type:"integer"`

	// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it
	// executes your function to access any other Amazon Web Services (AWS) resources.
	Role *string `type:"string"`

	// The runtime environment for the Lambda function.
	Runtime *string `type:"string"`

	// The function execution time at which Lambda should terminate the function.
	// Because the execution time has cost implications, we recommend you set this
	// value based on your expected execution time. The default is 3 seconds.
	Timeout *int64 `type:"integer"`

	metadataFunctionConfiguration `json:"-" xml:"-"`
}

type metadataFunctionConfiguration struct {
	SDKShapeTraits bool `type:"structure"`
}

type GetEventSourceMappingInput struct {
	// The AWS Lambda assigned ID of the event source mapping.
	UUID *string `location:"uri" locationName:"UUID" type:"string" required:"true"`

	metadataGetEventSourceMappingInput `json:"-" xml:"-"`
}

type metadataGetEventSourceMappingInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type GetFunctionConfigurationInput struct {
	// The name of the Lambda function for which you want to retrieve the configuration
	// information.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	metadataGetFunctionConfigurationInput `json:"-" xml:"-"`
}

type metadataGetFunctionConfigurationInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type GetFunctionInput struct {
	// The Lambda function name.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	metadataGetFunctionInput `json:"-" xml:"-"`
}

type metadataGetFunctionInput struct {
	SDKShapeTraits bool `type:"structure"`
}

// This response contains the object for the Lambda function location (see API_FunctionCodeLocation
type GetFunctionOutput struct {
	// The object for the Lambda function location.
	Code *FunctionCodeLocation `type:"structure"`

	// A complex type that describes function metadata.
	Configuration *FunctionConfiguration `type:"structure"`

	metadataGetFunctionOutput `json:"-" xml:"-"`
}

type metadataGetFunctionOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type GetPolicyInput struct {
	// Function name whose access policy you want to retrieve.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	metadataGetPolicyInput `json:"-" xml:"-"`
}

type metadataGetPolicyInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type GetPolicyOutput struct {
	// The access policy associated with the specified function. The response returns
	// the same as a string using "\" as an escape character in the JSON.
	Policy *string `type:"string"`

	metadataGetPolicyOutput `json:"-" xml:"-"`
}

type metadataGetPolicyOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type InvokeAsyncInput struct {
	// The Lambda function name.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// JSON that you want to provide to your Lambda function as input.
	InvokeArgs io.ReadSeeker `type:"blob" required:"true"`

	metadataInvokeAsyncInput `json:"-" xml:"-"`
}

type metadataInvokeAsyncInput struct {
	SDKShapeTraits bool `type:"structure" payload:"InvokeArgs"`
}

// Upon success, it returns empty response. Otherwise, throws an exception.
type InvokeAsyncOutput struct {
	// It will be 202 upon success.
	Status *int64 `location:"statusCode" type:"integer"`

	metadataInvokeAsyncOutput `json:"-" xml:"-"`
}

type metadataInvokeAsyncOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type InvokeInput struct {
	// Using the ClientContext you can pass client-specific information to the Lambda
	// function you are invoking. You can then process the client information in
	// your Lambda function as you choose through the context variable. For an example
	// of a ClientContext JSON, go to PutEvents (http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html)
	// in the Amazon Mobile Analytics API Reference and User Guide.
	//
	// The ClientContext JSON must be base64-encoded.
	ClientContext *string `location:"header" locationName:"X-Amz-Client-Context" type:"string"`

	// The Lambda function name.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// By default, the Invoke API assumes "RequestResponse" invocation type. You
	// can optionally request asynchronous execution by specifying "Event" as the
	// InvocationType. You can also use this parameter to request AWS Lambda to
	// not execute the function but do some verification, such as if the caller
	// is authorized to invoke the function and if the inputs are valid. You request
	// this by specifying "DryRun" as the InvocationType. This is useful in a cross-account
	// scenario when you want to verify access to a function without running it.
	InvocationType *string `location:"header" locationName:"X-Amz-Invocation-Type" type:"string"`

	// You can set this optional parameter to "Tail" in the request only if you
	// specify the InvocationType parameter with value "RequestResponse". In this
	// case, AWS Lambda returns the base64-encoded last 4 KB of log data produced
	// by your Lambda function in the x-amz-log-results header.
	LogType *string `location:"header" locationName:"X-Amz-Log-Type" type:"string"`

	// JSON that you want to provide to your Lambda function as input.
	Payload []byte `type:"blob"`

	metadataInvokeInput `json:"-" xml:"-"`
}

type metadataInvokeInput struct {
	SDKShapeTraits bool `type:"structure" payload:"Payload"`
}

// Upon success, returns an empty response. Otherwise, throws an exception.
type InvokeOutput struct {
	// Indicates whether an error occurred while executing the Lambda function.
	// If an error occurred this field will have one of two values; Handled or Unhandled.
	// Handled errors are errors that are reported by the function while the Unhandled
	// errors are those detected and reported by AWS Lambda. Unhandled errors include
	// out of memory errors and function timeouts. For information about how to
	// report an Handled error, see Programming Model (http://docs.aws.amazon.com/lambda/latest/dg/programming-model.html).
	FunctionError *string `location:"header" locationName:"X-Amz-Function-Error" type:"string"`

	// It is the base64-encoded logs for the Lambda function invocation. This is
	// present only if the invocation type is "RequestResponse" and the logs were
	// requested.
	LogResult *string `location:"header" locationName:"X-Amz-Log-Result" type:"string"`

	// It is the JSON representation of the object returned by the Lambda function.
	// In This is present only if the invocation type is "RequestResponse".
	//
	// In the event of a function error this field contains a message describing
	// the error. For the Handled errors the Lambda function will report this message.
	// For Unhandled errors AWS Lambda reports the message.
	Payload []byte `type:"blob"`

	// The HTTP status code will be in the 200 range for successful request. For
	// the "RequestResonse" invocation type this status code will be 200. For the
	// "Event" invocation type this status code will be 202. For the "DryRun" invocation
	// type the status code will be 204.
	StatusCode *int64 `location:"statusCode" type:"integer"`

	metadataInvokeOutput `json:"-" xml:"-"`
}

type metadataInvokeOutput struct {
	SDKShapeTraits bool `type:"structure" payload:"Payload"`
}

type ListEventSourceMappingsInput struct {
	// The Amazon Resource Name (ARN) of the Amazon Kinesis stream.
	EventSourceARN *string `location:"querystring" locationName:"EventSourceArn" type:"string"`

	// The name of the Lambda function.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"querystring" locationName:"FunctionName" type:"string"`

	// Optional string. An opaque pagination token returned from a previous ListEventSourceMappings
	// operation. If present, specifies to continue the list from where the returning
	// call left off.
	Marker *string `location:"querystring" locationName:"Marker" type:"string"`

	// Optional integer. Specifies the maximum number of event sources to return
	// in response. This value must be greater than 0.
	MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"`

	metadataListEventSourceMappingsInput `json:"-" xml:"-"`
}

type metadataListEventSourceMappingsInput struct {
	SDKShapeTraits bool `type:"structure"`
}

// Contains a list of event sources (see API_EventSourceMappingConfiguration)
type ListEventSourceMappingsOutput struct {
	// An array of EventSourceMappingConfiguration objects.
	EventSourceMappings []*EventSourceMappingConfiguration `type:"list"`

	// A string, present if there are more event source mappings.
	NextMarker *string `type:"string"`

	metadataListEventSourceMappingsOutput `json:"-" xml:"-"`
}

type metadataListEventSourceMappingsOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type ListFunctionsInput struct {
	// Optional string. An opaque pagination token returned from a previous ListFunctions
	// operation. If present, indicates where to continue the listing.
	Marker *string `location:"querystring" locationName:"Marker" type:"string"`

	// Optional integer. Specifies the maximum number of AWS Lambda functions to
	// return in response. This parameter value must be greater than 0.
	MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"`

	metadataListFunctionsInput `json:"-" xml:"-"`
}

type metadataListFunctionsInput struct {
	SDKShapeTraits bool `type:"structure"`
}

// Contains a list of AWS Lambda function configurations (see FunctionConfiguration.
type ListFunctionsOutput struct {
	// A list of Lambda functions.
	Functions []*FunctionConfiguration `type:"list"`

	// A string, present if there are more functions.
	NextMarker *string `type:"string"`

	metadataListFunctionsOutput `json:"-" xml:"-"`
}

type metadataListFunctionsOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type RemovePermissionInput struct {
	// Lambda function whose access policy you want to remove a permission from.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// Statement ID of the permission to remove.
	StatementID *string `location:"uri" locationName:"StatementId" type:"string" required:"true"`

	metadataRemovePermissionInput `json:"-" xml:"-"`
}

type metadataRemovePermissionInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type RemovePermissionOutput struct {
	metadataRemovePermissionOutput `json:"-" xml:"-"`
}

type metadataRemovePermissionOutput struct {
	SDKShapeTraits bool `type:"structure"`
}

type UpdateEventSourceMappingInput struct {
	// The maximum number of stream records that can be sent to your Lambda function
	// for a single invocation.
	BatchSize *int64 `type:"integer"`

	// Specifies whether AWS Lambda should actively poll the stream or not. If disabled,
	// AWS Lambda will not poll the stream.
	Enabled *bool `type:"boolean"`

	// The Lambda function to which you want the stream records sent.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `type:"string"`

	// The event source mapping identifier.
	UUID *string `location:"uri" locationName:"UUID" type:"string" required:"true"`

	metadataUpdateEventSourceMappingInput `json:"-" xml:"-"`
}

type metadataUpdateEventSourceMappingInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type UpdateFunctionCodeInput struct {
	// The existing Lambda function name whose code you want to replace.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// Based64-encoded .zip file containing your packaged source code.
	ZipFile []byte `type:"blob" required:"true"`

	metadataUpdateFunctionCodeInput `json:"-" xml:"-"`
}

type metadataUpdateFunctionCodeInput struct {
	SDKShapeTraits bool `type:"structure"`
}

type UpdateFunctionConfigurationInput struct {
	// A short user-defined function description. AWS Lambda does not use this value.
	// Assign a meaningful description as you see fit.
	Description *string `type:"string"`

	// The name of the Lambda function.
	//
	//  You can specify an unqualified function name (for example, "Thumbnail")
	// or you can specify Amazon Resource Name (ARN) of the function (for example,
	// "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also
	// allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail").
	// Note that the length constraint applies only to the ARN. If you specify only
	// the function name, it is limited to 64 character in length.
	FunctionName *string `location:"uri" locationName:"FunctionName" type:"string" required:"true"`

	// The function that Lambda calls to begin executing your function. For Node.js,
	// it is the module-name.export value in your function.
	Handler *string `type:"string"`

	// The amount of memory, in MB, your Lambda function is given. AWS Lambda uses
	// this memory size to infer the amount of CPU allocated to your function. Your
	// function use-case determines your CPU and memory requirements. For example,
	// a database operation might need less memory compared to an image processing
	// function. The default value is 128 MB. The value must be a multiple of 64
	// MB.
	MemorySize *int64 `type:"integer"`

	// The Amazon Resource Name (ARN) of the IAM role that Lambda will assume when
	// it executes your function.
	Role *string `type:"string"`

	// The function execution time at which AWS Lambda should terminate the function.
	// Because the execution time has cost implications, we recommend you set this
	// value based on your expected execution time. The default is 3 seconds.
	Timeout *int64 `type:"integer"`

	metadataUpdateFunctionConfigurationInput `json:"-" xml:"-"`
}

type metadataUpdateFunctionConfigurationInput struct {
	SDKShapeTraits bool `type:"structure"`
}


text:
DROP SEQUENCE IF EXISTS "public"."books_id_seq";
CREATE SEQUENCE "public"."books_id_seq" INCREMENT 1 START 5 MAXVALUE 9223372036854775807 MINVALUE 1 CACHE 1;

-- ----------------------------
--  Table structure for books
-- ----------------------------
DROP TABLE IF EXISTS "public"."books";
CREATE TABLE "public"."books" (
	"id" int4 NOT NULL DEFAULT nextval('books_id_seq'::regclass),
	"title" varchar(255) NOT NULL COLLATE "default",
	"author" varchar(40) NOT NULL COLLATE "default",
	"description" text COLLATE "default"
)
WITH (OIDS=FALSE);

-- ----------------------------
--  Records of books
-- ----------------------------
BEGIN;
INSERT INTO "public"."books" VALUES ('1', 'JerBear goes to the City', 'Garnee Smashington', 'A young hipster bear seeks his fortune in the wild city of Irvine.');
INSERT INTO "public"."books" VALUES ('2', 'Swarley''s Big Day', 'Barney Stinson', 'Putting his Playbook aside, one man seeks a lifetime of happiness.');
INSERT INTO "public"."books" VALUES ('3', 'All Around the Roundabound', 'Anakin Groundsitter', 'The riveting tale of a young lad taking pod-racing lessons from an instructor with a dark secret.');
INSERT INTO "public"."books" VALUES ('4', 'Mastering Crossfire: You''ll get caught up in it', 'Freddie Wong', 'It''s sometime in the future, the ultimate challenge...  Crossfire!');
COMMIT;

-- ----------------------------
--  Alter sequences owned by
-- ----------------------------
ALTER SEQUENCE "public"."books_id_seq" RESTART 4 OWNED BY "books"."id";

-- ----------------------------
--  Primary key structure for table books
-- ----------------------------
ALTER TABLE "public"."books" ADD PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE;


text:
You can create records by calling the `createRecord` method on the store.

```js
store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});
```

The store object is available in controllers and routes using `this.store`.

Although `createRecord` is fairly straightforward, the only thing to watch out for
is that you cannot assign a promise as a relationship, currently.

For example, if you want to set the `author` property of a post, this would **not** work
if the `user` with id isn't already loaded into the store:

```js
var store = this.store;

store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum',
  author: store.find('user', 1)
});
```

However, you can easily set the relationship after the promise has fulfilled:

```js
var store = this.store;

var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

store.find('user', 1).then(function(user) {
  post.set('author', user);
});
```

### Deleting Records

Deleting records is just as straightforward as creating records. Just call `deleteRecord()`
on any instance of `DS.Model`. This flags the record as `isDeleted` and thus removes
it from `all()` queries on the `store`. The deletion can then be persisted using `save()`.
Alternatively, you can use the `destroyRecord` method to delete and persist at the same time.

```js
store.find('post', 1).then(function (post) {
  post.deleteRecord();
  post.get('isDeleted'); // => true
  post.save(); // => DELETE to /posts/1
});

// OR
store.find('post', 2).then(function (post) {
  post.destroyRecord(); // => DELETE to /posts/2
});
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Browser Mockups</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <link href="css/color-blue.css" rel="stylesheet">
	<link rel="stylesheet" href="css/prism.css">
    <link href="css/default.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                BrowserMockup

Style

Colors

How To

Fork Me On Github

a BOLD way to express things

Browser mockups are the new bold way to showcase your screenshots or apps, an easy to use and highly configurable. Colored using Google's material design specifications (5 Presets included more through SASS).

Styles

Colors

How To

Styles

Flat Mockup

http://superbootstrap.com

Sketch Mockup

2d Mockup

http://superbootstrap.com/UPERBOOTSTRAP/trunk/themes/BrowserMock/index.html

Column 5

http://superbootstrap.com/UPERBOOTSTRAP/trunk/themes/BrowserMock/index.html

Column 4

http://superbootstrap.com

Column 3

Colors

How To

Basic snippet to generate a Browser Mock, use the markup in the next code block to create a flat browser mock. It comes with pre defined color pre-sets which can easily be modified to any other color through SASS, which is included.

Change the class browser-window-flat to browser-window-sketch or browser-window-2d to change the styling.

Add class browser-window-round next to browser-window to turn corners rounded.

	<div class="browser-window browser-window-flat">
		<div class="bar">
			<div class="home"></div>
			<div class="address">
				<div class="search link"><a href="">LINK</a></div>
			</div>
			<div class="menu"></div>
		</div>
		<div class="content">
			<img src="CONTENT_LINK" />
		</div>
	</div>

designed by SuperBootstrap


text:
var mod = require('bencoding.securely'),
	crypto = mod.createXPlatformCrypto(),
	password = "foo123456789",
	plainText = "mary had a little lamb, little lamb, little lamb",
	iOSOutput = "duSnwv3AGC5ICbn//3sjiL2L6kUNEMPjq+hniRdL9ow+QjGcM+2pBCw+3h19LAc3ugdEB5/ftwNVAO9sStSoNQ==";

var encyptedText = crypto.encrypt(password,plainText);
Ti.API.info('encyptedText = ' + encyptedText);

var decryptedText = crypto.decrypt(password, encyptedText);
Ti.API.info('decryptedText = ' + decryptedText);
Ti.API.info('Do they match? = ' + ((decryptedText == plainText) ? 'Yes' : 'No'));
if(Ti.Platform.Android){
	Ti.API.info('Output Cross Platform? = ' + ((crypto.decrypt(password, iOSOutput)==decryptedText) ? 'Yes' : 'No'));
}


text:
from __future__ import unicode_literals

import logging
import logging.config  # needed when logging_config doesn't start with logging.config
from copy import copy

from django.conf import settings
from django.core import mail
from django.core.mail import get_connection
from django.core.management.color import color_style
from django.utils.module_loading import import_string
from django.views.debug import ExceptionReporter

# Default logging for Django. This sends an email to the site admins on every
# HTTP 500 error. Depending on DEBUG, all other log records are either sent to
# the console (DEBUG=True) or discarded (DEBUG=False) by means of the
# require_debug_true filter.
DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'formatters': {
        'django.server': {
            '()': 'django.utils.log.ServerFormatter',
            'format': '[%(server_time)s] %(message)s',
        }
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        },
        'django.server': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'django.server',
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
        },
        'django.server': {
            'handlers': ['django.server'],
            'level': 'INFO',
            'propagate': False,
        },
    }
}

def configure_logging(logging_config, logging_settings):
    if logging_config:
        # First find the logging configuration function ...
        logging_config_func = import_string(logging_config)

        logging.config.dictConfig(DEFAULT_LOGGING)

        # ... then invoke it with the logging settings
        if logging_settings:
            logging_config_func(logging_settings)

class AdminEmailHandler(logging.Handler):
    """An exception log handler that emails log entries to site admins.

    If the request is passed as the first argument to the log record,
    request data will be provided in the email report.
    """

    def __init__(self, include_html=False, email_backend=None):
        logging.Handler.__init__(self)
        self.include_html = include_html
        self.email_backend = email_backend

    def emit(self, record):
        try:
            request = record.request
            subject = '%s (%s IP): %s' % (
                record.levelname,
                ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                 else 'EXTERNAL'),
                record.getMessage()
            )
        except Exception:
            subject = '%s: %s' % (
                record.levelname,
                record.getMessage()
            )
            request = None
        subject = self.format_subject(subject)

        # Since we add a nicely formatted traceback on our own, create a copy
        # of the log record without the exception data.
        no_exc_record = copy(record)
        no_exc_record.exc_info = None
        no_exc_record.exc_text = None

        if record.exc_info:
            exc_info = record.exc_info
        else:
            exc_info = (None, record.getMessage(), None)

        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
        html_message = reporter.get_traceback_html() if self.include_html else None
        self.send_mail(subject, message, fail_silently=True, html_message=html_message)

    def send_mail(self, subject, message, *args, **kwargs):
        mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)

    def connection(self):
        return get_connection(backend=self.email_backend, fail_silently=True)

    def format_subject(self, subject):
        """
        Escape CR and LF characters.
        """
        return subject.replace('\n', '\\n').replace('\r', '\\r')

class CallbackFilter(logging.Filter):
    """
    A logging filter that checks the return value of a given callable (which
    takes the record-to-be-logged as its only parameter) to decide whether to
    log a record.
    """
    def __init__(self, callback):
        self.callback = callback

    def filter(self, record):
        if self.callback(record):
            return 1
        return 0

class RequireDebugFalse(logging.Filter):
    def filter(self, record):
        return not settings.DEBUG

class RequireDebugTrue(logging.Filter):
    def filter(self, record):
        return settings.DEBUG

class ServerFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        self.style = color_style()
        super(ServerFormatter, self).__init__(*args, **kwargs)

    def format(self, record):
        msg = record.msg
        status_code = getattr(record, 'status_code', None)

        if status_code:
            if 200 <= status_code < 300:
                # Put 2XX first, since it should be the common case
                msg = self.style.HTTP_SUCCESS(msg)
            elif 100 <= status_code < 200:
                msg = self.style.HTTP_INFO(msg)
            elif status_code == 304:
                msg = self.style.HTTP_NOT_MODIFIED(msg)
            elif 300 <= status_code < 400:
                msg = self.style.HTTP_REDIRECT(msg)
            elif status_code == 404:
                msg = self.style.HTTP_NOT_FOUND(msg)
            elif 400 <= status_code < 500:
                msg = self.style.HTTP_BAD_REQUEST(msg)
            else:
                # Any 5XX, or any other status code
                msg = self.style.HTTP_SERVER_ERROR(msg)

        if self.uses_server_time() and not hasattr(record, 'server_time'):
            record.server_time = self.formatTime(record, self.datefmt)

        record.msg = msg
        return super(ServerFormatter, self).format(record)

    def uses_server_time(self):
        return self._fmt.find('%(server_time)') >= 0


text:
#include "Precompiled.h"
#include "extensions/CCSpine/AtlasAttachmentLoader.h"
#include "extensions/CCSpine/Extension.h"

NS_CC_BEGIN

Attachment* _AtlasAttachmentLoader_newAttachment ( AttachmentLoader* loader, Skin* skin, AttachmentType type, const KDchar* name )
{
	AtlasAttachmentLoader*	self = SUB_CAST ( AtlasAttachmentLoader, loader );
	switch ( type )
	{
		case ATTACHMENT_REGION :
		{
			AtlasRegion*	region = Atlas_findRegion ( self->atlas, name );
			if ( !region )
			{
				_AttachmentLoader_setError ( loader, "Region not found: ", name );
				return 0;
			}
			RegionAttachment*	attachment = RegionAttachment_create ( name );
			attachment->region = region;
			return SUPER ( attachment );
		}

		default :
			_AttachmentLoader_setUnknownTypeError ( loader, type );
			return 0;
	}
}

AtlasAttachmentLoader* AtlasAttachmentLoader_create ( Atlas* atlas )
{
	AtlasAttachmentLoader*	self = NEW ( AtlasAttachmentLoader );
	_AttachmentLoader_init ( SUPER ( self ), _AttachmentLoader_deinit, _AtlasAttachmentLoader_newAttachment );
	self->atlas = atlas;
	return self;
}

NS_CC_END


text:
<!--[metadata]>
+++
title = "Build your own bridge"
description = "Learn how to build your own bridge interface"
keywords = ["docker, bridge, docker0, network"]
[menu.main]
parent = "smn_networking_def"
+++
<![end-metadata]-->

# Build your own bridge

This section explains how to build your own bridge to replace the Docker default
bridge. This is a `bridge` network named `bridge` created automatically when you
install Docker.

> **Note**: The [Docker networks feature](../dockernetworks.md) allows you to
create user-defined networks in addition to the default bridge network.

You can set up your own bridge before starting Docker and use `-b BRIDGE` or
`--bridge=BRIDGE` to tell Docker to use your bridge instead. If you already
have Docker up and running with its default `docker0` still configured,
you can directly create your bridge and restart Docker with it or want to begin by
stopping the service and removing the interface:

```
# Stopping Docker and removing docker0

$ sudo service docker stop
$ sudo ip link set dev docker0 down
$ sudo brctl delbr docker0
$ sudo iptables -t nat -F POSTROUTING
```

Then, before starting the Docker service, create your own bridge and give it
whatever configuration you want. Here we will create a simple enough bridge
that we really could just have used the options in the previous section to
customize `docker0`, but it will be enough to illustrate the technique.

```
# Create our own bridge

$ sudo brctl addbr bridge0
$ sudo ip addr add 192.168.5.1/24 dev bridge0
$ sudo ip link set dev bridge0 up

# Confirming that our bridge is up and running

$ ip addr show bridge0
4: bridge0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state UP group default
    link/ether 66:38:d0:0d:76:18 brd ff:ff:ff:ff:ff:ff
    inet 192.168.5.1/24 scope global bridge0
       valid_lft forever preferred_lft forever

# Tell Docker about it and restart (on Ubuntu)

$ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker
$ sudo service docker start

# Confirming new outgoing NAT masquerade is set up

$ sudo iptables -t nat -L -n
...
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  192.168.5.0/24      0.0.0.0/0
```

The result should be that the Docker server starts successfully and is now
prepared to bind containers to the new bridge. After pausing to verify the
bridge's configuration, try creating a container -- you will see that its IP
address is in your new IP address range, which Docker will have auto-detected.

You can use the `brctl show` command to see Docker add and remove interfaces
from the bridge as you start and stop containers, and can run `ip addr` and `ip
route` inside a container to see that it has been given an address in the
bridge's IP address range and has been told to use the Docker host's IP address
on the bridge as its default gateway to the rest of the Internet.