text:
(function (b, c, d, e) {

/* document | [] | prototype | null */

  /*
   * init function (internal use)
   * a = selector, dom element or function
   */
  function i(a) {
    c.push.apply(this, a && a.nodeType ? [a] : '' + a === a ? b.querySelectorAll(a) : e)
  }

  /*
   * $ main function
   * a = css selector, dom object, or function
   * http://www.dustindiaz.com/smallest-domready-ever
   * returns instance or executes function on ready
   */
  $=function (a) {
    // no dependencies
    return /^f/.test(typeof a)?
             /c/.test(b.readyState)?
               a():
               $(b).on('DOMContentLoaded', a)
             :new i(a)
  }

  // set ki prototype
  $[d] = i[d] = {

    length: 0, // default length

    /* on method
     * a = string event type i.e 'click'
     * b = function
     * return this
     */
    on: function (a, b) {
      return this.each(function (c) {
        c.addEventListener(a, b)
      })
    },

    /* off method
     * a = string event type i.e 'click'
     * b = function
     * return this
     */
    off: function (a, b) {
      return this.each(function (c) {
        c.removeEventListener(a, b)
      })
    },

    /*
     * each method
     * use native forEach to iterate collection
     * a = the function to call on each iteration
     * i = the index for that function
     */
    each: function (a, i,z) {
      c.forEach.call(this, a, i,z)
      return this
    },

    // for some reason is needed to get an array-like
    // representation instead of an object
    splice: c.splice
  }
}(/*b*/document,/*c*/[],/*d*/'prototype'/*e*/));

// taken from ki.extend.js
(function() {

  // map some classlist functions to the jQuery counterpart
  var props = ['addClass', 'removeClass', 'toggleClass'],
  maps = ['add', 'remove', 'toggle'];

  props.forEach(function(prop, index) {
    $.prototype[prop] = function(a) {
      return this.each(function(b) {
        b.classList[maps[index]](a);
      });
    };
  });

  $.prototype.hasClass = function(a) {
    return this[0].classList.contains(a);
  };

  $.prototype.append = function(a) {
    return this.each(function(b) {
      b.appendChild(a[0]);
    });
  };

  $.prototype.prepend = function(a) {
    return this.each(function(b) {
      b.insertBefore(a[0], b.parentNode.firstChild);
    });
  };

  $.prototype.hide = function() {
    return this.each(function(b) {
      b.style.display = 'none';
    });
  };

  $.prototype.show = function() {
    return this.each(function(b) {
      b.style.display = '';
    });
  };

  $.prototype.attr = function(a, b) {
    return b === []._ ? this[0].getAttribute(a) : this.each(function(c) {
      c.setAttribute(a,
        (typeof b==='function')?
          b(c.getAttribute(a)):
          b
      );
    });
  };

  // by ansuz
  $.prototype.data = function(a,b){
    return b === []._ ? this[0].getAttribute('data-'+a) : this.each(function(c){
      c.setAttribute('data-'+a,b);
    });
  };

  $.prototype.removeAttr = function(a) {
    return this.each(function(b) {
      b.removeAttribute(a);
    });
  };

  $.prototype.hasAttr = function(a) {
    return this[0].hasAttribute(a);
  };

  $.prototype.before = function(a) {
    return this.each(function(b) {
      b.insertAdjacentHTML('beforebegin', a);
    });
  };

  $.prototype.after = function(a) {
    return this.each(function(b) {
      b.insertAdjacentHTML('afterend', a);
    });
  };

  $.prototype.css = function(a, b) {
    if(typeof a ==='object'){
      var that=this;
      Object.keys(a).map(function(prop){
        that.each(function(c) {
          c.style[prop] = a[prop];
        });
      });
      return this;
    }else{
      return b === []._ ? this[0].style[a] : this.each(function(c) {
        c.style[a] = b;
      });
    }
  };

  $.prototype.first = function() {
    return $(this[0]);
  };

  $.prototype.last = function() {
    return $(this[this.length - 1]);
  };

  $.prototype.get = function(a) {
    return $(this[a]);
  };

  $.prototype.text = function(a) {
    return a === []._ ? this[0].textContent : this.each(function(b) {
      b.textContent = a;
    });
  };

  $.prototype.html = function(a) {
    return a === []._ ? this[0].innerHTML : this.each(function(b) {
      b.innerHTML = (typeof a === 'function')?
        a(b.innerHTML):
        a;
    });
  };

  $.prototype.parent = function() {
    return (this.length < 2) ? $(this[0].parentNode): [];
  };

  $.prototype.next = function(){
    return $(this[0].nextElementSibling);
  };

  // it would be nice if 'sel' could be a function
  // maybe 'find by regex'? that would go a long way
  // isn't quite working?
  $.prototype.find = function(sel){
    sel=sel||'*';
    return (this.length < 2)? $(this[0].querySelectorAll(sel)):[];
  };

  $.prototype.remove = function() {
    return this.each(function(b) {
      b.parentNode.removeChild(b);
    });
  };

  $.prototype.trigger = function(a) {
    if (document.createEvent) {
      var event = document.createEvent('HTMLEvents');
      event.initEvent(a, true, false);
      this.each(function(b) {
        b.dispatchEvent(event);
      });
    } else {
      this.each(function(b) {
        b.fireEvent('on' + a);
      });
    }
  };

  $.prototype.is = function(a) {
    var m = (this[0].matches || this[0].matchesSelector || this[0].msMatchesSelector || this[0].mozMatchesSelector || this[0].webkitMatchesSelector || this[0].oMatchesSelector);
    if (m) {
      return m.call(this[0], a);
    } else {
      var n = this[0].parentNode.querySelectorAll(a);
      for (var i = n.length; i--;) {
        if (n[i] === this[0]) {
          return true;
        }
      }
      return false;
    }
  };

  $.prototype.create=function(type,id){
    var temp=document.createElement(type);
    if(id)temp.id=id;
    this[0].appendChild(temp);
    return temp;
  };

  $.prototype.resize=function(e,f){
    e.addEventListener('resize',f);
  };

  $.stop = function(e) {
    if (!e.preventDefault) {
      e.returnValue = false;
    } else {
      e.preventDefault();
    }
  };

  $.prototype.offset=function(el){
    el=this[0];
    var _x = 0, _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
  };

  $.param = function(obj, prefix) {
    var str = [];
    for(var p in obj) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ? $.param(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
    return str.join("&");
  };

  $.ajax = function(opt){  // a tiny little ajax function
    opt.callback||function(x){
      console.log(x);
    };
    var content=opt.content||false;
    var type = content?"POST":"GET";
    var url=opt.url||'/';
    opt.stack=[];
    opt.then=function(next){
      opt.stack.push(next);
      return opt;
    };
    var call=function(){

    };

    var jax = new XMLHttpRequest();
    jax.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
        opt.callback(this.responseText);
      }
    }
    jax.open(type, url, true);
    jax.send(type==='POST'?
      Object.keys(b)
        .map(function(k){
          return k+'='+b[k];
        }).join('&'):null);
    return opt;
  };
}());


text:
<TITLE>Review for Muppets From Space (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Muppets From Space (1999)

reviewed by
Steve Rhodes

MUPPETS FROM SPACE
A film review by Steve Rhodes
Copyright 1999 Steve Rhodes
RATING (0 TO ****):  *

Sometimes franchises just lose their appeal.  Other times, the concept
is still viable but the material isn't worthy of them.

For whatever reason, the latest Muppet movie, MUPPETS FROM SPACE, isn't
the least bit funny.  The old Muppet magic, seen in abundance in their
last movie, MUPPET TREASURE ISLAND, is gone.  Like a chef who has lost
the recipe to his signature entrée, long-time Muppet screenwriter Jerry
Juhl (along with Joey Mazzarino and Ken Kaufman) has trouble fashioning
a single memorable moment this time.

It all starts out when Gonzo (Dave Goelz) gets a message in his Kap'n
Alphabet cereal.  "Watch the sky," the little colored cereal bits spell
out for him.  Soon other places in the world from the Pyramids to
Stonehenge are getting the message: "R U THERE" emblazed on them.  Even
the famous Hollywood sign turns into a misspelled variation, "R U
THREE."

After Gonzo is hit by lightning, or perhaps it was a spaceship beam, he
decides he has alien links.  Two guys dressed like characters from MEN
IN BLACK show up claiming to be members of the Society for the
Prevention of Cruelty to Aliens.  Actually, they want to whisk him away
to a secret government agency that is investigating extraterrestrial
life.  Once there, he and his gang are chased by men with guns.

Ever on the prowl for something to laugh at in relatively humorless
comedies, I was able to find little this time.  Perhaps the closest to
an amusing line comes from Rizzo the Rat (Steve Whitmire) when he is
afraid.  "I never disobeyed my mother, and I never carried the plague,
even once," he claims, as his eyes look to the heavens.

The best that can be said of the movie is that it is so inoffensively
bland that families need not worry about the ages of their kids.  Anyone
can see the movie, but many are going to be disappointed.

MUPPETS FROM SPACE runs a mercifully short 1:27.  It is rated G and
would be acceptable for all ages.

My son Jeffrey, age 10, hated the movie, giving it just 1/2 of a star.
He thought it was "dumb, dumb, and dumber" and never funny.  His friend
Nickolas, age 10, thought it was pretty funny, except for the ending,
and gave it ***.  His friend Alan, age 10, loved it and gave it ****,
finding it hilarious.

Email: Steve.Rhodes@InternetReviews.com
Web: http://www.InternetReviews.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
package webrtc

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/pion/dtls/v2"
	"github.com/pion/dtls/v2/pkg/crypto/fingerprint"
	"github.com/pion/interceptor"
	"github.com/pion/logging"
	"github.com/pion/rtcp"
	"github.com/pion/srtp/v2"
	"github.com/pion/webrtc/v3/internal/mux"
	"github.com/pion/webrtc/v3/internal/util"
	"github.com/pion/webrtc/v3/pkg/rtcerr"
)

// DTLSTransport allows an application access to information about the DTLS
// transport over which RTP and RTCP packets are sent and received by
// RTPSender and RTPReceiver, as well other data such as SCTP packets sent
// and received by data channels.
type DTLSTransport struct {
	lock sync.RWMutex

	iceTransport          *ICETransport
	certificates          []Certificate
	remoteParameters      DTLSParameters
	remoteCertificate     []byte
	state                 DTLSTransportState
	srtpProtectionProfile srtp.ProtectionProfile

	onStateChangeHandler func(DTLSTransportState)

	conn *dtls.Conn

	srtpSession, srtcpSession   atomic.Value
	srtpEndpoint, srtcpEndpoint *mux.Endpoint
	simulcastStreams            []*srtp.ReadStreamSRTP
	srtpReady                   chan struct{}

	dtlsMatcher mux.MatchFunc

	api *API
	log logging.LeveledLogger
}

// NewDTLSTransport creates a new DTLSTransport.
// This constructor is part of the ORTC API. It is not
// meant to be used together with the basic WebRTC API.
func (api *API) NewDTLSTransport(transport *ICETransport, certificates []Certificate) (*DTLSTransport, error) {
	t := &DTLSTransport{
		iceTransport: transport,
		api:          api,
		state:        DTLSTransportStateNew,
		dtlsMatcher:  mux.MatchDTLS,
		srtpReady:    make(chan struct{}),
		log:          api.settingEngine.LoggerFactory.NewLogger("DTLSTransport"),
	}

	if len(certificates) > 0 {
		now := time.Now()
		for _, x509Cert := range certificates {
			if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) {
				return nil, &rtcerr.InvalidAccessError{Err: ErrCertificateExpired}
			}
			t.certificates = append(t.certificates, x509Cert)
		}
	} else {
		sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
		if err != nil {
			return nil, &rtcerr.UnknownError{Err: err}
		}
		certificate, err := GenerateCertificate(sk)
		if err != nil {
			return nil, err
		}
		t.certificates = []Certificate{*certificate}
	}

	return t, nil
}

// ICETransport returns the currently-configured *ICETransport or nil
// if one has not been configured
func (t *DTLSTransport) ICETransport() *ICETransport {
	t.lock.RLock()
	defer t.lock.RUnlock()
	return t.iceTransport
}

// onStateChange requires the caller holds the lock
func (t *DTLSTransport) onStateChange(state DTLSTransportState) {
	t.state = state
	handler := t.onStateChangeHandler
	if handler != nil {
		handler(state)
	}
}

// OnStateChange sets a handler that is fired when the DTLS
// connection state changes.
func (t *DTLSTransport) OnStateChange(f func(DTLSTransportState)) {
	t.lock.Lock()
	defer t.lock.Unlock()
	t.onStateChangeHandler = f
}

// State returns the current dtls transport state.
func (t *DTLSTransport) State() DTLSTransportState {
	t.lock.RLock()
	defer t.lock.RUnlock()
	return t.state
}

// WriteRTCP sends a user provided RTCP packet to the connected peer. If no peer is connected the
// packet is discarded.
func (t *DTLSTransport) WriteRTCP(pkts []rtcp.Packet) (int, error) {
	raw, err := rtcp.Marshal(pkts)
	if err != nil {
		return 0, err
	}

	srtcpSession, err := t.getSRTCPSession()
	if err != nil {
		return 0, err
	}

	writeStream, err := srtcpSession.OpenWriteStream()
	if err != nil {
		return 0, fmt.Errorf("%w: %v", errPeerConnWriteRTCPOpenWriteStream, err)
	}

	if n, err := writeStream.Write(raw); err != nil {
		return n, err
	}
	return 0, nil
}

// GetLocalParameters returns the DTLS parameters of the local DTLSTransport upon construction.
func (t *DTLSTransport) GetLocalParameters() (DTLSParameters, error) {
	fingerprints := []DTLSFingerprint{}

	for _, c := range t.certificates {
		prints, err := c.GetFingerprints()
		if err != nil {
			return DTLSParameters{}, err
		}

		fingerprints = append(fingerprints, prints...)
	}

	return DTLSParameters{
		Role:         DTLSRoleAuto, // always returns the default role
		Fingerprints: fingerprints,
	}, nil
}

// GetRemoteCertificate returns the certificate chain in use by the remote side
// returns an empty list prior to selection of the remote certificate
func (t *DTLSTransport) GetRemoteCertificate() []byte {
	t.lock.RLock()
	defer t.lock.RUnlock()
	return t.remoteCertificate
}

func (t *DTLSTransport) startSRTP() error {
	srtpConfig := &srtp.Config{
		Profile:       t.srtpProtectionProfile,
		BufferFactory: t.api.settingEngine.BufferFactory,
		LoggerFactory: t.api.settingEngine.LoggerFactory,
	}
	if t.api.settingEngine.replayProtection.SRTP != nil {
		srtpConfig.RemoteOptions = append(
			srtpConfig.RemoteOptions,
			srtp.SRTPReplayProtection(*t.api.settingEngine.replayProtection.SRTP),
		)
	}

	if t.api.settingEngine.disableSRTPReplayProtection {
		srtpConfig.RemoteOptions = append(
			srtpConfig.RemoteOptions,
			srtp.SRTPNoReplayProtection(),
		)
	}

	if t.api.settingEngine.replayProtection.SRTCP != nil {
		srtpConfig.RemoteOptions = append(
			srtpConfig.RemoteOptions,
			srtp.SRTCPReplayProtection(*t.api.settingEngine.replayProtection.SRTCP),
		)
	}

	if t.api.settingEngine.disableSRTCPReplayProtection {
		srtpConfig.RemoteOptions = append(
			srtpConfig.RemoteOptions,
			srtp.SRTCPNoReplayProtection(),
		)
	}

	connState := t.conn.ConnectionState()
	err := srtpConfig.ExtractSessionKeysFromDTLS(&connState, t.role() == DTLSRoleClient)
	if err != nil {
		return fmt.Errorf("%w: %v", errDtlsKeyExtractionFailed, err)
	}

	srtpSession, err := srtp.NewSessionSRTP(t.srtpEndpoint, srtpConfig)
	if err != nil {
		return fmt.Errorf("%w: %v", errFailedToStartSRTP, err)
	}

	srtcpSession, err := srtp.NewSessionSRTCP(t.srtcpEndpoint, srtpConfig)
	if err != nil {
		return fmt.Errorf("%w: %v", errFailedToStartSRTCP, err)
	}

	t.srtpSession.Store(srtpSession)
	t.srtcpSession.Store(srtcpSession)
	close(t.srtpReady)
	return nil
}

func (t *DTLSTransport) getSRTPSession() (*srtp.SessionSRTP, error) {
	if value, ok := t.srtpSession.Load().(*srtp.SessionSRTP); ok {
		return value, nil
	}

	return nil, errDtlsTransportNotStarted
}

func (t *DTLSTransport) getSRTCPSession() (*srtp.SessionSRTCP, error) {
	if value, ok := t.srtcpSession.Load().(*srtp.SessionSRTCP); ok {
		return value, nil
	}

	return nil, errDtlsTransportNotStarted
}

func (t *DTLSTransport) role() DTLSRole {
	// If remote has an explicit role use the inverse
	switch t.remoteParameters.Role {
	case DTLSRoleClient:
		return DTLSRoleServer
	case DTLSRoleServer:
		return DTLSRoleClient
	default:
	}

	// If SettingEngine has an explicit role
	switch t.api.settingEngine.answeringDTLSRole {
	case DTLSRoleServer:
		return DTLSRoleServer
	case DTLSRoleClient:
		return DTLSRoleClient
	default:
	}

	// Remote was auto and no explicit role was configured via SettingEngine
	if t.iceTransport.Role() == ICERoleControlling {
		return DTLSRoleServer
	}
	return defaultDtlsRoleAnswer
}

// Start DTLS transport negotiation with the parameters of the remote DTLS transport
func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error {
	// Take lock and prepare connection, we must not hold the lock
	// when connecting
	prepareTransport := func() (DTLSRole, *dtls.Config, error) {
		t.lock.Lock()
		defer t.lock.Unlock()

		if err := t.ensureICEConn(); err != nil {
			return DTLSRole(0), nil, err
		}

		if t.state != DTLSTransportStateNew {
			return DTLSRole(0), nil, &rtcerr.InvalidStateError{Err: fmt.Errorf("%w: %s", errInvalidDTLSStart, t.state)}
		}

		t.srtpEndpoint = t.iceTransport.newEndpoint(mux.MatchSRTP)
		t.srtcpEndpoint = t.iceTransport.newEndpoint(mux.MatchSRTCP)
		t.remoteParameters = remoteParameters

		cert := t.certificates[0]
		t.onStateChange(DTLSTransportStateConnecting)

		return t.role(), &dtls.Config{
			Certificates: []tls.Certificate{
				{
					Certificate: [][]byte{cert.x509Cert.Raw},
					PrivateKey:  cert.privateKey,
				},
			},
			SRTPProtectionProfiles: func() []dtls.SRTPProtectionProfile {
				if len(t.api.settingEngine.srtpProtectionProfiles) > 0 {
					return t.api.settingEngine.srtpProtectionProfiles
				}

				return defaultSrtpProtectionProfiles()
			}(),
			ClientAuth:         dtls.RequireAnyClientCert,
			LoggerFactory:      t.api.settingEngine.LoggerFactory,
			InsecureSkipVerify: true,
		}, nil
	}

	var dtlsConn *dtls.Conn
	dtlsEndpoint := t.iceTransport.newEndpoint(mux.MatchDTLS)
	role, dtlsConfig, err := prepareTransport()
	if err != nil {
		return err
	}

	if t.api.settingEngine.replayProtection.DTLS != nil {
		dtlsConfig.ReplayProtectionWindow = int(*t.api.settingEngine.replayProtection.DTLS)
	}

	if t.api.settingEngine.dtls.retransmissionInterval != 0 {
		dtlsConfig.FlightInterval = t.api.settingEngine.dtls.retransmissionInterval
	}

	// Connect as DTLS Client/Server, function is blocking and we
	// must not hold the DTLSTransport lock
	if role == DTLSRoleClient {
		dtlsConn, err = dtls.Client(dtlsEndpoint, dtlsConfig)
	} else {
		dtlsConn, err = dtls.Server(dtlsEndpoint, dtlsConfig)
	}

	// Re-take the lock, nothing beyond here is blocking
	t.lock.Lock()
	defer t.lock.Unlock()

	if err != nil {
		t.onStateChange(DTLSTransportStateFailed)
		return err
	}

	srtpProfile, ok := dtlsConn.SelectedSRTPProtectionProfile()
	if !ok {
		t.onStateChange(DTLSTransportStateFailed)
		return ErrNoSRTPProtectionProfile
	}

	switch srtpProfile {
	case dtls.SRTP_AEAD_AES_128_GCM:
		t.srtpProtectionProfile = srtp.ProtectionProfileAeadAes128Gcm
	case dtls.SRTP_AES128_CM_HMAC_SHA1_80:
		t.srtpProtectionProfile = srtp.ProtectionProfileAes128CmHmacSha1_80
	default:
		t.onStateChange(DTLSTransportStateFailed)
		return ErrNoSRTPProtectionProfile
	}

	// Check the fingerprint if a certificate was exchanged
	remoteCerts := dtlsConn.ConnectionState().PeerCertificates
	if len(remoteCerts) == 0 {
		t.onStateChange(DTLSTransportStateFailed)
		return errNoRemoteCertificate
	}
	t.remoteCertificate = remoteCerts[0]

	if !t.api.settingEngine.disableCertificateFingerprintVerification {
		parsedRemoteCert, err := x509.ParseCertificate(t.remoteCertificate)
		if err != nil {
			if closeErr := dtlsConn.Close(); closeErr != nil {
				t.log.Error(err.Error())
			}

			t.onStateChange(DTLSTransportStateFailed)
			return err
		}

		if err = t.validateFingerPrint(parsedRemoteCert); err != nil {
			if closeErr := dtlsConn.Close(); closeErr != nil {
				t.log.Error(err.Error())
			}

			t.onStateChange(DTLSTransportStateFailed)
			return err
		}
	}

	t.conn = dtlsConn
	t.onStateChange(DTLSTransportStateConnected)

	return t.startSRTP()
}

// Stop stops and closes the DTLSTransport object.
func (t *DTLSTransport) Stop() error {
	t.lock.Lock()
	defer t.lock.Unlock()

	// Try closing everything and collect the errors
	var closeErrs []error

	if srtpSession, err := t.getSRTPSession(); err == nil && srtpSession != nil {
		closeErrs = append(closeErrs, srtpSession.Close())
	}

	if srtcpSession, err := t.getSRTCPSession(); err == nil && srtcpSession != nil {
		closeErrs = append(closeErrs, srtcpSession.Close())
	}

	for i := range t.simulcastStreams {
		closeErrs = append(closeErrs, t.simulcastStreams[i].Close())
	}

	if t.conn != nil {
		// dtls connection may be closed on sctp close.
		if err := t.conn.Close(); err != nil && !errors.Is(err, dtls.ErrConnClosed) {
			closeErrs = append(closeErrs, err)
		}
	}
	t.onStateChange(DTLSTransportStateClosed)
	return util.FlattenErrs(closeErrs)
}

func (t *DTLSTransport) validateFingerPrint(remoteCert *x509.Certificate) error {
	for _, fp := range t.remoteParameters.Fingerprints {
		hashAlgo, err := fingerprint.HashFromString(fp.Algorithm)
		if err != nil {
			return err
		}

		remoteValue, err := fingerprint.Fingerprint(remoteCert, hashAlgo)
		if err != nil {
			return err
		}

		if strings.EqualFold(remoteValue, fp.Value) {
			return nil
		}
	}

	return errNoMatchingCertificateFingerprint
}

func (t *DTLSTransport) ensureICEConn() error {
	if t.iceTransport == nil {
		return errICEConnectionNotStarted
	}

	return nil
}

func (t *DTLSTransport) storeSimulcastStream(s *srtp.ReadStreamSRTP) {
	t.lock.Lock()
	defer t.lock.Unlock()

	t.simulcastStreams = append(t.simulcastStreams, s)
}

func (t *DTLSTransport) streamsForSSRC(ssrc SSRC, streamInfo interceptor.StreamInfo) (*srtp.ReadStreamSRTP, interceptor.RTPReader, *srtp.ReadStreamSRTCP, interceptor.RTCPReader, error) {
	srtpSession, err := t.getSRTPSession()
	if err != nil {
		return nil, nil, nil, nil, err
	}

	rtpReadStream, err := srtpSession.OpenReadStream(uint32(ssrc))
	if err != nil {
		return nil, nil, nil, nil, err
	}

	rtpInterceptor := t.api.interceptor.BindRemoteStream(&streamInfo, interceptor.RTPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) {
		n, err = rtpReadStream.Read(in)
		return n, a, err
	}))

	srtcpSession, err := t.getSRTCPSession()
	if err != nil {
		return nil, nil, nil, nil, err
	}

	rtcpReadStream, err := srtcpSession.OpenReadStream(uint32(ssrc))
	if err != nil {
		return nil, nil, nil, nil, err
	}

	rtcpInterceptor := t.api.interceptor.BindRTCPReader(interceptor.RTPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) {
		n, err = rtcpReadStream.Read(in)
		return n, a, err
	}))

	return rtpReadStream, rtpInterceptor, rtcpReadStream, rtcpInterceptor, nil
}


text:
package org.springframework.boot.actuate.audit.listener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;

/**
 * The default {@link AbstractAuditListener} implementation. Listens for
 * {@link AuditApplicationEvent}s and stores them in a {@link AuditEventRepository}.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 * @author Vedran Pavic
 * @since 1.0.0
 */
public class AuditListener extends AbstractAuditListener {

	private static final Log logger = LogFactory.getLog(AuditListener.class);

	private final AuditEventRepository auditEventRepository;

	public AuditListener(AuditEventRepository auditEventRepository) {
		this.auditEventRepository = auditEventRepository;
	}

	@Override
	protected void onAuditEvent(AuditEvent event) {
		if (logger.isDebugEnabled()) {
			logger.debug(event);
		}
		this.auditEventRepository.add(event);
	}

}


text:
centos
Treat this as my coding log.


text:
package cloudstack

import (
	"encoding/json"
	"fmt"
	"net/url"
	"strconv"
	"strings"
)

type CreateAffinityGroupParams struct {
	p map[string]interface{}
}

func (p *CreateAffinityGroupParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["account"]; found {
		u.Set("account", v.(string))
	}
	if v, found := p.p["description"]; found {
		u.Set("description", v.(string))
	}
	if v, found := p.p["domainid"]; found {
		u.Set("domainid", v.(string))
	}
	if v, found := p.p["name"]; found {
		u.Set("name", v.(string))
	}
	if v, found := p.p["projectid"]; found {
		u.Set("projectid", v.(string))
	}
	if v, found := p.p["type"]; found {
		u.Set("type", v.(string))
	}
	return u
}

func (p *CreateAffinityGroupParams) SetAccount(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["account"] = v
	return
}

func (p *CreateAffinityGroupParams) SetDescription(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["description"] = v
	return
}

func (p *CreateAffinityGroupParams) SetDomainid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["domainid"] = v
	return
}

func (p *CreateAffinityGroupParams) SetName(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["name"] = v
	return
}

func (p *CreateAffinityGroupParams) SetProjectid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["projectid"] = v
	return
}

func (p *CreateAffinityGroupParams) SetType(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["affinityGroupType"] = v
	return
}

// You should always use this function to get a new CreateAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewCreateAffinityGroupParams(name string, affinityGroupType string) *CreateAffinityGroupParams {
	p := &CreateAffinityGroupParams{}
	p.p = make(map[string]interface{})
	p.p["name"] = name
	p.p["affinityGroupType"] = affinityGroupType
	return p
}

// Creates an affinity/anti-affinity group
func (s *AffinityGroupService) CreateAffinityGroup(p *CreateAffinityGroupParams) (*CreateAffinityGroupResponse, error) {
	resp, err := s.cs.newRequest("createAffinityGroup", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CreateAffinityGroupResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}

type CreateAffinityGroupResponse struct {
	JobID             string   `json:"jobid,omitempty"`
	Account           string   `json:"account,omitempty"`
	Description       string   `json:"description,omitempty"`
	Domain            string   `json:"domain,omitempty"`
	Domainid          string   `json:"domainid,omitempty"`
	Id                string   `json:"id,omitempty"`
	Name              string   `json:"name,omitempty"`
	Project           string   `json:"project,omitempty"`
	Projectid         string   `json:"projectid,omitempty"`
	Type              string   `json:"type,omitempty"`
	VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
}

type DeleteAffinityGroupParams struct {
	p map[string]interface{}
}

func (p *DeleteAffinityGroupParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["account"]; found {
		u.Set("account", v.(string))
	}
	if v, found := p.p["domainid"]; found {
		u.Set("domainid", v.(string))
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	if v, found := p.p["name"]; found {
		u.Set("name", v.(string))
	}
	if v, found := p.p["projectid"]; found {
		u.Set("projectid", v.(string))
	}
	return u
}

func (p *DeleteAffinityGroupParams) SetAccount(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["account"] = v
	return
}

func (p *DeleteAffinityGroupParams) SetDomainid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["domainid"] = v
	return
}

func (p *DeleteAffinityGroupParams) SetId(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["id"] = v
	return
}

func (p *DeleteAffinityGroupParams) SetName(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["name"] = v
	return
}

func (p *DeleteAffinityGroupParams) SetProjectid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["projectid"] = v
	return
}

// You should always use this function to get a new DeleteAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewDeleteAffinityGroupParams() *DeleteAffinityGroupParams {
	p := &DeleteAffinityGroupParams{}
	p.p = make(map[string]interface{})
	return p
}

// Deletes affinity group
func (s *AffinityGroupService) DeleteAffinityGroup(p *DeleteAffinityGroupParams) (*DeleteAffinityGroupResponse, error) {
	resp, err := s.cs.newRequest("deleteAffinityGroup", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteAffinityGroupResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}

type DeleteAffinityGroupResponse struct {
	JobID       string `json:"jobid,omitempty"`
	Displaytext string `json:"displaytext,omitempty"`
	Success     bool   `json:"success,omitempty"`
}

type ListAffinityGroupsParams struct {
	p map[string]interface{}
}

func (p *ListAffinityGroupsParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["account"]; found {
		u.Set("account", v.(string))
	}
	if v, found := p.p["domainid"]; found {
		u.Set("domainid", v.(string))
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	if v, found := p.p["isrecursive"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("isrecursive", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["listall"]; found {
		vv := strconv.FormatBool(v.(bool))
		u.Set("listall", vv)
	}
	if v, found := p.p["name"]; found {
		u.Set("name", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	if v, found := p.p["projectid"]; found {
		u.Set("projectid", v.(string))
	}
	if v, found := p.p["type"]; found {
		u.Set("type", v.(string))
	}
	if v, found := p.p["virtualmachineid"]; found {
		u.Set("virtualmachineid", v.(string))
	}
	return u
}

func (p *ListAffinityGroupsParams) SetAccount(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["account"] = v
	return
}

func (p *ListAffinityGroupsParams) SetDomainid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["domainid"] = v
	return
}

func (p *ListAffinityGroupsParams) SetId(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["id"] = v
	return
}

func (p *ListAffinityGroupsParams) SetIsrecursive(v bool) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["isrecursive"] = v
	return
}

func (p *ListAffinityGroupsParams) SetKeyword(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["keyword"] = v
	return
}

func (p *ListAffinityGroupsParams) SetListall(v bool) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["listall"] = v
	return
}

func (p *ListAffinityGroupsParams) SetName(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["name"] = v
	return
}

func (p *ListAffinityGroupsParams) SetPage(v int) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["page"] = v
	return
}

func (p *ListAffinityGroupsParams) SetPagesize(v int) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["pagesize"] = v
	return
}

func (p *ListAffinityGroupsParams) SetProjectid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["projectid"] = v
	return
}

func (p *ListAffinityGroupsParams) SetType(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["affinityGroupType"] = v
	return
}

func (p *ListAffinityGroupsParams) SetVirtualmachineid(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["virtualmachineid"] = v
	return
}

// You should always use this function to get a new ListAffinityGroupsParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewListAffinityGroupsParams() *ListAffinityGroupsParams {
	p := &ListAffinityGroupsParams{}
	p.p = make(map[string]interface{})
	return p
}

// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupID(name string, opts ...OptionFunc) (string, int, error) {
	p := &ListAffinityGroupsParams{}
	p.p = make(map[string]interface{})

	p.p["name"] = name

	for _, fn := range opts {
		if err := fn(s.cs, p); err != nil {
			return "", -1, err
		}
	}

	l, err := s.ListAffinityGroups(p)
	if err != nil {
		return "", -1, err
	}

	if l.Count == 0 {
		return "", l.Count, fmt.Errorf("No match found for %s: %+v", name, l)
	}

	if l.Count == 1 {
		return l.AffinityGroups[0].Id, l.Count, nil
	}

	if l.Count > 1 {
		for _, v := range l.AffinityGroups {
			if v.Name == name {
				return v.Id, l.Count, nil
			}
		}
	}
	return "", l.Count, fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}

// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupByName(name string, opts ...OptionFunc) (*AffinityGroup, int, error) {
	id, count, err := s.GetAffinityGroupID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetAffinityGroupByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}

// This is a courtesy helper function, which in some cases may not work as expected!
func (s *AffinityGroupService) GetAffinityGroupByID(id string, opts ...OptionFunc) (*AffinityGroup, int, error) {
	p := &ListAffinityGroupsParams{}
	p.p = make(map[string]interface{})

	p.p["id"] = id

	for _, fn := range opts {
		if err := fn(s.cs, p); err != nil {
			return nil, -1, err
		}
	}

	l, err := s.ListAffinityGroups(p)
	if err != nil {
		if strings.Contains(err.Error(), fmt.Sprintf(
			"Invalid parameter id value=%s due to incorrect long value format, "+
				"or entity does not exist", id)) {
			return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
		}
		return nil, -1, err
	}

	if l.Count == 0 {
		return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
	}

	if l.Count == 1 {
		return l.AffinityGroups[0], l.Count, nil
	}
	return nil, l.Count, fmt.Errorf("There is more then one result for AffinityGroup UUID: %s!", id)
}

// Lists affinity groups
func (s *AffinityGroupService) ListAffinityGroups(p *ListAffinityGroupsParams) (*ListAffinityGroupsResponse, error) {
	resp, err := s.cs.newRequest("listAffinityGroups", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListAffinityGroupsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}
	return &r, nil
}

type ListAffinityGroupsResponse struct {
	Count          int              `json:"count"`
	AffinityGroups []*AffinityGroup `json:"affinitygroup"`
}

type AffinityGroup struct {
	Account           string   `json:"account,omitempty"`
	Description       string   `json:"description,omitempty"`
	Domain            string   `json:"domain,omitempty"`
	Domainid          string   `json:"domainid,omitempty"`
	Id                string   `json:"id,omitempty"`
	Name              string   `json:"name,omitempty"`
	Project           string   `json:"project,omitempty"`
	Projectid         string   `json:"projectid,omitempty"`
	Type              string   `json:"type,omitempty"`
	VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
}

type UpdateVMAffinityGroupParams struct {
	p map[string]interface{}
}

func (p *UpdateVMAffinityGroupParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["affinitygroupids"]; found {
		vv := strings.Join(v.([]string), ",")
		u.Set("affinitygroupids", vv)
	}
	if v, found := p.p["affinitygroupnames"]; found {
		vv := strings.Join(v.([]string), ",")
		u.Set("affinitygroupnames", vv)
	}
	if v, found := p.p["id"]; found {
		u.Set("id", v.(string))
	}
	return u
}

func (p *UpdateVMAffinityGroupParams) SetAffinitygroupids(v []string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["affinitygroupids"] = v
	return
}

func (p *UpdateVMAffinityGroupParams) SetAffinitygroupnames(v []string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["affinitygroupnames"] = v
	return
}

func (p *UpdateVMAffinityGroupParams) SetId(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["id"] = v
	return
}

// You should always use this function to get a new UpdateVMAffinityGroupParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewUpdateVMAffinityGroupParams(id string) *UpdateVMAffinityGroupParams {
	p := &UpdateVMAffinityGroupParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}

// Updates the affinity/anti-affinity group associations of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect.
func (s *AffinityGroupService) UpdateVMAffinityGroup(p *UpdateVMAffinityGroupParams) (*UpdateVMAffinityGroupResponse, error) {
	resp, err := s.cs.newRequest("updateVMAffinityGroup", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r UpdateVMAffinityGroupResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}

type UpdateVMAffinityGroupResponse struct {
	JobID         string `json:"jobid,omitempty"`
	Account       string `json:"account,omitempty"`
	Affinitygroup []struct {
		Account           string   `json:"account,omitempty"`
		Description       string   `json:"description,omitempty"`
		Domain            string   `json:"domain,omitempty"`
		Domainid          string   `json:"domainid,omitempty"`
		Id                string   `json:"id,omitempty"`
		Name              string   `json:"name,omitempty"`
		Project           string   `json:"project,omitempty"`
		Projectid         string   `json:"projectid,omitempty"`
		Type              string   `json:"type,omitempty"`
		VirtualmachineIds []string `json:"virtualmachineIds,omitempty"`
	} `json:"affinitygroup,omitempty"`
	Cpunumber             int               `json:"cpunumber,omitempty"`
	Cpuspeed              int               `json:"cpuspeed,omitempty"`
	Cpuused               string            `json:"cpuused,omitempty"`
	Created               string            `json:"created,omitempty"`
	Details               map[string]string `json:"details,omitempty"`
	Diskioread            int64             `json:"diskioread,omitempty"`
	Diskiowrite           int64             `json:"diskiowrite,omitempty"`
	Diskkbsread           int64             `json:"diskkbsread,omitempty"`
	Diskkbswrite          int64             `json:"diskkbswrite,omitempty"`
	Diskofferingid        string            `json:"diskofferingid,omitempty"`
	Diskofferingname      string            `json:"diskofferingname,omitempty"`
	Displayname           string            `json:"displayname,omitempty"`
	Displayvm             bool              `json:"displayvm,omitempty"`
	Domain                string            `json:"domain,omitempty"`
	Domainid              string            `json:"domainid,omitempty"`
	Forvirtualnetwork     bool              `json:"forvirtualnetwork,omitempty"`
	Group                 string            `json:"group,omitempty"`
	Groupid               string            `json:"groupid,omitempty"`
	Guestosid             string            `json:"guestosid,omitempty"`
	Haenable              bool              `json:"haenable,omitempty"`
	Hostid                string            `json:"hostid,omitempty"`
	Hostname              string            `json:"hostname,omitempty"`
	Hypervisor            string            `json:"hypervisor,omitempty"`
	Id                    string            `json:"id,omitempty"`
	Instancename          string            `json:"instancename,omitempty"`
	Isdynamicallyscalable bool              `json:"isdynamicallyscalable,omitempty"`
	Isodisplaytext        string            `json:"isodisplaytext,omitempty"`
	Isoid                 string            `json:"isoid,omitempty"`
	Isoname               string            `json:"isoname,omitempty"`
	Keypair               string            `json:"keypair,omitempty"`
	Memory                int               `json:"memory,omitempty"`
	Name                  string            `json:"name,omitempty"`
	Networkkbsread        int64             `json:"networkkbsread,omitempty"`
	Networkkbswrite       int64             `json:"networkkbswrite,omitempty"`
	Nic                   []struct {
		Broadcasturi string `json:"broadcasturi,omitempty"`
		Deviceid     string `json:"deviceid,omitempty"`
		Gateway      string `json:"gateway,omitempty"`
		Id           string `json:"id,omitempty"`
		Ip6address   string `json:"ip6address,omitempty"`
		Ip6cidr      string `json:"ip6cidr,omitempty"`
		Ip6gateway   string `json:"ip6gateway,omitempty"`
		Ipaddress    string `json:"ipaddress,omitempty"`
		Isdefault    bool   `json:"isdefault,omitempty"`
		Isolationuri string `json:"isolationuri,omitempty"`
		Macaddress   string `json:"macaddress,omitempty"`
		Netmask      string `json:"netmask,omitempty"`
		Networkid    string `json:"networkid,omitempty"`
		Networkname  string `json:"networkname,omitempty"`
		Secondaryip  []struct {
			Id        string `json:"id,omitempty"`
			Ipaddress string `json:"ipaddress,omitempty"`
		} `json:"secondaryip,omitempty"`
		Traffictype      string `json:"traffictype,omitempty"`
		Type             string `json:"type,omitempty"`
		Virtualmachineid string `json:"virtualmachineid,omitempty"`
	} `json:"nic,omitempty"`
	Ostypeid        int64  `json:"ostypeid,omitempty"`
	Password        string `json:"password,omitempty"`
	Passwordenabled bool   `json:"passwordenabled,omitempty"`
	Project         string `json:"project,omitempty"`
	Projectid       string `json:"projectid,omitempty"`
	Publicip        string `json:"publicip,omitempty"`
	Publicipid      string `json:"publicipid,omitempty"`
	Rootdeviceid    int64  `json:"rootdeviceid,omitempty"`
	Rootdevicetype  string `json:"rootdevicetype,omitempty"`
	Securitygroup   []struct {
		Account     string `json:"account,omitempty"`
		Description string `json:"description,omitempty"`
		Domain      string `json:"domain,omitempty"`
		Domainid    string `json:"domainid,omitempty"`
		Egressrule  []struct {
			Account           string `json:"account,omitempty"`
			Cidr              string `json:"cidr,omitempty"`
			Endport           int    `json:"endport,omitempty"`
			Icmpcode          int    `json:"icmpcode,omitempty"`
			Icmptype          int    `json:"icmptype,omitempty"`
			Protocol          string `json:"protocol,omitempty"`
			Ruleid            string `json:"ruleid,omitempty"`
			Securitygroupname string `json:"securitygroupname,omitempty"`
			Startport         int    `json:"startport,omitempty"`
			Tags              []struct {
				Account      string `json:"account,omitempty"`
				Customer     string `json:"customer,omitempty"`
				Domain       string `json:"domain,omitempty"`
				Domainid     string `json:"domainid,omitempty"`
				Key          string `json:"key,omitempty"`
				Project      string `json:"project,omitempty"`
				Projectid    string `json:"projectid,omitempty"`
				Resourceid   string `json:"resourceid,omitempty"`
				Resourcetype string `json:"resourcetype,omitempty"`
				Value        string `json:"value,omitempty"`
			} `json:"tags,omitempty"`
		} `json:"egressrule,omitempty"`
		Id          string `json:"id,omitempty"`
		Ingressrule []struct {
			Account           string `json:"account,omitempty"`
			Cidr              string `json:"cidr,omitempty"`
			Endport           int    `json:"endport,omitempty"`
			Icmpcode          int    `json:"icmpcode,omitempty"`
			Icmptype          int    `json:"icmptype,omitempty"`
			Protocol          string `json:"protocol,omitempty"`
			Ruleid            string `json:"ruleid,omitempty"`
			Securitygroupname string `json:"securitygroupname,omitempty"`
			Startport         int    `json:"startport,omitempty"`
			Tags              []struct {
				Account      string `json:"account,omitempty"`
				Customer     string `json:"customer,omitempty"`
				Domain       string `json:"domain,omitempty"`
				Domainid     string `json:"domainid,omitempty"`
				Key          string `json:"key,omitempty"`
				Project      string `json:"project,omitempty"`
				Projectid    string `json:"projectid,omitempty"`
				Resourceid   string `json:"resourceid,omitempty"`
				Resourcetype string `json:"resourcetype,omitempty"`
				Value        string `json:"value,omitempty"`
			} `json:"tags,omitempty"`
		} `json:"ingressrule,omitempty"`
		Name      string `json:"name,omitempty"`
		Project   string `json:"project,omitempty"`
		Projectid string `json:"projectid,omitempty"`
		Tags      []struct {
			Account      string `json:"account,omitempty"`
			Customer     string `json:"customer,omitempty"`
			Domain       string `json:"domain,omitempty"`
			Domainid     string `json:"domainid,omitempty"`
			Key          string `json:"key,omitempty"`
			Project      string `json:"project,omitempty"`
			Projectid    string `json:"projectid,omitempty"`
			Resourceid   string `json:"resourceid,omitempty"`
			Resourcetype string `json:"resourcetype,omitempty"`
			Value        string `json:"value,omitempty"`
		} `json:"tags,omitempty"`
		Virtualmachinecount int      `json:"virtualmachinecount,omitempty"`
		Virtualmachineids   []string `json:"virtualmachineids,omitempty"`
	} `json:"securitygroup,omitempty"`
	Serviceofferingid   string `json:"serviceofferingid,omitempty"`
	Serviceofferingname string `json:"serviceofferingname,omitempty"`
	Servicestate        string `json:"servicestate,omitempty"`
	State               string `json:"state,omitempty"`
	Tags                []struct {
		Account      string `json:"account,omitempty"`
		Customer     string `json:"customer,omitempty"`
		Domain       string `json:"domain,omitempty"`
		Domainid     string `json:"domainid,omitempty"`
		Key          string `json:"key,omitempty"`
		Project      string `json:"project,omitempty"`
		Projectid    string `json:"projectid,omitempty"`
		Resourceid   string `json:"resourceid,omitempty"`
		Resourcetype string `json:"resourcetype,omitempty"`
		Value        string `json:"value,omitempty"`
	} `json:"tags,omitempty"`
	Templatedisplaytext string `json:"templatedisplaytext,omitempty"`
	Templateid          string `json:"templateid,omitempty"`
	Templatename        string `json:"templatename,omitempty"`
	Userid              string `json:"userid,omitempty"`
	Username            string `json:"username,omitempty"`
	Vgpu                string `json:"vgpu,omitempty"`
	Zoneid              string `json:"zoneid,omitempty"`
	Zonename            string `json:"zonename,omitempty"`
}

type ListAffinityGroupTypesParams struct {
	p map[string]interface{}
}

func (p *ListAffinityGroupTypesParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	return u
}

func (p *ListAffinityGroupTypesParams) SetKeyword(v string) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["keyword"] = v
	return
}

func (p *ListAffinityGroupTypesParams) SetPage(v int) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["page"] = v
	return
}

func (p *ListAffinityGroupTypesParams) SetPagesize(v int) {
	if p.p == nil {
		p.p = make(map[string]interface{})
	}
	p.p["pagesize"] = v
	return
}

// You should always use this function to get a new ListAffinityGroupTypesParams instance,
// as then you are sure you have configured all required params
func (s *AffinityGroupService) NewListAffinityGroupTypesParams() *ListAffinityGroupTypesParams {
	p := &ListAffinityGroupTypesParams{}
	p.p = make(map[string]interface{})
	return p
}

// Lists affinity group types available
func (s *AffinityGroupService) ListAffinityGroupTypes(p *ListAffinityGroupTypesParams) (*ListAffinityGroupTypesResponse, error) {
	resp, err := s.cs.newRequest("listAffinityGroupTypes", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListAffinityGroupTypesResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}
	return &r, nil
}

type ListAffinityGroupTypesResponse struct {
	Count              int                  `json:"count"`
	AffinityGroupTypes []*AffinityGroupType `json:"affinitygrouptype"`
}

type AffinityGroupType struct {
	Type string `json:"type,omitempty"`
}


text:
// *****************************************************************
// Title: Validation.cs
// Author: John Fitzgerald
// Date: 1-29-17
// Description: Validation class determine if user input is valid,
// and if the cards in the Players' hands are valid.
// *****************************************************************
using System;
using System.Linq;

class Validation : PokerGame
{
    public static char[] MenuOptionsStart = { 'r', 'm', 'q' };
    public static char[] MenuOptionsEnd = { 'p', 'q' };

    /// <summary>
    /// validate user input for menus
    /// </summary>
    /// <param name="key"></param>
    /// <param name="menuType"></param>
    /// <returns></returns>
    public static char Validate_Input_Menu(ConsoleKeyInfo key, string menuType)
    {
        char charInput = key.KeyChar;
        char[] menuOptions;

        // determine type of menu options being validated
        if (menuType == "Start")
            menuOptions = MenuOptionsStart;
        else
            menuOptions = MenuOptionsEnd;

        // prompt user for a valid option
        while (!menuOptions.Contains(Char.ToLower(charInput)))
        {
            Console.WriteLine("\n{0} is not valid. Please enter a valid character: ", key.KeyChar);
            charInput = Console.ReadKey().KeyChar;
        }

        if (Char.ToLower(charInput) == 'm')
            IsManual = true;

        return charInput;
    }

    /// <summary>
    /// validate what to do at start of program based on user input
    /// </summary>
    /// <param name="charInput"></param>
    public static void Validate_Input_Decision(char charInput)
    {
        char lowerCharInput = Char.ToLower(charInput);

        // randomly generate cards
        if (lowerCharInput == 'r')
        {
            IsManual = false;
            IsRandom = true;
        }
        // manually enter cards
        else if (lowerCharInput == 'm')
        {
            IsRandom = false;
            IsManual = true;
        }
        // play again
        else if (lowerCharInput == 'p')
            Display.Display_Play_Again();
        // quit program
        else if (lowerCharInput == 'q')
        {
            Display.Display_Quit_Program();
            IsPlay = false;
        }
        // should never reach here (if using input validation)
        else
            Display.Display_Invalid_Character(charInput);
    }

    /// <summary>
    /// validate the cards in Players' hands
    /// </summary>
    /// <param name="hand"></param>
    /// <returns></returns>
    public static bool Validate_Input_Hand(string hand)
    {
        // proper length of input (+1 to account for space between hands)
        int inputLength = NumberOfCardsPerHand * NumberOfPlayers * 2 + 1;
        string[] hands;

        // check size of hand
        if (hand.Length > inputLength || hand.Length < inputLength)
        {
            ErrorHand = "Please input two hands seperated by a space.";
            return false;
        }

        // split cards into two hands
        hands = hand.Split(' ');

        // verify each hand contains valid cards and add them to the player's hand
        for (int i = 0; i < NumberOfPlayers; ++i)
        {
            // find player
            int handNum = i + 1;
            Players.TryGetValue(PlayerName + handNum, out Player player);

            // check contents of hand
            for (int j = 0; j < NumberOfCardsPerHand * 2; ++j)
            {
                Deck.Card checkCard = new Deck.Card(hands[i][j], hands[i][++j]);
                //checkCard.value = hands[i][j];
                //checkCard.suit = hands[i][++j];
                if (!CardDeck.FullDeck.Contains(checkCard))
                {
                    // clear each player's hand (in-case user changes previous players' cards)
                    foreach (var _player in Players)
                        _player.Value.Hand.Clear();

                    ErrorHand = "Invalid characters for card detected: " + checkCard.value + checkCard.suit;
                    return false;
                }

                // add card to player's hand
                player.Hand.Add(checkCard);
            }
        }

        // TODO: check for duplicates

        return true;
    }
}


text:
class Door;

class Entity {
public:
  using SharedEntity = std::shared_ptr<Entity>;
  virtual ~Entity(){}
  virtual mos::Model model() = 0;
  virtual void update(const float dt) = 0;
  std::vector<Door> exits;
  bool intersects(const Entity &entity) const;
  mos::Box box() const;
  friend std::ostream& operator<<(std::ostream& ofs, Entity& e);
protected:
  virtual void print(std::ostream &os) = 0;
  mos::Box box_;
};

#endif // ENTITY_HPP


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AcceptVerbsAttribute_.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}


text:
package org.kuali.rice.kew.xml;

import org.junit.Test;
import org.kuali.rice.kew.test.KEWTestCase;

public class XmlImportTest extends KEWTestCase {

	/*public void testCanParseWhiteSpace() throws Exception {
		//XmlImportTest_white_space_test.xml contains white space that will make things choke if not
		//properly handled
		this.loadXmlFile("XmlImportTest_white_space_test.xml");

	}

	public void testCantParseReturnChar() throws Exception {
		this.loadXmlFile("XmlImportTest_white_space_return_char_test.xml");
	}*/

	@Test public void testRuleTemplate() throws Exception{
		this.loadXmlFile("RuleTemplate_test_white_space.xml");
		this.loadXmlFile("RuleTemplate_test_newline.xml");
	}

	@Test public void testDocumentType() throws Exception{
		this.loadXmlFile("DocumentType_white_space_test.xml");
		this.loadXmlFile("DocumentType_newline_test.xml");
	}

	@Test public void testRule() throws Exception{
		this.loadXmlFile("Rule_white_space_test.xml");
		this.loadXmlFile("Rule_newline_test.xml");

	}

}


text:
import styled, { css } from "styled-components";
import PropTypes from "prop-types";
import { margin } from "styled-system";
import baseTheme from "../../style/themes/base";
import { PROGRESS_TRACKER_SIZES } from "./progress-tracker.config";

const StyledProgressTracker = styled.div`
  ${margin}
  text-align: center;
  white-space: nowrap;

  ${({ isVertical, length }) => css`
    ${!isVertical &&
    `
      width: ${length};
    `}
    ${isVertical &&
    `
      height: ${length};
      display: flex;
    `}
  `}
`;

const StyledProgressBar = styled.span`
  ${({ direction, isVertical, size }) => css`
    display: flex;
    position: relative;
    background-color: var(--colorsSemanticNeutral200);

    ${!isVertical &&
    css`
      overflow-x: hidden;
      height: ${getHeight(size)};
      width: 100%;
    `}
    ${isVertical &&
    css`
      overflow-y: hidden;
      width: ${getHeight(size)};
      height: 100%;

      ${direction === "up" &&
      `
        align-items: flex-end;
      `}
    `}
  `}
`;

const StyledValue = styled.span`
  color: var(--colorsUtilityYin090);
  ${({ isMaxValue }) => css`
    ${isMaxValue && `color: var(--colorsUtilityYin055);`}
    ${!isMaxValue && `font-weight: bold;`}
  `}
`;

const StyledValuesLabel = styled.span`
  text-align: start;
  display: flex;
  justify-content: space-between;
  ${({ isVertical, position }) => css`
    ${isVertical &&
    css`
      flex-direction: column;

      ${position !== "left" &&
      css`
        padding-left: 4px;
      `}

      ${position === "left" &&
      css`
        padding-right: 4px;

        ${StyledValue} {
          text-align: right;
        }
      `}
    `}

    ${!isVertical &&
    css`
      ${position !== "bottom" &&
      css`
        padding-bottom: 4px;
      `}

      ${position === "bottom" &&
      css`
        padding-top: 4px;
      `}
    `}
  `}
`;

const InnerBar = styled.span`
  ${({ isVertical, progress, size, length }) => css`
    position: absolute;
    left: 0;
    background-color: ${getInnerBarColour(progress)};

    ${!isVertical &&
    css`
      width: calc(${length} * ${progress / 100});
      min-width: 2px;
      height: ${getHeight(size)};
    `}
    ${isVertical &&
    css`
      height: calc(${length} * ${progress / 100});
      min-height: 2px;
      width: ${getHeight(size)};
    `}
  `}
`;

function getHeight(size) {
  switch (size) {
    case "small":
      return "var(--sizing050)";
    case "large":
      return "var(--sizing200)";
    default:
      return "var(--sizing100)";
  }
}

function getInnerBarColour(progress) {
  if (progress >= 100) return "var(--colorsSemanticPositive500)";
  return "var(--colorsSemanticNeutral500)";
}

StyledProgressTracker.defaultProps = {
  theme: baseTheme,
};

StyledProgressBar.defaultProps = {
  size: "medium",
};

InnerBar.defaultProps = {
  progress: 0,
  size: "medium",
};

InnerBar.propTypes = {
  size: PropTypes.oneOf(PROGRESS_TRACKER_SIZES),
  progress: PropTypes.number,
  isVertical: PropTypes.bool,
};

StyledProgressTracker.propTypes = {
  theme: PropTypes.object,
  isVertical: PropTypes.bool,
};

StyledValuesLabel.propTypes = {
  isVertical: PropTypes.bool,
  position: PropTypes.oneOf(["top", "bottom", "left", "right"]),
};

StyledValue.propTypes = {
  isMaxValue: PropTypes.bool,
};

StyledProgressBar.propTypes = {
  direction: PropTypes.oneOf(["up", "down"]),
  isVertical: PropTypes.bool,
  size: PropTypes.oneOf(PROGRESS_TRACKER_SIZES),
};

export {
  StyledProgressBar,
  InnerBar,
  StyledProgressTracker,
  StyledValuesLabel,
  StyledValue,
};


text:
/*
 * This Jquery/Javascript file takes care of the sending and receiving of any
 * data relating to the Labour Cost Management function within the application.
 */

$(function() {

    function toTitleCase(str)
    {
        // Many thanks to Greg Dean http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
        return str.replace(/\w\S*/g, function(txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    }

    function checkPercentages(fieldName) {
        if ($('' + fieldName).val() === "") {
            $('' + fieldName).val('0.00');
            return errors = true;
        } else if ($('' + fieldName).val() !== "") {
            var value = $('' + fieldName).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^\d*(\.\d{1})?\d{0,1}$/;
            if (!intRegex.test(value)) {
                $('' + fieldName).after('
&nbspPlease enter numeric digits only
');
                return errors = true;
            } else {
                return errors = false;
            }
        }
    }

    function checkIntegers(fieldName) {
        if ($('' + fieldName).val() === "") {
            $('' + fieldName).val('0');
            return errors = true;
        } else if ($('' + fieldName).val() !== "") {
            var value = $('' + fieldName).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^\s*-?[0-9]{1,10}\s*$/;
            if (!intRegex.test(value)) {
                $('' + fieldName).after('
&nbspPlease enter integers only
');
                return errors = true;
            } else {
                return errors = false;
            }
        }
    }

    function checkNumerics(fieldName) {
        if ($('' + fieldName).val() === "") {
            $('' + fieldName).val('0.00');
            return errors = true;
        } else if ($('' + fieldName).val() !== "") {
            var value = $('' + fieldName).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^\d*(\.\d{1})?\d{0,1}$/;
            if (!intRegex.test(value)) {
                $('' + fieldName).after('
&nbspPlease enter numeric digits only
');
                return errors = true;
            } else {
                return errors = false;
            }
        }
    }

    function checkFields(fieldName) {
        if ($('' + fieldName).val() === "") {
            $('' + fieldName).after('
&nbspThis field cannot be empty
');
            return errors = true;
        } else if ($('' + fieldName).val() !== "") {
            var value = $('' + fieldName).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^[A-Za-z0-9.;,:"'_\-\s]+$/;
            if (!intRegex.test(value)) {
                $('' + fieldName).after('
&nbspPlease enter alphanumeric characters only
');
                return errors = true;
            } else {
                return errors = false;
            }
        }
    }

    function checkNumbers(fieldName) {
        if ($('' + fieldName).val() !== "") {
            var value = $('' + fieldName).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^\d*(\.\d{1})?\d{0,1}$/;
            if (!intRegex.test(value)) {
                $('' + fieldName).after('
&nbspPlease enter numeric digits only
');
                return errors = true;
            } else {
                return errors = false;
            }
        }
    }

    $('#labourFormShow').click(function() {
        $("#showLabourCostsFormContainer").remove();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var insertString = "

Current Labour Costs

";
        var field = "";
        var thisCurrency = [];

        $.post(url, data, function(response) {
            for (var i = 0; i < response.length; i += 2) {

                insertString += "
";
                if (response[i] === "id") {
                    insertString += "	";
                } else {
                    var tableEntry = response[i];
                    tableEntry = tableEntry.replace(/_/g, " ");
                    tableEntry = toTitleCase(tableEntry);
                    insertString += "" + tableEntry + "	";
                }

                field = response[i];

                for (var j = 0; j < response[i + 1].length; j++) {
                    if (response[i] === "id") {
                        insertString += "	";
                    } else if (response[i] === "employee_category") {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/currency/g)) {
                        thisCurrency[j] = response[i + 1][j][field];
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/update/g)) {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/numbers_of_this/g)) {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/employee_type/g)) {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/_allocation/g)) {
                        insertString += "" + response[i + 1][j][field] + " %	";
                    } else {
                        insertString += " " + response[i + 1][j][field] + "	";
                    }

                }

                insertString += "
";

            }
            insertString += "

";
            $("#labourMainMIDMainSectionRHS").append(insertString);
            for (var i = 0; i <= thisCurrency.length; i++) {
                $('.currency' + i).text('' + thisCurrency[i]);
            }
            return false;
        }, 'json');

        return false;

    });

    $('#labourFormAdd').click(function() {
        $("#showLabourCostsFormContainer").remove();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var lastupdatedby = $('#lastupdatedby').val();
        var percentArray = [];
        var numericArray = [];
        var fieldArray = [];
        var integerArray = [];
        var insertString = "

Add Labour Costs
<form name='labourAddLabour' id='labourFormAddSubmit' action='ajax_LabourAdd'>
";
        insertString += "<input type='hidden' name='tableName' value='labour'><input type='hidden' name='lastupdatedby' value='" + lastupdatedby + "'>";
        $.post(url, data, function(response) {
            for (var i = 0; i < response.length; i += 2) {

                insertString += "
";
                if (response[i] === "id" || response[i] === "lastupdatedby" || response[i] === "lastupdated") {
                    insertString += "	";
                } else {
                    var tableEntry = response[i];
                    tableEntry = tableEntry.replace(/_/g, " ");
                    tableEntry = toTitleCase(tableEntry);
                    insertString += "" + tableEntry + "	";
                }

                switch (response[i]) {
                    case "id":
                        insertString += "	";
                        break;
                    case "lastupdatedby":
                        insertString += "	";
                        break;
                    case "lastupdated":
                        insertString += "	";
                        break;
                    case "employee_category":
                        insertString += "<input id='" + response[i] + "' class='alphanumeric' name='" + response[i] + "' maxlength='30'>	";
                        var duplicateCheck = response[i];
                        fieldArray.push(response[i]);
                        break;
                    case ("numbers_of_this_employee"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'>	";
                        integerArray.push(response[i]);
                        break;
                    case ("award_bonus_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("pension_contribution"):
                        insertString += "<input id='" + response[i] + "' class='monetary' name='" + response[i] + "' maxlength='8'>	";
                        percentArray.push(response[i]);
                        break;
                    case ("expenses_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("maternity_paternity_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("sickness_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("legal_challenges_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("redundancy_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("jury_civil_duties_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("employer_social_security_allocation"):
                        insertString += "<input id='" + response[i] + "' class='percentage' name='" + response[i] + "' maxlength='4'> %	";
                        percentArray.push(response[i]);
                        break;
                    case ("employee_type"):
                        insertString += "<select class='selectCurrency' id='" + response[i] + "' name='" + response[i] + "'><option value='Central Performer'>Central Performer</option><option value='On-site Performer'>On-Site Performer</option><option value='Non-Performer'>Non-Performer</option></select>	";
                        break;
                    case ("currency"):

                        insertString += "<select class='selectCurrency' id='" + response[i] + "' name='" + response[i] + "'>";

                        $.ajax({
                            type: 'GET',
                            url: 'ajax_getCurrency',
                            async: false,
                            dataType: 'json',
                            success: function(response) {

                                for (var i = 0; i < response.length; i += 1) {
                                    insertString += "<option value='" + response[i] + "'>" + response[i] + "</option>";
                                }

                            }, error: function(jqXHR, textStatus, errorThrown) {
                                window.location.assign('error/index');
                            }
                        });
                        insertString += "</select>	";
                        break;
                    default:
                        insertString += "<input id='" + response[i] + "' class='monetary' name='" + response[i] + "' maxlength='14'>	";
                        numericArray.push(response[i]);
                        break;
                }

                insertString += "
";

            }
            insertString += "
";
            insertString += "
<input class='labourAddInputSubmit' id='labourFormAddButton' type='submit' value='Add Labour Costs'/>
";
            insertString += "</form>
";
            $("#labourMainMIDMainSectionRHS").append(insertString);

            $('#labourFormAddSubmit').submit(function(e) {
                e.preventDefault();

                var errors = false;
                var error_count = 0;
                $('.addlabourAddFormErrors').remove();

                $.each(percentArray, function(ky, val) {
                    errors = checkPercentages("#" + val);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                $.each(fieldArray, function(ky, val) {
                    errors = checkFields("#" + val);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                $.each(integerArray, function(key, value) {
                    errors = checkIntegers("#" + value);
                    if (errors === true) {
                       error_count+=1;

                    }
                });

                $.each(numericArray, function(key, value) {
                    errors = checkNumerics("#" + value);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                var duplicateValue = $('#' + duplicateCheck).val();
                var url1 = 'ajax_checkForDuplicate';
                var data1 = {};

                data1['value'] = duplicateValue;
                data1['tableName'] = "labour";

                $.ajax({
                    type: 'GET',
                    url: url1,
                    data: data1,
                    async: false,
                    success: function(response) {
                        if (response === "true") {
                            console.log("in here so true");
                            error_count += 1;
                            $('#' + duplicateCheck).after('
&nbspThis Category is already registered.
');
                        }
                    }, error: function(jqXHR, textStatus, errorThrown) {
                        window.location.assign('error/index');
                    }
                });

                if (errors === false && error_count === 0) {
                    var data = $(this).serializeArray();
                    var url = $(this).attr('action');

                    $.post(url, data, function(response) {
                        window.location.assign('../labour/index');
                        return false;
                    });

                }

                return false;
            });
            return false;
        }, 'json');
        return false;
    });

    $('#labourFormDelete').click(function(e) {
        e.preventDefault();
        $("#showLabourCostsFormContainer").remove();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var insertString = "

Delete Labour Costs

";
        var field = "";
        var thisCurrency = [];

        $.post(url, data, function(response) {
            for (var i = 0; i < response.length; i += 2) {

                insertString += "
";
                if (response[i] === "id") {
                    insertString += "	";
                } else {
                    var tableEntry = response[i];
                    tableEntry = tableEntry.replace(/_/g, " ");
                    tableEntry = toTitleCase(tableEntry);
                    insertString += "" + tableEntry + "	";
                }

                field = response[i];
                for (var j = 0; j < response[i + 1].length; j++) {
                    if (response[i] === "id") {
                        insertString += "<button id='deleteThisColumn' class='deleteButton'>Delete Entry</button>	";
                    } else if (response[i] === "employee_category") {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/currency/g)) {
                        thisCurrency[j] = response[i + 1][j][field];
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else if (response[i].match(/_allocation/g)) {
                        insertString += "" + response[i + 1][j][field] + " %	";
                    } else if (response[i].match(/update/g)) {
                        insertString += "" + response[i + 1][j][field] + "	";
                    } else {
                        insertString += " " + response[i + 1][j][field] + "	";
                    }
                }
                insertString += "
";
            }
            insertString += "

";
            $("#labourMainMIDMainSectionRHS").append(insertString);
            for (var i = 0; i <= thisCurrency.length; i++) {
                $('.currency' + i).text('' + thisCurrency[i]);
            }

            $(".labourDelete").click(function(e) {
                e.preventDefault();
                var uid = $(this).attr('rel');
                var colnum = $(this).attr('id');

                $.post('ajax_LabourDelete', {'id': uid}, function(o) {

                }, 'json');
                $("." + colnum).hide();
                return false;
            });
            return false;
        }, 'json');

        return false;
    });

    $('#labourFormModify').click(function(e) {
        e.preventDefault();
        $("#showLabourCostsFormContainer").remove();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var currentupdater = $('#currentupdater').val();
        var insertString = "

Modify Labour Costs
<form name='modifyLabour'>
";
        var field = "";
        var numberArray = [];
        var integerArray = [];
        var fieldArray = [];
        var colNames = [];
        var originalField = [];
        $.post(url, data, function(response) {
            for (var i = 0; i < response.length; i += 2) {
                colNames.push(response[i]);
                insertString += "
";
                if (response[i] === "id" || response[i] === "lastupdated" || response[i] === "lastupdatedby") {
                    insertString += "	";
                } else {
                    var tableEntry = response[i];
                    tableEntry = tableEntry.replace(/_/g, " ");
                    tableEntry = toTitleCase(tableEntry);
                    insertString += "" + tableEntry + "	";
                }

                field = response[i];

                for (var j = 0; j < response[i + 1].length; j++) {

                    if (response[i] === "id") {
                        insertString += "<button id='updateThisColumn' class='updateButton'>Update Entry</button>	";
                    } else if (response[i] === "employee_category") {
                        insertString += "<input class='inputModify' id='" + response[i] + j + "' value='" + response[i + 1][j][field] + "'/>	";
                        fieldArray.push(response[i] + j);
                        var duplicateCheck = response[i];
                        originalField.push(response[i + 1][j][field]);
                    } else if (response[i] === "lastupdated" || response[i] === "lastupdatedby") {
                        insertString += "	";
                    } else if (response[i].match(/_allocation/g)) {
                        insertString += "<input class='percentage' id='" + response[i] + j + "' value='" + response[i + 1][j][field] + "' maxlength='4' /> %	";
                        numberArray.push(response[i] + j);
                    } else if (response[i].match(/this_employee/g)) {
                        insertString += "<input class='percentage' id='" + response[i] + j + "' value='" + response[i + 1][j][field] + "' maxlength='8' />	";
                        integerArray.push(response[i] + j);
                    } else if (response[i].match(/currency/g)) {
                        insertString += "<select class='selectCurrency' id='" + response[i] + j + "' name='" + response[i] + "'>";
                        var currentCurrency = response[i + 1][j][field];
                        $.ajax({
                            type: 'GET',
                            url: 'ajax_getCurrency',
                            async: false,
                            dataType: 'json',
                            success: function(response) {

                                for (var i = 0; i < response.length; i += 1) {
                                    if (response[i] === currentCurrency) {
                                        insertString += "<option selected value='" + response[i] + "'>" + response[i] + "</option>";
                                    } else {
                                        insertString += "<option value='" + response[i] + "'>" + response[i] + "</option>";
                                    }
                                }

                            }, error: function(jqXHR, textStatus, errorThrown) {
                                window.location.assign('error/index');
                            }
                        });
                        insertString += "</select>	";
                    } else if (response[i].match(/employee_type/g)) {
                        var currentEmployeeType = response[i + 1][j][field];
                        var types = ["Non-Performer", "Central Performer","On-Site Performer"];
                        insertString += "<select class='selectCurrency' id='" + response[i] + j + "' name='" + response[i] + "'>";
                        insertString += "<option selected value='" + currentEmployeeType +"'>" + currentEmployeeType +"</option>";
                        if (currentEmployeeType === "Central Performer") {
                            insertString += "<option value='On-site Performer'>On-site Performer</option><option value='Non-Performer'>Non-Performer</option>";
                        } else if (currentEmployeeType === "On-site Performer"){
                            insertString += "<option value='Central Performer'>Central Performer</option><option value='Non-Performer'>Non-Performer</option>";
                        } else {
                            insertString += "<option value='On-site Performer'>On-site Performer</option><option value='Central Performer'>Central Performer</option>";
                        }
                        insertString += "</select>	";
                    } else {
                        insertString += "<input class='inputModify' id='" + response[i] + j + "' value='" + response[i + 1][j][field] + "' maxlength='10'/>	";
                        numberArray.push(response[i] + j);
                    }
                }
                insertString += "
";
            }
            insertString += "
</form>
";
            $("#labourMainMIDMainSectionRHS").append(insertString);

            $(".labourModify").click(function(e) {
                e.preventDefault();
                var uid = $(this).attr('rel');
                var colnum = $(this).attr('id');
                var errors = false;
                var error_count = 0;

                $.each(numberArray, function(key, value) {
                    errors = checkNumbers("#" + value);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                $.each(integerArray, function(key, value) {
                    errors = checkIntegers("#" + value);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                $.each(fieldArray, function(key, value) {
                    errors = checkFields("#" + value);
                    if (errors === true) {
                        error_count += 1;
                    }
                });

                var duplicateValue = $('#' + duplicateCheck + colnum).val();

                if (originalField[colnum] !== duplicateValue) {
                    var url1 = 'ajax_checkForDuplicate';
                    var data1 = {};

                    data1['value'] = duplicateValue;
                    data1['tableName'] = "labour";

                    $.ajax({
                        type: 'GET',
                        url: url1,
                        data: data1,
                        async: false,
                        success: function(response) {
                            if (response === "true") {
                                error_count += 1;
                                $('#' + duplicateCheck + colnum).after('
&nbspThis Data Center is already registered.
');
                            }
                        }, error: function(jqXHR, textStatus, errorThrown) {
                            window.location.assign('error/index');
                        }
                    });

                }

                if (errors === false && error_count === 0) {
                    var myjsonforPosting = {};
                    myjsonforPosting["currentupdater"] = currentupdater;
                    $.each(colNames, function(key, value) {
                        if (value !== "id" && value !== "lastupdatedby") {
                            myjsonforPosting['' + value] = $("#" + value + colnum).val();
                        }
                    });
                    myjsonforPosting["id"] = uid;
                    $.post('ajax_LabourModify', myjsonforPosting, function(o) {

                    }, 'json');
                    $("." + colnum).hide();
                }
                return false;
            });
            return false;
        }, 'json');

        return false;
    });

    return false;
});


text:
/* eslint-env jest */

jest.mock('../style.less', () => jest.fn())
jest.mock('bootstrap/scss/bootstrap.scss', () => jest.fn())

window.URL = {
  createObjectURL: () => {}
}


text:
import * as React from 'react'
import * as Styles from '../../../../../../styles'
import * as Kb from '../../../../../../common-adapters'
import {formatTimeForChat} from '../../../../../../util/timestamp'

type Props = {
  endTime?: number
}

const UnfurlSharingEnded = (props: Props) => (
  <Kb.Box2 direction="vertical" style={styles.container}>
    <Kb.Text type="BodySemibold">Location sharing ended</Kb.Text>
    {props.endTime && <Kb.Text type="BodyTiny">Last updated {formatTimeForChat(props.endTime)}</Kb.Text>}
  </Kb.Box2>
)

const styles = Styles.styleSheetCreate(() => ({
  container: {
    ...Styles.padding(Styles.globalMargins.xtiny, Styles.globalMargins.tiny),
    backgroundColor: Styles.globalColors.white,
    borderColor: Styles.globalColors.grey,
    borderRadius: Styles.borderRadius,
    borderStyle: 'solid',
    borderWidth: 1,
    marginTop: Styles.globalMargins.xtiny,
  },
}))

export default UnfurlSharingEnded


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Test.Perf;

namespace Azure.Storage.Files.Shares.Perf.Scenarios
{
    /// <summary>
    /// This tests various client ctors and hierarchy traversal.
    /// </summary>
    public class CreateClients : PerfTest<PerfOptions>
    {
        private static readonly string s_connectionString = $"DefaultEndpointsProtocol=https;AccountName=foo;AccountKey={Convert.ToBase64String(Guid.NewGuid().ToByteArray())};EndpointSuffix=core.windows.net";
        private static readonly Uri s_serviceUri = new Uri("https://foo.files.core.windows.net");
        private static readonly Uri s_shareUri = new Uri("https://foo.files.core.windows.net/foo");
        private static readonly Uri s_directoryUri = new Uri("https://foo.files.core.windows.net/foo/bar");
        private static readonly Uri s_fileUri = new Uri("https://foo.files.core.windows.net/foo/bar/baz");
        private static readonly AzureSasCredential s_azureSasCredential = new AzureSasCredential("foo");
        private static readonly StorageSharedKeyCredential s_storageSharedKey = new StorageSharedKeyCredential("foo", Convert.ToBase64String(Guid.NewGuid().ToByteArray()));

        public CreateClients(PerfOptions options) : base(options)
        {
        }

#pragma warning disable CA1806 // Do not ignore method results
        public override void Run(CancellationToken cancellationToken)
        {
            var serviceClient = new ShareServiceClient(s_connectionString);
            new ShareServiceClient(s_serviceUri);
            new ShareServiceClient(s_serviceUri, s_azureSasCredential);
            new ShareServiceClient(s_serviceUri, s_storageSharedKey);

            var shareClient = new ShareClient(s_connectionString, "foo");
            new ShareClient(s_shareUri);
            new ShareClient(s_shareUri, s_azureSasCredential);
            new ShareClient(s_shareUri, s_storageSharedKey);

            var directoryClient = new ShareDirectoryClient(s_connectionString, "foo", "bar");
            new ShareDirectoryClient(s_directoryUri);
            new ShareDirectoryClient(s_directoryUri, s_azureSasCredential);
            new ShareDirectoryClient(s_directoryUri, s_storageSharedKey);

            new ShareFileClient(s_connectionString, "foo", "bar/baz");
            new ShareFileClient(s_fileUri);
            new ShareFileClient(s_fileUri, s_azureSasCredential);
            new ShareFileClient(s_fileUri, s_storageSharedKey);

            serviceClient.GetShareClient("foo");
            shareClient.GetDirectoryClient("bar");
            directoryClient.GetFileClient("baz");
        }
#pragma warning restore CA1806 // Do not ignore method results

        public override Task RunAsync(CancellationToken cancellationToken)
        {
            Run(cancellationToken);
            return Task.CompletedTask;
        }
    }
}


text:
package org.projectfloodlight.openflow.types;

import org.jboss.netty.buffer.ChannelBuffer;

import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.Shorts;

/**
 * ODU-SIGTYPE field representation
 */
public class OduSigtype implements OFValueType<OduSigtype> {

    static final short MAX_SIGTYPE = 0xFF;
    static final int LENGTH = 1;

    private final short sigtype;

    static final short NUM_OFPODUT_ODU0        = 0x0a;
    static final short NUM_OFPODUT_ODU1        = 0x01;
    static final short NUM_OFPODUT_ODU2        = 0x02;
    static final short NUM_OFPODUT_ODU3        = 0x03;
    static final short NUM_OFPODUT_ODU4        = 0x04;
    static final short NUM_OFPODUT_ODU2E       = 0x0b;
    static final short NUM_OFPODUT_ODUfCBR     = 0x14;
    static final short NUM_OFPODUT_ODUfGFPfHAO = 0x15;
    static final short NUM_OFPODUT_ODUfGFPf    = 0x16;

    public static final OduSigtype OFPODUT_ODU0        = new OduSigtype(NUM_OFPODUT_ODU0);
    public static final OduSigtype OFPODUT_ODU1        = new OduSigtype(NUM_OFPODUT_ODU1);
    public static final OduSigtype OFPODUT_ODU2        = new OduSigtype(NUM_OFPODUT_ODU2);
    public static final OduSigtype OFPODUT_ODU3        = new OduSigtype(NUM_OFPODUT_ODU3);
    public static final OduSigtype OFPODUT_ODU4        = new OduSigtype(NUM_OFPODUT_ODU4);
    public static final OduSigtype OFPODUT_ODU2E       = new OduSigtype(NUM_OFPODUT_ODU2E);
    public static final OduSigtype OFPODUT_ODUfCBR     = new OduSigtype(NUM_OFPODUT_ODUfCBR);
    public static final OduSigtype OFPODUT_ODUfGFPfHAO = new OduSigtype(NUM_OFPODUT_ODUfGFPfHAO);
    public static final OduSigtype OFPODUT_ODUfGFPf    = new OduSigtype(NUM_OFPODUT_ODUfGFPf);

    public static final OduSigtype NONE = OFPODUT_ODU1;

    public static final OduSigtype NO_MASK = OFPODUT_ODU1;
    public static final OduSigtype FULL_MASK = new OduSigtype((short)0x0000);

    private OduSigtype(short sigtype) {
        this.sigtype = sigtype;
    }

    @Override
    public int getLength() {
        return LENGTH;
    }

    public static OduSigtype of(short sigtype) {
        switch (sigtype) {
            case NUM_OFPODUT_ODU0:
                return OFPODUT_ODU0;
            case NUM_OFPODUT_ODU1:
                return OFPODUT_ODU1;
            case NUM_OFPODUT_ODU2:
                return OFPODUT_ODU2;
            case NUM_OFPODUT_ODU3:
                return OFPODUT_ODU3;
            case NUM_OFPODUT_ODU4:
                return OFPODUT_ODU4;
            case NUM_OFPODUT_ODU2E:
                return OFPODUT_ODU2E;
            case NUM_OFPODUT_ODUfCBR:
                return OFPODUT_ODUfCBR;
            case NUM_OFPODUT_ODUfGFPfHAO:
                return OFPODUT_ODUfGFPfHAO;
            case NUM_OFPODUT_ODUfGFPf:
                return OFPODUT_ODUfGFPf;
            default:
                if (sigtype >= MAX_SIGTYPE) {
                    throw new IllegalArgumentException("Illegal ODU-signal-type number: "
                            + sigtype);
                } else {
                    return new OduSigtype(sigtype);
                }
        }
    }

    @Override
    public String toString() {
        return Integer.toHexString(sigtype);
    }

    public void writeByte(ChannelBuffer c) {
        c.writeByte(this.sigtype);
    }

    public static OduSigtype readByte(ChannelBuffer c) {
        return OduSigtype.of(c.readUnsignedByte());
    }

    @Override
    public OduSigtype applyMask(OduSigtype mask) {
        return OduSigtype.of((short)(this.sigtype & mask.sigtype));
    }

    public short getOduSigtypeNumber() {
        return sigtype;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof OduSigtype))
            return false;
        OduSigtype o = (OduSigtype)obj;
        if (o.sigtype != this.sigtype)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 37;
        int result = 1;
        result = prime * result + sigtype;
        return result;
    }

    @Override
    public int compareTo(OduSigtype o) {
        return Shorts.compare(sigtype, o.sigtype);
    }

    @Override
    public void putTo(PrimitiveSink sink) {
        sink.putShort(sigtype);
    }

}


text:
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { dbSeason } from '/db/dbSeason';
import { limitSubscription } from '/server/imports/utils/rateLimit';
import { debug } from '/server/imports/utils/debug';

Meteor.publish('adjacentSeason', function(seasonId) {
  debug.log('publish adjacentSeason', seasonId);
  check(seasonId, String);

  const specificSeasonData = dbSeason.findOne(seasonId);
  if (specificSeasonData) {
    this.added('season', specificSeasonData._id, specificSeasonData);
    const specificSeasonDataBeginDate = specificSeasonData.beginDate;
    const observer1 = dbSeason
      .find({ beginDate: { $gt: specificSeasonDataBeginDate } }, {
        sort: { beginDate: 1 },
        limit: 1,
        disableOplog: true
      })
      .observeChanges({
        added: (id, fields) => {
          this.added('season', id, fields);
        },
        removed: (id) => {
          this.removed('season', id);
        }
      });
    const observer2 = dbSeason
      .find({ beginDate: { $lt: specificSeasonDataBeginDate } }, {
        sort: { beginDate: -1 },
        limit: 1,
        disableOplog: true
      })
      .observeChanges({
        added: (id, fields) => {
          this.added('season', id, fields);
        },
        removed: (id) => {
          this.removed('season', id);
        }
      });
    this.onStop(() => {
      observer1.stop();
      observer2.stop();
    });
  }
  this.ready();
});
// 一分鐘最多重複訂閱20次
limitSubscription('adjacentSeason');


text:
import { Response } from '../../response'
import bytes from 'bytes'

// TODO encoding

export default function (options = {}) {
  options = Object.assign({
    length: null,
    limit: '1mb',
    encoding: 'utf8' // TODO
  }, options)
  const length = bytes.parse(options.length)
  const limit = bytes.parse(options.limit)
  return (context) => {
    const request = context.request
    return new Promise((resolve, reject) => {
      let done = false
      let size = 0
      const raw = []
      function onError (err) {
        reject(err)
      }
      function onAborted () {
        if (done) return
        resolve(Response.status(400).build())
      }
      function onData (chunk) {
        if (done) return
        size += chunk.length
        if (limit !== null && size > limit) {
          resolve(Response.status(413).build())
        } else if (length !== null && size > length) {
          resolve(Response.status(413).build())
        } else {
          raw.push(chunk)
        }
      }
      function onEnd () {
        if (done) return
        done = true
        onClose()
        if (length !== null && length !== size) {
          resolve(Response.status(400).build())
        } else {
          context.rawBody = Buffer.concat(raw).toString()
        }
      }
      function onClose () {
        request.removeListener('error', onError)
        request.removeListener('aborted', onAborted)
        request.removeListener('data', onData)
        request.removeListener('end', onEnd)
        request.removeListener('close', onClose)
      }
      request.on('error', onError).on('aborted', onAborted).on('close', onClose).on('data', onData).on('end', onEnd)
    })
  }
}


text:
#import "CMPedometerData+ORKJSONDictionary.h"

#import "ORKHelpers_Internal.h"

@import CoreMotion;

@implementation CMPedometerData (ORKJSONDictionary)

- (NSDictionary *)ork_JSONDictionary {
    NSMutableDictionary *dictionary = [@{@"startDate": ORKStringFromDateISO8601(self.startDate),
                                         @"endDate": ORKStringFromDateISO8601(self.endDate)
                                         } mutableCopy];
    for (NSString *key in @[@"numberOfSteps", @"distance", @"floorsAscended", @"floorsDescended"]) {
        [dictionary setValue:[self valueForKey:key] forKey:key];
    }
    return dictionary;
}

@end