text:
package gosnmp

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/des"
	"encoding/asn1"
	"encoding/binary"
	"fmt"
	"net"
	"sync/atomic"
	"syscall"
	"time"
)

//
// Remaining globals and definitions located here.
// See http://www.rane.com/note161.html for a succint description of the SNMP
// protocol.
//

// SnmpVersion 1, 2c and 3 implemented
type SnmpVersion uint8

// SnmpVersion 1, 2c and 3 implemented
const (
	Version1  SnmpVersion = 0x0
	Version2c SnmpVersion = 0x1
	Version3  SnmpVersion = 0x3
)

// SnmpV3MsgFlags contains various message flags to describe Authentication, Privacy, and whether a report PDU must be sent.
type SnmpV3MsgFlags uint8

// Possible values of SnmpV3MsgFlags
const (
	NoAuthNoPriv SnmpV3MsgFlags = 0x0 // No authentication, and no privacy
	AuthNoPriv   SnmpV3MsgFlags = 0x1 // Authentication and no privacy
	AuthPriv     SnmpV3MsgFlags = 0x3 // Authentication and privacy
	Reportable   SnmpV3MsgFlags = 0x4 // Report PDU must be sent.
)

// SnmpV3SecurityModel describes the security model used by a SnmpV3 connection
type SnmpV3SecurityModel uint8

// UserSecurityModel is the only SnmpV3SecurityModel currently implemented.
const (
	UserSecurityModel SnmpV3SecurityModel = 3
)

// SnmpV3AuthProtocol describes the authentication protocol in use by an authenticated SnmpV3 connection.
type SnmpV3AuthProtocol uint8

// NoAuth, MD5, and SHA are implemented
const (
	NoAuth SnmpV3AuthProtocol = 1
	MD5    SnmpV3AuthProtocol = 2
	SHA    SnmpV3AuthProtocol = 3
)

// SnmpV3PrivProtocol is the privacy protocol in use by an private SnmpV3 connection.
type SnmpV3PrivProtocol uint8

// NoPriv, DES implemented, AES planned
const (
	NoPriv SnmpV3PrivProtocol = 1
	DES    SnmpV3PrivProtocol = 2
	AES    SnmpV3PrivProtocol = 3
)

// SnmpV3SecurityParameters is a generic interface type to contain various implementations of SnmpV3SecurityParameters
type SnmpV3SecurityParameters interface {
	Copy() SnmpV3SecurityParameters
}

// UsmSecurityParameters is an implementation of SnmpV3SecurityParameters for the UserSecurityModel
type UsmSecurityParameters struct {
	AuthoritativeEngineID    string
	AuthoritativeEngineBoots uint32
	AuthoritativeEngineTime  uint32
	UserName                 string
	AuthenticationParameters string
	PrivacyParameters        []byte

	AuthenticationProtocol SnmpV3AuthProtocol
	PrivacyProtocol        SnmpV3PrivProtocol

	AuthenticationPassphrase string
	PrivacyPassphrase        string

	localDESSalt uint32
	localAESSalt uint64
}

// Copy method for UsmSecurityParameters used to copy a SnmpV3SecurityParameters without knowing it's implementation
func (sp *UsmSecurityParameters) Copy() SnmpV3SecurityParameters {
	return &UsmSecurityParameters{AuthoritativeEngineID: sp.AuthoritativeEngineID,
		AuthoritativeEngineBoots: sp.AuthoritativeEngineBoots,
		AuthoritativeEngineTime:  sp.AuthoritativeEngineTime,
		UserName:                 sp.UserName,
		AuthenticationParameters: sp.AuthenticationParameters,
		PrivacyParameters:        sp.PrivacyParameters,
		AuthenticationProtocol:   sp.AuthenticationProtocol,
		PrivacyProtocol:          sp.PrivacyProtocol,
		AuthenticationPassphrase: sp.AuthenticationPassphrase,
		PrivacyPassphrase:        sp.PrivacyPassphrase,
		localDESSalt:             sp.localDESSalt,
		localAESSalt:             sp.localAESSalt,
	}
}

// SnmpPacket struct represents the entire SNMP Message or Sequence at the
// application layer.
type SnmpPacket struct {
	Version            SnmpVersion
	MsgFlags           SnmpV3MsgFlags
	SecurityModel      SnmpV3SecurityModel
	SecurityParameters SnmpV3SecurityParameters
	ContextEngineID    string
	ContextName        string
	Community          string
	PDUType            PDUType
	MsgID              uint32
	RequestID          uint32
	Error              uint8
	ErrorIndex         uint8
	NonRepeaters       uint8
	MaxRepetitions     uint8
	Variables          []SnmpPDU
}

// VarBind struct represents an SNMP Varbind.
type VarBind struct {
	Name  asn1.ObjectIdentifier
	Value asn1.RawValue
}

// PDUType describes which SNMP Protocol Data Unit is being sent.
type PDUType byte

// The currently supported PDUType's
const (
	Sequence       PDUType = 0x30
	GetRequest     PDUType = 0xa0
	GetNextRequest PDUType = 0xa1
	GetResponse    PDUType = 0xa2
	SetRequest     PDUType = 0xa3
	Trap           PDUType = 0xa4
	GetBulkRequest PDUType = 0xa5
	InformRequest  PDUType = 0xa6
	SNMPV2Trap     PDUType = 0xa7
	Report         PDUType = 0xa8
)

const (
	rxBufSizeMin = 1024   // Minimal buffer size to handle 1 OID (see dispatch())
	rxBufSizeMax = 131072 // 2 x max MTU size (65507)
)

// Logger is an interface used for debugging. Both Print and
// Printf have the same interfaces as Package Log in the std library. The
// Logger interface is small to give you flexibility in how you do
// your debugging.
//
// For verbose logging to stdout:
//
//     gosnmp_logger = log.New(os.Stdout, "", 0)
type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
}

// send/receive one snmp request
func (x *GoSNMP) sendOneRequest(pdus []SnmpPDU, packetOut *SnmpPacket) (result *SnmpPacket, err error) {
	finalDeadline := time.Now().Add(x.Timeout)

	allReqIDs := make([]uint32, 0, x.Retries+1)
	allMsgIDs := make([]uint32, 0, x.Retries+1)
	for retries := 0; ; retries++ {
		if retries > 0 {
			if x.loggingEnabled {
				x.Logger.Printf("Retry number %d. Last error was: %v", retries, err)
			}
			if time.Now().After(finalDeadline) {
				err = fmt.Errorf("Request timeout (after %d retries)", retries-1)
				break
			}
			if retries > x.Retries {
				// Report last error
				break
			}
		}
		err = nil

		reqDeadline := time.Now().Add(x.Timeout / time.Duration(x.Retries+1))
		x.Conn.SetDeadline(reqDeadline)

		// Request ID is an atomic counter (started at a random value)
		reqID := atomic.AddUint32(&(x.requestID), 1) // TODO: fix overflows
		allReqIDs = append(allReqIDs, reqID)

		var msgID uint32
		if x.Version == Version3 {
			msgID = atomic.AddUint32(&(x.msgID), 1) // TODO: fix overflows
			allMsgIDs = append(allMsgIDs, msgID)

			// http://tools.ietf.org/html/rfc2574#section-8.1.1.1
			// localDESSalt needs to be incremented on every packet.
			if x.MsgFlags&AuthPriv > AuthNoPriv && x.SecurityModel == UserSecurityModel {
				baseSecParams, ok := x.SecurityParameters.(*UsmSecurityParameters)
				if !ok || baseSecParams == nil {
					err = fmt.Errorf("&GoSNMP.SecurityModel indicates the User Security Model, but &GoSNMP.SecurityParameters is not of type &UsmSecurityParameters")
					break
				}
				var newPktLocalAESSalt uint64
				var newPktLocalDESSalt uint32
				switch baseSecParams.PrivacyProtocol {
				case AES:
					newPktLocalAESSalt = atomic.AddUint64(&(baseSecParams.localAESSalt), 1)
				case DES:
					newPktLocalDESSalt = atomic.AddUint32(&(baseSecParams.localDESSalt), 1)
				}

				if packetOut.Version == Version3 && packetOut.SecurityModel == UserSecurityModel && packetOut.MsgFlags&AuthPriv > AuthNoPriv {

					pktSecParams, ok := packetOut.SecurityParameters.(*UsmSecurityParameters)
					if !ok || baseSecParams == nil {
						err = fmt.Errorf("packetOut.SecurityModel indicates the User Security Model, but packetOut.SecurityParameters is not of type &UsmSecurityParameters")
						break
					}

					switch pktSecParams.PrivacyProtocol {
					case AES:
						var salt = make([]byte, 8)
						binary.BigEndian.PutUint64(salt, newPktLocalAESSalt)
						pktSecParams.PrivacyParameters = salt
					default:
						var salt = make([]byte, 8)
						binary.BigEndian.PutUint32(salt, pktSecParams.AuthoritativeEngineBoots)
						binary.BigEndian.PutUint32(salt[4:], newPktLocalDESSalt)
						pktSecParams.PrivacyParameters = salt
					}
				}
			}
		}

		var outBuf []byte
		outBuf, err = packetOut.marshalMsg(pdus, packetOut.PDUType, msgID, reqID)
		if err != nil {
			// Don't retry - not going to get any better!
			err = fmt.Errorf("marshal: %v", err)
			break
		}

		var expected int
		if packetOut.PDUType == GetBulkRequest {
			expected = int(packetOut.MaxRepetitions)
		} else {
			expected = len(pdus)
		}

		var resp []byte
		resp, err = x.dispatch(x.Conn, outBuf, expected)
		if err != nil {
			continue
		}
		result = new(SnmpPacket)
		result.MsgFlags = packetOut.MsgFlags
		if packetOut.SecurityParameters != nil {
			result.SecurityParameters = packetOut.SecurityParameters.Copy()
		}
		err = x.unmarshal(resp, result)
		if err != nil {
			err = fmt.Errorf("Unable to decode packet: %s", err.Error())
			continue
		}
		if result == nil || len(result.Variables) < 1 {
			err = fmt.Errorf("Unable to decode packet: nil")
			continue
		}

		validID := false
		for _, id := range allReqIDs {
			if id == result.RequestID {
				validID = true
			}
		}
		if result.RequestID == 0 {
			validID = true
		}
		if !validID {
			err = fmt.Errorf("Out of order response")
			continue
		}
		// Success!
		return result, nil
	}

	// Return last error
	return nil, err
}

// generic "sender" that negotiate any version of snmp request
func (x *GoSNMP) send(pdus []SnmpPDU, packetOut *SnmpPacket) (result *SnmpPacket, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("recover: %v", e)
		}
	}()

	if x.Conn == nil {
		return nil, fmt.Errorf("&GoSNMP.Conn is missing. Provide a connection or use Connect()")
	}

	if x.Retries < 0 {
		x.Retries = 0
	}

	// http://tools.ietf.org/html/rfc2574#section-2.2.3
	// This code does not check if the last message received was more than 150 seconds ago
	// The snmpds that this code was tested on emit an 'out of time window' error with the new
	// time and this code will retransmit when that is received.
	if packetOut.Version == Version3 {
		if packetOut.SecurityModel == UserSecurityModel {
			secParams, ok := packetOut.SecurityParameters.(*UsmSecurityParameters)
			if !ok || secParams == nil {
				return nil, fmt.Errorf("packetOut.SecurityModel indicates the User Security Model, but packetOut.SecurityParameters is not of type &UsmSecurityParameters")
			}
			if secParams.AuthoritativeEngineID == "" {
				// send blank packet to discover authoriative engine ID/boots/time
				blankPacket := &SnmpPacket{
					Version:            Version3,
					MsgFlags:           Reportable | NoAuthNoPriv,
					SecurityModel:      UserSecurityModel,
					SecurityParameters: &UsmSecurityParameters{},
					PDUType:            GetRequest,
				}
				var emptyPdus []SnmpPDU
				result, err := x.sendOneRequest(emptyPdus, blankPacket)

				if err != nil {
					return nil, err
				}
				// store the authoritative engine parameters
				newSecParams, ok := result.SecurityParameters.(*UsmSecurityParameters)
				if ok && newSecParams != nil {
					secParams.AuthoritativeEngineID = newSecParams.AuthoritativeEngineID
					secParams.AuthoritativeEngineBoots = newSecParams.AuthoritativeEngineBoots
					secParams.AuthoritativeEngineTime = newSecParams.AuthoritativeEngineTime

					// it seems common to use the authoritative engine id as the default
					// context engine id when it is not specified
					if packetOut.ContextEngineID == "" {
						packetOut.ContextEngineID = newSecParams.AuthoritativeEngineID
					}
					// store for base connection as well
					if x.ContextEngineID == "" {
						x.ContextEngineID = newSecParams.AuthoritativeEngineID
					}
				}

			}
		}
	}

	// perform request
	result, err = x.sendOneRequest(pdus, packetOut)
	if err != nil {
		return result, err
	}

	if result.Version == Version3 && result.SecurityModel == UserSecurityModel {
		secParams, ok := result.SecurityParameters.(*UsmSecurityParameters)
		if !ok || secParams == nil {
			return nil, fmt.Errorf("result.SecurityModel indicates the User Security Model, but result.SecurityParameters is not of type &UsmSecurityParameters")
		}
		if x.Version == Version3 && x.SecurityModel == UserSecurityModel {
			connSecParams, ok := x.SecurityParameters.(*UsmSecurityParameters)
			if !ok || connSecParams != nil {
				connSecParams.AuthoritativeEngineID = secParams.AuthoritativeEngineID
				connSecParams.AuthoritativeEngineBoots = secParams.AuthoritativeEngineBoots
				connSecParams.AuthoritativeEngineTime = secParams.AuthoritativeEngineTime
			}
			if x.ContextEngineID == "" {
				x.ContextEngineID = secParams.AuthoritativeEngineID
			}
		}

		if len(result.Variables) == 1 && result.Variables[0].Name == ".1.3.6.1.6.3.15.1.1.2.0" {

			// out of time window -- but since we just renegotiated the authoritative engine parameters,
			// just resubmit the packet with updated parameters
			pktSecParams, ok := packetOut.SecurityParameters.(*UsmSecurityParameters)
			if !ok || pktSecParams == nil {
				return nil, fmt.Errorf("packetOut.SecurityModel indicates the User Security Model, but packetOut.SecurityParameters is not of type &UsmSecurityParameters")
			}
			pktSecParams.AuthoritativeEngineID = secParams.AuthoritativeEngineID
			pktSecParams.AuthoritativeEngineBoots = secParams.AuthoritativeEngineBoots
			pktSecParams.AuthoritativeEngineTime = secParams.AuthoritativeEngineTime

			if packetOut.ContextEngineID == "" {
				packetOut.ContextEngineID = secParams.AuthoritativeEngineID
			}

			return x.sendOneRequest(pdus, packetOut)
		}
	}
	return result, err
}

// -- Marshalling Logic --------------------------------------------------------

// marshal an SNMP message
func (packet *SnmpPacket) marshalMsg(pdus []SnmpPDU,
	pdutype PDUType, msgid uint32, requestid uint32) ([]byte, error) {
	var authParamStart uint32
	buf := new(bytes.Buffer)

	// version
	buf.Write([]byte{2, 1, byte(packet.Version)})

	if packet.Version != Version3 {
		// community
		buf.Write([]byte{4, uint8(len(packet.Community))})
		buf.WriteString(packet.Community)
		// pdu
		pdu, err := packet.marshalPDU(pdus, requestid)
		if err != nil {
			return nil, err
		}
		buf.Write(pdu)
	} else {
		header, err := packet.marshalSnmpV3Header(msgid)
		if err != nil {
			return nil, err
		}
		buf.Write([]byte{byte(Sequence), byte(len(header))})
		buf.Write(header)

		var securityParameters []byte
		if packet.SecurityModel == UserSecurityModel {
			securityParameters, authParamStart, err = packet.marshalSnmpV3UsmSecurityParameters()
			if err != nil {
				return nil, err
			}
		}

		buf.Write([]byte{byte(OctetString)})
		secParamLen, err := marshalLength(len(securityParameters))
		if err != nil {
			return nil, err
		}
		buf.Write(secParamLen)
		authParamStart += uint32(buf.Len())
		buf.Write(securityParameters)

		scopedPdu, err := packet.marshalSnmpV3ScopedPDU(pdus, requestid)
		if err != nil {
			return nil, err
		}
		buf.Write(scopedPdu)
	}

	// build up resulting msg - sequence, length then the tail (buf)
	msg := new(bytes.Buffer)
	msg.WriteByte(byte(Sequence))

	bufLengthBytes, err2 := marshalLength(buf.Len())
	if err2 != nil {
		return nil, err2
	}
	msg.Write(bufLengthBytes)
	authParamStart += uint32(msg.Len())
	buf.WriteTo(msg) // reverse logic - want to do msg.Write(buf)

	authenticatedMessage, err := packet.authenticate(msg.Bytes(), authParamStart)
	if err != nil {
		return nil, err
	}

	return authenticatedMessage, nil
}

// marshal a snmp version 3 packet header
func (packet *SnmpPacket) marshalSnmpV3Header(msgid uint32) ([]byte, error) {
	buf := new(bytes.Buffer)

	// msg id
	buf.Write([]byte{byte(Integer), 4})
	err := binary.Write(buf, binary.BigEndian, msgid)
	if err != nil {
		return nil, err
	}

	// maximum response msg size
	maxmsgsize := marshalUvarInt(rxBufSizeMax)
	buf.Write([]byte{byte(Integer), byte(len(maxmsgsize))})
	buf.Write(maxmsgsize)

	// msg flags
	buf.Write([]byte{byte(OctetString), 1, byte(packet.MsgFlags)})

	// msg security model
	buf.Write([]byte{byte(Integer), 1, byte(packet.SecurityModel)})

	return buf.Bytes(), nil
}

// marshal a snmp version 3 security parameters field for the User Security Model
func (packet *SnmpPacket) marshalSnmpV3UsmSecurityParameters() ([]byte, uint32, error) {
	var buf bytes.Buffer
	var authParamStart uint32

	secParams, ok := packet.SecurityParameters.(*UsmSecurityParameters)
	if !ok || secParams == nil {
		return nil, 0, fmt.Errorf("packet.SecurityParameters is not of type &UsmSecurityParameters")
	}

	// msgAuthoritativeEngineID
	buf.Write([]byte{byte(OctetString), byte(len(secParams.AuthoritativeEngineID))})
	buf.WriteString(secParams.AuthoritativeEngineID)

	// msgAuthoritativeEngineBoots
	msgAuthoritativeEngineBoots := marshalUvarInt(secParams.AuthoritativeEngineBoots)
	buf.Write([]byte{byte(Integer), byte(len(msgAuthoritativeEngineBoots))})
	buf.Write(msgAuthoritativeEngineBoots)

	// msgAuthoritativeEngineTime
	msgAuthoritativeEngineTime := marshalUvarInt(secParams.AuthoritativeEngineTime)
	buf.Write([]byte{byte(Integer), byte(len(msgAuthoritativeEngineTime))})
	buf.Write(msgAuthoritativeEngineTime)

	// msgUserName
	buf.Write([]byte{byte(OctetString), byte(len(secParams.UserName))})
	buf.WriteString(secParams.UserName)

	authParamStart = uint32(buf.Len() + 2) // +2 indicates PDUType + Length
	// msgAuthenticationParameters
	if packet.MsgFlags&AuthNoPriv > 0 {
		buf.Write([]byte{byte(OctetString), 12,
			0, 0, 0, 0,
			0, 0, 0, 0,
			0, 0, 0, 0})
	} else {
		buf.Write([]byte{byte(OctetString), 0})
	}
	// msgPrivacyParameters
	if packet.MsgFlags&AuthPriv > AuthNoPriv {
		privlen, err := marshalLength(len(secParams.PrivacyParameters))
		if err != nil {
			return nil, 0, err
		}
		buf.Write([]byte{byte(OctetString)})
		buf.Write(privlen)
		buf.Write(secParams.PrivacyParameters)
	} else {
		buf.Write([]byte{byte(OctetString), 0})
	}

	// wrap security parameters in a sequence
	paramLen, err := marshalLength(buf.Len())
	if err != nil {
		return nil, 0, err
	}
	tmpseq := append([]byte{byte(Sequence)}, paramLen...)
	authParamStart += uint32(len(tmpseq))
	tmpseq = append(tmpseq, buf.Bytes()...)

	return tmpseq, authParamStart, nil
}

// marshal and encrypt (if necessary) a snmp version 3 Scoped PDU
func (packet *SnmpPacket) marshalSnmpV3ScopedPDU(pdus []SnmpPDU, requestid uint32) ([]byte, error) {
	var b []byte

	scopedPdu, err := packet.prepareSnmpV3ScopedPDU(pdus, requestid)
	if err != nil {
		return nil, err
	}
	pduLen, err := marshalLength(len(scopedPdu))
	if err != nil {
		return nil, err
	}
	b = append([]byte{byte(Sequence)}, pduLen...)
	scopedPdu = append(b, scopedPdu...)
	if packet.MsgFlags&AuthPriv > AuthNoPriv && packet.SecurityModel == UserSecurityModel {
		secParams, ok := packet.SecurityParameters.(*UsmSecurityParameters)
		if !ok || secParams == nil {
			return nil, fmt.Errorf("packet.SecurityModel indicates the User Security Model, but packet.SecurityParameters is not of type &UsmSecurityParameters")
		}
		var privkey = genlocalkey(secParams.AuthenticationProtocol,
			secParams.PrivacyPassphrase,
			secParams.AuthoritativeEngineID)
		switch secParams.PrivacyProtocol {
		case AES:
			var iv [16]byte
			binary.BigEndian.PutUint32(iv[:], secParams.AuthoritativeEngineBoots)
			binary.BigEndian.PutUint32(iv[4:], secParams.AuthoritativeEngineTime)
			copy(iv[8:], secParams.PrivacyParameters)

			block, err := aes.NewCipher(privkey[:16])
			if err != nil {
				return nil, err
			}
			stream := cipher.NewCFBEncrypter(block, iv[:])
			ciphertext := make([]byte, len(scopedPdu))
			stream.XORKeyStream(ciphertext, scopedPdu)
			pduLen, err := marshalLength(len(ciphertext))
			if err != nil {
				return nil, err
			}
			b = append([]byte{byte(OctetString)}, pduLen...)
			scopedPdu = append(b, ciphertext...)
		default:
			preiv := privkey[8:]
			var iv [8]byte
			for i := 0; i < len(iv); i++ {
				iv[i] = preiv[i] ^ secParams.PrivacyParameters[i]
			}
			block, err := des.NewCipher(privkey[:8])
			if err != nil {
				return nil, err
			}
			mode := cipher.NewCBCEncrypter(block, iv[:])

			pad := make([]byte, des.BlockSize-len(scopedPdu)%des.BlockSize)
			scopedPdu = append(scopedPdu, pad...)

			ciphertext := make([]byte, len(scopedPdu))
			mode.CryptBlocks(ciphertext, scopedPdu)
			pduLen, err := marshalLength(len(ciphertext))
			if err != nil {
				return nil, err
			}
			b = append([]byte{byte(OctetString)}, pduLen...)
			scopedPdu = append(b, ciphertext...)
		}

	}

	return scopedPdu, nil
}

// prepare the plain text of a snmp version 3 Scoped PDU
func (packet *SnmpPacket) prepareSnmpV3ScopedPDU(pdus []SnmpPDU, requestid uint32) ([]byte, error) {
	var buf bytes.Buffer

	//ContextEngineID
	idlen, err := marshalLength(len(packet.ContextEngineID))
	if err != nil {
		return nil, err
	}
	buf.Write(append([]byte{byte(OctetString)}, idlen...))
	buf.WriteString(packet.ContextEngineID)

	//ContextName
	namelen, err := marshalLength(len(packet.ContextName))
	if err != nil {
		return nil, err
	}
	buf.Write(append([]byte{byte(OctetString)}, namelen...))
	buf.WriteString(packet.ContextName)

	data, err := packet.marshalPDU(pdus, requestid)
	if err != nil {
		return nil, err
	}
	buf.Write(data)
	return buf.Bytes(), nil
}

// marshal a PDU
func (packet *SnmpPacket) marshalPDU(pdus []SnmpPDU, requestid uint32) ([]byte, error) {
	buf := new(bytes.Buffer)

	// requestid
	buf.Write([]byte{2, 4})
	err := binary.Write(buf, binary.BigEndian, requestid)
	if err != nil {
		return nil, err
	}

	if packet.PDUType == GetBulkRequest {
		// non repeaters
		buf.Write([]byte{2, 1, packet.NonRepeaters})

		// max repetitions
		buf.Write([]byte{2, 1, packet.MaxRepetitions})
	} else { // get and getnext have same packet format

		// error
		buf.Write([]byte{2, 1, 0})

		// error index
		buf.Write([]byte{2, 1, 0})
	}

	// varbind list
	vbl, err := packet.marshalVBL(pdus)
	if err != nil {
		return nil, err
	}
	buf.Write(vbl)

	// build up resulting pdu - request type, length, then the tail (buf)
	pdu := new(bytes.Buffer)
	pdu.WriteByte(byte(packet.PDUType))

	bufLengthBytes, err2 := marshalLength(buf.Len())
	if err2 != nil {
		return nil, err2
	}
	pdu.Write(bufLengthBytes)

	buf.WriteTo(pdu) // reverse logic - want to do pdu.Write(buf)
	return pdu.Bytes(), nil
}

// marshal a varbind list
func (packet *SnmpPacket) marshalVBL(pdus []SnmpPDU) ([]byte, error) {

	vblBuf := new(bytes.Buffer)
	for _, pdu := range pdus {
		vb, err := marshalVarbind(&pdu)
		if err != nil {
			return nil, err
		}
		vblBuf.Write(vb)
	}

	vblBytes := vblBuf.Bytes()
	vblLengthBytes, err := marshalLength(len(vblBytes))
	if err != nil {
		return nil, err
	}

	// FIX does bytes.Buffer give better performance than byte slices?
	result := []byte{byte(Sequence)}
	result = append(result, vblLengthBytes...)
	result = append(result, vblBytes...)
	return result, nil
}

// marshal a varbind
func marshalVarbind(pdu *SnmpPDU) ([]byte, error) {
	oid, err := marshalOID(pdu.Name)
	if err != nil {
		return nil, err
	}
	pduBuf := new(bytes.Buffer)
	tmpBuf := new(bytes.Buffer)

	// Marshal the PDU type into the appropriate BER
	switch pdu.Type {

	case Null:
		pduBuf.Write([]byte{byte(Sequence), byte(len(oid) + 4)})
		pduBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
		pduBuf.Write(oid)
		pduBuf.Write([]byte{Null, 0x00})

	case Integer:
		// TODO tests currently only cover positive integers
		// Oid
		tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
		tmpBuf.Write(oid)
		// Integer
		var intBytes []byte
		switch value := pdu.Value.(type) {
		case byte:
			intBytes = []byte{byte(pdu.Value.(int))}
		case int:
			intBytes = marshalInt16(value)
		default:
			return nil, fmt.Errorf("Unable to marshal PDU Integer; not byte or int.")
		}
		tmpBuf.Write([]byte{byte(Integer), byte(len(intBytes))})
		tmpBuf.Write(intBytes)
		// Sequence, length of oid + integer, then oid/integer data
		pduBuf.WriteByte(byte(Sequence))
		pduBuf.WriteByte(byte(len(oid) + len(intBytes) + 4))
		pduBuf.Write(tmpBuf.Bytes())

	case OctetString:
		//Oid
		tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
		tmpBuf.Write(oid)
		//OctetString
		var octetStringBytes []byte
		switch value := pdu.Value.(type) {
		case []byte:
			octetStringBytes = value
		case string:
			octetStringBytes = []byte(value)
		default:
			return nil, fmt.Errorf("Unable to marshal PDU OctetString; not []byte or String.")
		}
		tmpBuf.Write([]byte{byte(OctetString), byte(len(octetStringBytes))})
		tmpBuf.Write(octetStringBytes)
		// Sequence, length of oid + octetstring, then oid/octetstring data
		pduBuf.WriteByte(byte(Sequence))
		pduBuf.WriteByte(byte(len(oid) + len(octetStringBytes) + 4))
		pduBuf.Write(tmpBuf.Bytes())

	default:
		return nil, fmt.Errorf("Unable to marshal PDU: unknown BER type %d", pdu.Type)
	}

	return pduBuf.Bytes(), nil
}

// -- Unmarshalling Logic ------------------------------------------------------

func (x *GoSNMP) unmarshal(packet []byte, response *SnmpPacket) error {
	if response == nil {
		return fmt.Errorf("Cannot unmarshal response into nil packet reference")
	}
	var OrigMsgFlags = response.MsgFlags
	var OrigAuthEngineID string

	secParameters, ok := response.SecurityParameters.(*UsmSecurityParameters)
	if ok && secParameters != nil {
		OrigAuthEngineID = secParameters.AuthoritativeEngineID
	}
	response.Variables = make([]SnmpPDU, 0, 5)

	// Start parsing the packet
	cursor := 0

	// First bytes should be 0x30
	if PDUType(packet[0]) != Sequence {
		return fmt.Errorf("Invalid packet header\n")
	}

	length, cursor := parseLength(packet)
	if len(packet) != length {
		return fmt.Errorf("Error verifying packet sanity: Got %d Expected: %d\n", len(packet), length)
	}
	if x.loggingEnabled {
		x.Logger.Printf("Packet sanity verified, we got all the bytes (%d)", length)
	}

	// Parse SNMP Version
	rawVersion, count, err := x.parseRawField(packet[cursor:], "version")
	if err != nil {
		return fmt.Errorf("Error parsing SNMP packet version: %s", err.Error())
	}

	cursor += count
	if version, ok := rawVersion.(int); ok {
		response.Version = SnmpVersion(version)
		if x.loggingEnabled {
			x.Logger.Printf("Parsed version %d", version)
		}
	}
	if response.Version != Version3 {
		// Parse community
		rawCommunity, count, err := x.parseRawField(packet[cursor:], "community")
		if err != nil {
			return fmt.Errorf("Error parsing community string: %s", err.Error())
		}
		cursor += count
		if community, ok := rawCommunity.(string); ok {
			response.Community = community
			if x.loggingEnabled {
				x.Logger.Printf("Parsed community %s", community)
			}
		}
	} else {
		if PDUType(packet[cursor]) != Sequence {
			return fmt.Errorf("Invalid SNMPV3 Header\n")
		}

		_, cursorTmp := parseLength(packet[cursor:])
		cursor += cursorTmp

		rawMsgID, count, err := x.parseRawField(packet[cursor:], "msgID")
		if err != nil {
			return fmt.Errorf("Error parsing SNMPV3 message ID: %s", err.Error())
		}
		cursor += count
		if MsgID, ok := rawMsgID.(int); ok {
			response.MsgID = uint32(MsgID)
			if x.loggingEnabled {
				x.Logger.Printf("Parsed message ID %d", MsgID)

			}
		}
		// discard msg max size
		_, count, err = x.parseRawField(packet[cursor:], "maxMsgSize")
		if err != nil {
			return fmt.Errorf("Error parsing SNMPV3 maxMsgSize: %s", err.Error())
		}
		cursor += count
		// discard msg max size

		rawMsgFlags, count, err := x.parseRawField(packet[cursor:], "msgFlags")
		if err != nil {
			return fmt.Errorf("Error parsing SNMPV3 msgFlags: %s", err.Error())
		}
		cursor += count
		if MsgFlags, ok := rawMsgFlags.(string); ok {
			response.MsgFlags = SnmpV3MsgFlags(MsgFlags[0])
			if x.loggingEnabled {
				x.Logger.Printf("parsed msg flags %s", MsgFlags)
			}
		}

		rawSecModel, count, err := x.parseRawField(packet[cursor:], "msgSecurityModel")
		if err != nil {
			return fmt.Errorf("Error parsing SNMPV3 msgSecModel: %s", err.Error())
		}
		cursor += count
		if SecModel, ok := rawSecModel.(int); ok {
			response.SecurityModel = SnmpV3SecurityModel(SecModel)
			if x.loggingEnabled {
				x.Logger.Printf("Parsed security model %d", SecModel)
			}
		}

		if PDUType(packet[cursor]) != OctetString {
			return fmt.Errorf("Invalid SNMPV3 Security Parameters\n")
		}
		_, cursorTmp = parseLength(packet[cursor:])
		cursor += cursorTmp

		if response.SecurityModel == UserSecurityModel {
			secParameters, ok := response.SecurityParameters.(*UsmSecurityParameters)
			if !ok || secParameters == nil {
				return fmt.Errorf("&GoSNMP.SecurityModel indicates the User Security Model, but &GoSNMP.SecurityParameters is not of type &UsmSecurityParameters")
			}

			if PDUType(packet[cursor]) != Sequence {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model parameters\n")
			}
			_, cursorTmp = parseLength(packet[cursor:])
			cursor += cursorTmp

			rawMsgAuthoritativeEngineID, count, err := x.parseRawField(packet[cursor:], "msgAuthoritativeEngineID")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgAuthoritativeEngineID: %s", err.Error())
			}
			cursor += count
			if AuthoritativeEngineID, ok := rawMsgAuthoritativeEngineID.(string); ok {
				secParameters.AuthoritativeEngineID = AuthoritativeEngineID
				if x.loggingEnabled {
					x.Logger.Printf("Parsed authoritativeEngineID %s", AuthoritativeEngineID)
				}
			}

			rawMsgAuthoritativeEngineBoots, count, err := x.parseRawField(packet[cursor:], "msgAuthoritativeEngineBoots")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgAuthoritativeEngineBoots: %s", err.Error())
			}
			cursor += count
			if AuthoritativeEngineBoots, ok := rawMsgAuthoritativeEngineBoots.(int); ok {
				secParameters.AuthoritativeEngineBoots = uint32(AuthoritativeEngineBoots)
				if x.loggingEnabled {
					x.Logger.Printf("Parsed authoritativeEngineBoots %d", AuthoritativeEngineBoots)
				}
			}

			rawMsgAuthoritativeEngineTime, count, err := x.parseRawField(packet[cursor:], "msgAuthoritativeEngineTime")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgAuthoritativeEngineTime: %s", err.Error())
			}
			cursor += count
			if AuthoritativeEngineTime, ok := rawMsgAuthoritativeEngineTime.(int); ok {
				secParameters.AuthoritativeEngineTime = uint32(AuthoritativeEngineTime)
				if x.loggingEnabled {
					x.Logger.Printf("Parsed authoritativeEngineTime %d", AuthoritativeEngineTime)
				}
			}

			rawMsgUserName, count, err := x.parseRawField(packet[cursor:], "msgUserName")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgUserName: %s", err.Error())
			}
			cursor += count
			if msgUserName, ok := rawMsgUserName.(string); ok {
				secParameters.UserName = msgUserName
				if x.loggingEnabled {
					x.Logger.Printf("Parsed userName %s", msgUserName)
				}
			}

			rawMsgAuthParameters, count, err := x.parseRawField(packet[cursor:], "msgAuthenticationParameters")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgAuthenticationParameters: %s", err.Error())
			}

			if msgAuthenticationParameters, ok := rawMsgAuthParameters.(string); ok {
				secParameters.AuthenticationParameters = msgAuthenticationParameters
				if x.loggingEnabled {
					x.Logger.Printf("Parsed authenticationParameters %s", msgAuthenticationParameters)
				}
			}
			// use the authoritative copy of MsgFlags to determine whether this message should be authenticated
			if OrigMsgFlags&AuthNoPriv > 0 {
				if count != 14 {
					return fmt.Errorf("Error authenticating incoming packet: msgAuthenticationParameters is not the correct size")
				}
				blank := make([]byte, 12)
				copy(packet[cursor+2:cursor+14], blank)
				// secParameters.AuthenticationProtocol and secParameters.AuthenticationPassphrase are not written to in this function,
				// so no need to save an 'original' to authenticate against
				if !isAuthentic(packet, secParameters.AuthenticationParameters,
					secParameters.AuthenticationProtocol,
					secParameters.AuthenticationPassphrase,
					OrigAuthEngineID) {
					return fmt.Errorf("Incoming packet is not authentic, discarding")
				}
			}
			cursor += count

			rawMsgPrivacyParameters, count, err := x.parseRawField(packet[cursor:], "msgPrivacyParameters")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 User Security Model msgPrivacyParameters: %s", err.Error())
			}
			cursor += count
			if msgPrivacyParameters, ok := rawMsgPrivacyParameters.(string); ok {
				secParameters.PrivacyParameters = []byte(msgPrivacyParameters)
				if x.loggingEnabled {
					x.Logger.Printf("Parsed privacyParameters %s", msgPrivacyParameters)
				}
			}

			//response.SecurityParameters = &secParameters
		}
		switch PDUType(packet[cursor]) {
		case OctetString:
			// pdu is encrypted
			_, cursorTmp := parseLength(packet[cursor:])
			cursorTmp += cursor

			if response.SecurityModel == UserSecurityModel {
				var secParams *UsmSecurityParameters
				secParams, ok := response.SecurityParameters.(*UsmSecurityParameters)
				if !ok || secParams == nil {
					return fmt.Errorf("response.SecurityModel indicates the User Security Model, but response.SecurityParameters is not of type &UsmSecurityParameters")
				}
				var privkey = genlocalkey(secParams.AuthenticationProtocol,
					secParams.PrivacyPassphrase,
					secParams.AuthoritativeEngineID)
				switch secParams.PrivacyProtocol {
				case AES:
					var iv [16]byte
					binary.BigEndian.PutUint32(iv[:], secParams.AuthoritativeEngineBoots)
					binary.BigEndian.PutUint32(iv[4:], secParams.AuthoritativeEngineTime)
					copy(iv[8:], secParams.PrivacyParameters)

					block, err := aes.NewCipher(privkey[:16])
					if err != nil {
						return err
					}
					stream := cipher.NewCFBDecrypter(block, iv[:])
					plaintext := make([]byte, len(packet[cursorTmp:]))
					stream.XORKeyStream(plaintext, packet[cursorTmp:])
					copy(packet[cursor:], plaintext)
					packet = packet[:cursor+len(plaintext)]
				default:
					if len(packet[cursorTmp:])%des.BlockSize != 0 {
						return fmt.Errorf("Error decrypting ScopedPDU: not multiple of des block size.")
					}
					preiv := privkey[8:]
					var iv [8]byte
					for i := 0; i < len(iv); i++ {
						iv[i] = preiv[i] ^ secParams.PrivacyParameters[i]
					}
					block, err := des.NewCipher(privkey[:8])
					if err != nil {
						return err
					}
					mode := cipher.NewCBCDecrypter(block, iv[:])

					plaintext := make([]byte, len(packet[cursorTmp:]))
					mode.CryptBlocks(plaintext, packet[cursorTmp:])
					copy(packet[cursor:], plaintext)
					// truncate packet to remove extra space caused by the
					// octetstring/length header that was just replaced
					packet = packet[:cursor+len(plaintext)]
				}

			}
			fallthrough
		case Sequence:
			// pdu is plaintext
			tlength, cursorTmp := parseLength(packet[cursor:])
			// truncate padding that may have been included with
			// the encrypted PDU
			packet = packet[:cursor+tlength]
			cursor += cursorTmp
			rawContextEngineID, count, err := x.parseRawField(packet[cursor:], "contextEngineID")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 contextEngineID: %s", err.Error())
			}
			cursor += count
			if contextEngineID, ok := rawContextEngineID.(string); ok {
				response.ContextEngineID = contextEngineID
				if x.loggingEnabled {
					x.Logger.Printf("Parsed contextEngineID %s", contextEngineID)
				}
			}
			rawContextName, count, err := x.parseRawField(packet[cursor:], "contextName")
			if err != nil {
				return fmt.Errorf("Error parsing SNMPV3 contextName: %s", err.Error())
			}
			cursor += count
			if contextName, ok := rawContextName.(string); ok {
				response.ContextName = contextName
				if x.loggingEnabled {
					x.Logger.Printf("Parsed contextName %s", contextName)
				}
			}

		default:
			return fmt.Errorf("Error parsing SNMPV3 scoped PDU\n")
		}
	}
	// Parse SNMP packet type
	requestType := PDUType(packet[cursor])
	switch requestType {
	// known, supported types
	case GetResponse, GetNextRequest, GetBulkRequest, Report, SNMPV2Trap:
		response, err = x.unmarshalResponse(packet[cursor:], response, length, requestType)
		if err != nil {
			return fmt.Errorf("Error in unmarshalResponse: %s", err.Error())
		}
	default:
		return fmt.Errorf("Unknown PDUType %#x", requestType)
	}
	return nil
}

func (x *GoSNMP) unmarshalResponse(packet []byte, response *SnmpPacket, length int, requestType PDUType) (*SnmpPacket, error) {
	cursor := 0
	x.dumpBytes1(packet, "SNMP Packet is GET RESPONSE", 16)
	response.PDUType = requestType

	getResponseLength, cursor := parseLength(packet)
	if len(packet) != getResponseLength {
		return nil, fmt.Errorf("Error verifying Response sanity: Got %d Expected: %d\n", len(packet), getResponseLength)
	}
	if x.loggingEnabled {
		x.Logger.Printf("getResponseLength: %d", getResponseLength)
	}

	// Parse Request-ID
	rawRequestID, count, err := x.parseRawField(packet[cursor:], "request id")
	if err != nil {
		return nil, fmt.Errorf("Error parsing SNMP packet request ID: %s", err.Error())
	}
	cursor += count
	if requestid, ok := rawRequestID.(int); ok {
		response.RequestID = uint32(requestid)
		if x.loggingEnabled {
			x.Logger.Printf("requestID: %d", response.RequestID)
		}
	}

	if response.PDUType == GetBulkRequest {
		// Parse Non Repeaters
		rawNonRepeaters, count, err := x.parseRawField(packet[cursor:], "non repeaters")
		if err != nil {
			return nil, fmt.Errorf("Error parsing SNMP packet non repeaters: %s", err.Error())
		}
		cursor += count
		if nonRepeaters, ok := rawNonRepeaters.(int); ok {
			response.NonRepeaters = uint8(nonRepeaters)
		}

		// Parse Max Repetitions
		rawMaxRepetitions, count, err := x.parseRawField(packet[cursor:], "max repetitions")
		if err != nil {
			return nil, fmt.Errorf("Error parsing SNMP packet max repetitions: %s", err.Error())
		}
		cursor += count
		if maxRepetitions, ok := rawMaxRepetitions.(int); ok {
			response.MaxRepetitions = uint8(maxRepetitions)
		}
	} else {
		// Parse Error-Status
		rawError, count, err := x.parseRawField(packet[cursor:], "error-status")
		if err != nil {
			return nil, fmt.Errorf("Error parsing SNMP packet error: %s", err.Error())
		}
		cursor += count
		if errorStatus, ok := rawError.(int); ok {
			response.Error = uint8(errorStatus)
			if x.loggingEnabled {
				x.Logger.Printf("errorStatus: %d", uint8(errorStatus))
			}
		}

		// Parse Error-Index
		rawErrorIndex, count, err := x.parseRawField(packet[cursor:], "error index")
		if err != nil {
			return nil, fmt.Errorf("Error parsing SNMP packet error index: %s", err.Error())
		}
		cursor += count
		if errorindex, ok := rawErrorIndex.(int); ok {
			response.ErrorIndex = uint8(errorindex)
			if x.loggingEnabled {
				x.Logger.Printf("error-index: %d", uint8(errorindex))
			}
		}
	}

	return x.unmarshalVBL(packet[cursor:], response, length)
}

// unmarshal a Varbind list
func (x *GoSNMP) unmarshalVBL(packet []byte, response *SnmpPacket,
	length int) (*SnmpPacket, error) {

	x.dumpBytes1(packet, "\n=== unmarshalVBL()", 32)
	var cursor, cursorInc int
	var vblLength int
	if packet[cursor] != 0x30 {
		return nil, fmt.Errorf("Expected a sequence when unmarshalling a VBL, got %x",
			packet[cursor])
	}

	vblLength, cursor = parseLength(packet)
	if len(packet) != vblLength {
		return nil, fmt.Errorf("Error verifying: packet length %d vbl length %d\n",
			len(packet), vblLength)
	}
	if x.loggingEnabled {
		x.Logger.Printf("vblLength: %d", vblLength)
	}

	// check for an empty response
	if vblLength == 2 && packet[1] == 0x00 {
		return response, nil
	}

	// Loop & parse Varbinds
	for cursor < vblLength {
		x.dumpBytes1(packet[cursor:], fmt.Sprintf("\nSTARTING a varbind. Cursor %d", cursor), 32)
		if packet[cursor] != 0x30 {
			return nil, fmt.Errorf("Expected a sequence when unmarshalling a VB, got %x", packet[cursor])
		}

		_, cursorInc = parseLength(packet[cursor:])
		cursor += cursorInc

		// Parse OID
		rawOid, oidLength, err := x.parseRawField(packet[cursor:], "OID")
		if err != nil {
			return nil, fmt.Errorf("Error parsing OID Value: %s", err.Error())
		}
		cursor += oidLength

		var oid []int
		var ok bool
		if oid, ok = rawOid.([]int); !ok {
			return nil, fmt.Errorf("unable to type assert rawOid |%v| to []int", rawOid)
		}
		oidStr := oidToString(oid)
		if x.loggingEnabled {
			x.Logger.Printf("OID: %s", oidStr)
		}

		// Parse Value
		v, err := x.decodeValue(packet[cursor:], "value")
		if err != nil {
			return nil, fmt.Errorf("Error decoding value: %v", err)
		}
		valueLength, _ := parseLength(packet[cursor:])
		cursor += valueLength
		response.Variables = append(response.Variables, SnmpPDU{oidStr, v.Type, v.Value})
	}
	return response, nil
}

// dispatch request on network, and read the results into a byte array
//
// Previously, resp was allocated rxBufSize (65536) bytes ie a fixed size for
// all responses. To decrease memory usage, resp is dynamically sized, at the
// cost of possible additional network round trips.
func (x *GoSNMP) dispatch(c net.Conn, outBuf []byte, expected int) ([]byte, error) {
	if expected <= 0 {
		expected = 1
	}
	var resp []byte
	for bufSize := rxBufSizeMin * expected; bufSize < rxBufSizeMax; bufSize *= 2 {
		resp = make([]byte, bufSize)
		_, err := c.Write(outBuf)
		if err != nil {
			return resp, fmt.Errorf("Error writing to socket: %s", err.Error())
		}
		n, err := c.Read(resp)
		if err != nil {
			// On Windows we don't get a partial read and truncation. Instead
			// we get an error if buff is too small - WSAEMSGSIZE 10040.
			const WSAEMSGSIZE syscall.Errno = 10040
			if opErr, ok := err.(*net.OpError); ok {
				if opErr.Err == WSAEMSGSIZE {
					continue
				}
			}
			return resp, fmt.Errorf("Error reading from UDP: %s", err.Error())
		}

		if n < bufSize {
			// Memory usage optimization. Help the runtime to release as much memory as
			// possible.
			//
			// See: http://blog.golang.org/go-slices-usage-and-internals,
			//    section: A possible "gotcha"
			// ...As mentioned earlier, re-slicing a slice doesn't make a copy of the
			// underlying array. The full array will be kept in memory until it is no
			// longer referenced. Occasionally this can cause the program to hold all
			// the data in memory when only a small piece of it is needed.
			resp = resp[:n]
			resp2 := make([]byte, len(resp))
			copy(resp2, resp)
			return resp2, nil
		}
		x.Logger.Printf("Retrying. Buffer size was too small. (size %d)", bufSize)
	}
	return resp, fmt.Errorf("Response bufSize exceeded rxBufSizeMax (%d)", rxBufSizeMax)
}


text:
layout: page
title: Snyder Ice Air Trade Fair
date: 2016-05-24
author: Margaret Jackson
tags: weekly links, java
status: published
summary: Suspendisse vitae mi et lacus pharetra.
banner: images/banner/people.jpg
booking:
  startDate: 06/02/2019
  endDate: 06/05/2019
  ctyhocn: BALEGHX
  groupCode: SIATF
published: true
---
Quisque vitae sapien id nunc ultricies blandit. Duis pharetra viverra aliquam. Curabitur viverra justo vel sagittis condimentum. Donec lectus nibh, facilisis tristique elit id, efficitur viverra lorem. Donec pretium urna sagittis, maximus dui eleifend, bibendum risus. Integer egestas mauris purus, non faucibus justo ultrices nec. Nullam mauris libero, blandit eget fermentum et, finibus id est. Nunc a ex vel risus finibus consequat. Curabitur nunc orci, mollis ut nisi at, rutrum interdum orci. Ut interdum nunc nunc, vestibulum semper odio faucibus eu. In nec ligula turpis.

* Etiam vitae lectus euismod, tristique odio egestas, pharetra enim
* Proin ut eros nec felis consequat auctor imperdiet quis libero.

Etiam et nulla nulla. Fusce volutpat purus vitae nisl dignissim sagittis. Mauris rhoncus in ante in hendrerit. Duis eget neque nisl. Fusce fermentum arcu consequat sem congue imperdiet. Quisque rutrum vehicula consequat. Duis viverra eget purus id tristique.

redpajama_set_name: RedPajamaGithub


text:
class AddProjectIdToIdea < ActiveRecord::Migration
  def up
    add_column :ideas, :project_id, :integer
    add_index :ideas, :project_id
  end

  def down
    remove_column :ideas, :project_id
  end
end


text:
====
smif
====

Simulation Modelling Integration Framework

.. image:: https://img.shields.io/badge/github-nismod%2Fsmif-brightgreen.svg
   :target: https://github.com/nismod/smif/
   :alt: nismod/smif on github

.. include:: ../README.rst
   :start-line: 8
   :end-line: 36

.. include:: ../README.rst
   :start-line: 36
   :end-line: 118

.. include:: ../README.rst
   :start-line: 241

Contents
========

.. toctree::
   :maxdepth: 2

   Installation <installation>
   Getting Started <getting_started>
   Concepts <concepts>
   Configuration <project_configuration>
   Adding a Model <simulation_models>
   Strategies, Interventions and Decisions <decisions>

.. toctree::
   :maxdepth: 3

   Reference <api/modules>

.. toctree::
   :maxdepth: 2

   Developing `smif` <developers>
   Contributing <contributing>
   License <license>
   Authors <authors>
   Changelog <changelog>

Indexes and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
"""Handling connection with a local Taxonomy Database."""

import doctest
import pymongo
import os
import json
from pymongo.errors import AutoReconnect

from own_exceptions import NoProteinLink, NoRecord
from own_objects import Node

# MongoDB connection test for methods requiring database access
def autoreconnect_retry(func, retries=3):
    """Decorating checking connection to the database."""
    def db_op_wrapper(*args, **kwargs):
        """Decorator wrapper"""
        tries = 0

        while tries < retries:
            try:
                return func(*args, **kwargs)

            except AutoReconnect:
                tries += 1

        raise Exception(
            "Couldn't connect to the database, even after %d retries" % retries)
    return db_op_wrapper

class TaxDb(object):
    """Class containing methods to handle users requests for translating
    tax ids into phylogenies.

    """

    def __init__(self, cfg_file=None):
        """Connects to the database"""

        # Read database configuration from file
        if not cfg_file:
            cfg_file = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                    'db.cfg'))
        cfg = self.read_db_cfg(cfg_file)

        # Parse database configuration
        self.HOSTNAME = cfg['HOSTNAME']
        self.PORT = int(cfg['PORT'])
        self.NAME = cfg['NAME']

        self.db_client = pymongo.MongoClient(self.HOSTNAME, self.PORT)

        database = self.db_client[self.NAME]
        self.db_nodes = database.nodes
        self.db_links = database.links

    @staticmethod
    def read_db_cfg(cfg_file=None):
        """Reads database configuration from JSON file."""

        # Get absolute path to a default config file, if not provided
        with open(cfg_file, 'r') as handle:
            cfg = json.load(handle)

        return cfg

    def disconnect(self):
        """Closes connection to the database"""

        self.db_client.close()

    @autoreconnect_retry
    def add_record(self, node):
        """Method updates database with a new entry.

        Params:
            node (Node): TaxDB node object

        Returns:
            result (ObjectId): Unique ID of a newly added record.

        """

        try:
            self.db_nodes.insert_one(node.post_format())
        except pymongo.errors.DuplicateKeyError:
            print('%s already exists. Record not inserted.' % node.taxid)

    @autoreconnect_retry
    def add_protein_link(self, protein_link):
        """Method updates database with a new protein link.
        Params:
            protein_link (ProteinLink): ProteinLink object

        Returns:
            result (ObjectID): Unique ID of a newly added link
        """

        try:
            self.db_links.insert_one(protein_link.post_format())
        except pymongo.errors.DuplicateKeyError:
            print('%s already exists, link not inserted.'
                  % protein_link.protein_id)

    @autoreconnect_retry
    def get_node(self, taxid):
        """Returns node record from database.

        Params:
            taxid (str): Taxonomy ID

        Returns:
            record (Node): Node record
        """

        result = self.db_nodes.find_one({'TaxID': taxid})

        if not result:
            raise NoRecord(taxid)

        record = Node(taxid=result['TaxID'],
                      scientific_name=result['SciName'],
                      upper_hierarchy=result['Parent'])

        return record

    @autoreconnect_retry
    def search_scientific_name(self, sci_name):
        """Search Database with scientific name

        Params:
            sci_name (str): Scientific name of an organism or phylum to search

        Returns:
            record (Node): Node record from the database

        """

        result = self.db_nodes.find_one({'SciName': sci_name})

        if not result:
            raise NoRecord(sci_name)

        record = Node(taxid=result['TaxID'],
                      scientific_name=result['SciName'],
                      upper_hierarchy=result['Parent'])

        return record

    @autoreconnect_retry
    def protein_taxid(self, protein_id):
        """Translates protein id to taxonomy id"""

        record = self.db_links.find_one({'ProteinID':protein_id})

        if not record:
            raise NoProteinLink(protein_acc=protein_id)

        return record['TaxID']

    def get_lineage_from_db(self, taxid, lineage=None):
        """Method retrieves phylogenetic lineage from database based on
        accession.

        Params:
            tax_id (str): NCBI taxonomy identifier.

        Returns:
            lineage (str): Lineage of an organism represented by tax identifier.
        """

        # If it is the first call
        if not lineage:
            lineage = []

        curr_taxid = self.get_node(taxid=taxid)

        # Check whether it is not the highest hierarchy possible
        if curr_taxid.taxid != curr_taxid.upper_hierarchy:
            # if there is higher hierarchy, append and travel up the tree
            lineage.append(curr_taxid.scientific_name)
            try:
                return TaxDb.get_lineage_from_db(self, curr_taxid.upper_hierarchy, lineage)
            except NoRecord:
                pass

        lineage.append(curr_taxid.scientific_name)
        lineage.reverse()
        return lineage

if __name__ == "__main__":
    doctest.testmod()


text:
// 起動コード
window.addEventListener('DOMContentLoaded', () => {
  new Main();
});

/**
 * パーティクルデモのメインクラスです。
 * @author Yasunobu Ikeda
 */
class Main {

  constructor() {
    // ウェーブ風グラフィック用のステージを作成
    this.stageCalcInside = new createjs.Stage(document.createElement('canvas'));
    this.stageCalcInside.autoClear = false;

    // ウェーブ風グラフィックを作成
    const waveShape = new WaveShape();
    this.stageCalcInside.addChild(waveShape);

    // スポットライト風グラフィック用のステージを作成
    this.stageOverlay = new createjs.Stage('canvasOverlay');

    // スポットライト風グラフィック
    this.spotLightShape = new SpotLightShape();
    this.stageOverlay.addChild(this.spotLightShape);

    // Tickerを作成
    createjs.Ticker.timingMode = createjs.Ticker.RAF;
    createjs.Ticker.on('tick', this.handleTick, this);

    // リサイズイベント
    this.handleResize();
    window.addEventListener('resize', () => {
      this.handleResize();
    });
  }

  /**
   * エンターフレームイベント
   */
  handleTick() {
    // 薄く暗く塗る
    const context = this.stageCalcInside.canvas.getContext('2d');
    context.fillStyle = `rgba(0, 0, 0, 0.2)`;
    context.fillRect(
      0,
      0,
      this.stageCalcInside.canvas.width,
      this.stageCalcInside.canvas.height);

    // 波の表現を更新
    this.stageCalcInside.update();

    // スポットライト風グラフィックの描画
    this.spotLightShape.drawContents(innerWidth, innerHeight);
    this.stageOverlay.update();

    // 2つのステージを合成する
    const context2 = this.stageOverlay.canvas.getContext('2d');
    context2.globalCompositeOperation = 'lighter';
    context2.drawImage(this.stageCalcInside.canvas, 0, 0);
  }

  /**
   * リサイズイベント
   */
  handleResize() {
    // ウェーブ風グラフィック用ステージのりサイズ
    this.stageCalcInside.canvas.width = innerWidth;
    this.stageCalcInside.canvas.height = innerHeight;

    // スポットライト風グラフィック用ステージのりサイズ
    this.stageOverlay.canvas.width = innerWidth;
    this.stageOverlay.canvas.height = innerHeight;
  }
}


text:
package com.mmnaseri.cs.clrs.ch09.sp;

import com.mmnaseri.cs.clrs.ch09.s3.LinearSelector;
import com.mmnaseri.cs.clrs.common.ArrayUtils;
import com.mmnaseri.cs.clrs.common.Sorter;
import com.mmnaseri.cs.qa.annotation.Quality;
import com.mmnaseri.cs.qa.annotation.Stage;

import java.util.Comparator;

import static com.mmnaseri.cs.clrs.ch09.SelectionUtils.selectPartition;

/**
 * @author Mohammad Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (7/12/15, 9:05 PM)
 */
@Quality(Stage.TESTED)
public class BestCaseQuickSorter<E extends Comparable<E>> implements Sorter<E> {

    private final Comparator<E> comparator;
    private final LinearSelector<E> selector;

    public BestCaseQuickSorter(Comparator<E> comparator) {
        this.comparator = comparator;
        selector = new LinearSelector<>(comparator);
    }

    private int partition(E[] items, int from, int to, int pivot) {
        return selectPartition(comparator, items, from, to, pivot);
    }

    private void sort(E[] items, int from, int to) {
        if (from < to - 1) {
            if (to - from == 2) {
                if (comparator.compare(items[from], items[to - 1]) > 0) {
                    ArrayUtils.swap(items, from, to - 1);
                }
                return;
            }
            int median = (int) Math.ceil((from + to) / 2.0) - 1;
            final int pivot = selector.select(items, null, 0, items.length, median);
            int middle = partition(items, from, to, pivot);
            sort(items, from, middle);
            sort(items, middle + 1, to);
        }
    }

    @Override
    public void sort(E[] items) {
        sort(items, 0, items.length);
    }

}


text:
<?php
namespace buildok\validator\exceptions;

/**
*
*/
class ValidatorException extends \Exception
{

}


text:
import unittest
import os
import sys
if os.environ.get('USELIB') != '1':
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from pyleri import (
    KeywordError,
    create_grammar,
    Sequence,
    Keyword,
)  # nopep8

class TestSequence(unittest.TestCase):

    def test_sequence(self):
        k_hi = Keyword('hi')
        k_iris = Keyword('iris')
        seq = Sequence(k_hi, k_iris)
        grammar = create_grammar(seq)

        self.assertTrue(grammar.parse('hi iris').is_valid)
        self.assertFalse(grammar.parse(' hi sasha ').is_valid)
        self.assertEqual(
            str(grammar.parse('hi sasha')),
            'error at position 3, expecting: iris'
        )

if __name__ == '__main__':
    unittest.main()


text:
using SharpKit.JavaScript;
namespace Ext.layout
{
    #region ClassList
    /// <inheritdocs />
    ///
    ///
This class provides a DOM ClassList API to buffer access to an element's class.
    /// Instances of this class are created by <see cref="Ext.layout.ContextItem.getClassList">Ext.layout.ContextItem.getClassList</see>.

    ///
    [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
    public partial class ClassList : Ext.Base
    {
        ///
        /// Adds a single class to the class list.
        ///
        /// <param name="cls">
        /// </param>
        public void add(object cls){}
        ///
        /// Adds one or more classes in an array or space-delimited string to the class list.
        ///
        /// <param name="classes">
        /// </param>
        public void addMany(object classes){}
        ///
        /// Removes a single class from the class list.
        ///
        /// <param name="cls">
        /// </param>
        public void remove(object cls){}
        ///
        /// Removes one or more classes in an array or space-delimited string from the class
        /// list.
        ///
        /// <param name="classes">
        /// </param>
        public void removeMany(object classes){}
        public ClassList(ClassListConfig config){}
        public ClassList(){}
        public ClassList(params object[] args){}
    }
    #endregion
    #region ClassListConfig
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class ClassListConfig : Ext.BaseConfig
    {
        public ClassListConfig(params object[] args){}
    }
    #endregion
    #region ClassListEvents
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class ClassListEvents : Ext.BaseEvents
    {
        public ClassListEvents(params object[] args){}
    }
    #endregion
}


text:
from helper import CompatTestCase
from validator.compat import TB14_DEFINITION

class TestTB14Compat(CompatTestCase):
    """
    Test that compatibility tests for Thunderbird 14 are properly executed.
    """

    VERSION = TB14_DEFINITION

    def test_interfaces(self):
        for method in self.run_xpcom_for_compat(
                "nsIMsgPluggableStore", ["copyMessages()"]):
            self.assert_silent()
            self.assert_compat_error(type_="notice")

    def test_functions(self):
        patterns = ["mailnews.display.html_sanitizer.allowed_tags", "gPrefs()",
         "gHeaderParser()", "(msgComposeService()", "nsPrefBranch()",
         "(cvHeaderParser",]
        for pattern in patterns:
            self.run_regex_for_compat("var x = %s();" % pattern)
            self.assert_silent()
            assert self.compat_err.notices
            assert self.compat_err.compat_summary["errors"]

        # These patterns should not be flagged.
        for pattern in ["cvsPrefs()", "mailnews()",
                        "CollapseSectionHeaderators()",
                        "msgMailSession", "msgPrefs",]:
            self.run_regex_for_compat("var x = %s();" % pattern, is_js=True)
            self.assert_silent()
            self.assert_compat_silent()


text:
<!DOCTYPE HTML>

<title>HoughTransform</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2022-10-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package algorithms.compGeometry

Class HoughTransform

java.lang.Object

algorithms.compGeometry.HoughTransform

public class HoughTransform
extends java.lang.Object

a class for Hough transforms of simple geometric shapes.  currently a line
 is implemented.

 Helpful in starting this was a look at the code available from
 http://vase.essex.ac.uk/software/HoughTransform/
 and
 http://homepages.inf.ed.ac.uk/rbf/HIPR2/flatjavasrc/Hough.java
 though this implementation is different.

Author:

nichole

Nested Class Summary

Nested Classes

Modifier and Type
Class
Description

class
HoughTransform.HoughTransformLines

Constructor Summary

Constructors

Constructor
Description

HoughTransform()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

java.util.Map<algorithms.util.PairInt,algorithms.util.PairInt>
calculateHoughTransforms(gnu.trove.list.TIntList xCoords,
                        gnu.trove.list.TIntList yCoords,
                        gnu.trove.list.TIntList theta)

java.util.Map<algorithms.util.PairInt,algorithms.util.PairInt>
calculateHoughTransforms(java.util.Set<algorithms.util.PairInt> points,
                        GreyscaleImage theta360)

given the theta values and a set of point coordinates, returns a map
 of the angle and distance from the image origin.

java.util.Map<algorithms.util.PairInt,java.util.Set<algorithms.util.PairInt>>
calculateLineGivenEdge(algorithms.util.PairIntArray edge,
                      int imageWidth,
                      int imageHeight)

given an edge of points, computes the Hough
 transform of lines and returns results as an associate array with
 key = pair with x = polar theta in degrees and y = distance from
 the origin in pixels; value = number of transformation points having
 the key.

protected algorithms.util.PairIntArray
createLine(int len,
          int xOff,
          int yOff)

java.util.List<algorithms.util.PairInt>
sortByVotes(java.util.Map<algorithms.util.PairInt,java.util.Set<algorithms.util.PairInt>> thetaRadiusPixMap)

runtime complexity is O(N * lg_2(N)).

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HoughTransform

public HoughTransform()

Method Detail

calculateLineGivenEdge

public java.util.Map<algorithms.util.PairInt,java.util.Set<algorithms.util.PairInt>> calculateLineGivenEdge(algorithms.util.PairIntArray edge,
                                                                                int imageWidth,
                                                                                int imageHeight)

given an edge of points, computes the Hough
 transform of lines and returns results as an associate array with
 key = pair with x = polar theta in degrees and y = distance from
 the origin in pixels; value = number of transformation points having
 the key.   Note that the angle is calculated for expectations of a
 counter clockwise ordered curve and the vector of the angle is
 perpendicular to p1 (direction given by right hand rule).
 The angles are 0 to 360.

 Note that if the edge has less than 3 points, an empty map is returned.

 runtime complexity is O(N_edge_pts), but includes transcendental operations.

Parameters:

edge - a curve defined by the points within

imageWidth -

imageHeight -

Returns:

thetaRadiusPixCoords mappings

calculateHoughTransforms

public java.util.Map<algorithms.util.PairInt,algorithms.util.PairInt> calculateHoughTransforms(java.util.Set<algorithms.util.PairInt> points,
                                                                                GreyscaleImage theta360)

given the theta values and a set of point coordinates, returns a map
 of the angle and distance from the image origin.

Parameters:

points -

theta360 -

Returns:

calculateHoughTransforms

public java.util.Map<algorithms.util.PairInt,algorithms.util.PairInt> calculateHoughTransforms(gnu.trove.list.TIntList xCoords,
                                                                                gnu.trove.list.TIntList yCoords,
                                                                                gnu.trove.list.TIntList theta)

Parameters:

xCoords -

yCoords -

theta - orientations of xCoords, yCoords in range 0 to 359,
 inclusive.

Returns:

createLine

protected algorithms.util.PairIntArray createLine(int len,
                                                  int xOff,
                                                  int yOff)

sortByVotes

public java.util.List<algorithms.util.PairInt> sortByVotes(java.util.Map<algorithms.util.PairInt,java.util.Set<algorithms.util.PairInt>> thetaRadiusPixMap)

runtime complexity is O(N * lg_2(N)).

Parameters:

thetaRadiusPixMap -

Returns:

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
App.TreeNodeView = Ember.View.extend({
    opened: false,
    //keep track of which uri has children
    hasChildrenList: {},
    fetchingData: false,
    highlighted: false,

    hidden: function() {
        return this.get('content').get('hidden');
    }.property('content.hidden'),

    branch: function() {
        return this.get('content').get('hasChildren');
    }.property('content.hasChildren'),

    node: function() {
        return (this.get('content').get('hasChildren') === false);
    }.property('content.hasChildren'),

    isOpened: function() {
        return (this.get('content').get('opened') === true);
    }.property('content.opened'),

    closed: function() {
        return (this.get('content').get('opened') === false);
    }.property('content.closed'),

    subBranch: undefined,
    fetchedData: false,
    indentLevel: function() {
        return 'indentLevel' + this.get('content').get('level');
    }.property('content.level'),
    tagName: 'div',
    // class names that determine what icons are used beside the node
    classNameBindings: [':medium-padding-bottom', 'hidden', 'indentLevel', 'highlighted:highlight-on'],
    classNames: ['treerow'],
    templateName: 'treenode',
    // Ember had some issues with finding the treenode template when the branch view is dynamically added to
    // the parent collection view in the click event. Had to compile the template here instead

    actions: {
        expand: function() {
            var controller = this.get('controller');
            var contentIndex = controller.get('content').indexOf(this.get('content'));
            var parent = controller.get('content')[contentIndex];
            var me = this;
            this.set('fetchingData', true);
            // the initial treebranch is loaded with data from the controller, sub branches are given data directly
            // hence the need to get the data slightly differently. Sure it's a fudge but.....
            if (parent.get('opened')) {
                // user wants to close the branch
                var index = this.get('parentView').indexOf(this) + 1;
                me.iterateOverChildren(this.get('content'), true);
                this.set('opened', false);
                this.get('content').set('opened', false);
                this.set('fetchingData', false);
            } else if (parent.get('fetchedData')) {
                // user wants to open the branch and we have already created the view before
                var index = this.get('parentView').indexOf(this) + 1;
                me.iterateOverChildren(this.get('content'), false);
                this.set('fetchingData', false);
                this.set('opened', true);
                this.get('content').set('opened', true);
            } else {
                // user wants to open the branch for the first time
                var name, uri;
                var me = this;
                var parent = this.get('content');
                name = this.get('content').get('name');
                uri = this.get('content').get('uri');
                if (this.get('content').get('hasChildren')) {
                    var contentIndex = controller.get('content').indexOf(this.get('content'));
                    var searcher = new TreeSearch(ldaBaseUrl, appID, appKey);
                    var callback = function(success, status, response) {
                        if (success && response) {
                            me.set('fetchingData', false);
                            me.set('opened', true);
			    parent.set('opened', true);
                            var members = searcher.parseChildNodes(response);
                            var membersWithSingleName = [];
                            var allMembers = [];
                            //firstly find all the children
                            $.each(members.children, function(index, member) {
                                var enzyme = me.get('controller').store.createRecord('tree');
                                if (member.uri != null && member.names[0] != null) {
                                    enzyme.set('uri', member.uri);
                                    enzyme.set('name', member.names[0]);
                                    enzyme.set('id', member.uri.split('/').pop());
                                    // assume that all the children have children until clicked unless we have already loaded this one
                                    if (me.get('hasChildrenList')[member.uri] != null && me.get('hasChildrenList')[member.uri] === true) {
                                        enzyme.set('hasChildren', true);
                                    } else if (me.get('hasChildrenList')[member.uri] != null && me.get('hasChildrenList')[member.uri] === false) {
                                        enzyme.set('hasChildren', false);
                                    } else {
                                        enzyme.set('hasChildren', true);
                                    }
                                    enzyme.set('level', parent.get('level') + 1);
                                    allMembers.push(enzyme);
                                }
                            });
                            //then sort them
                            allMembers.sort(function(a, b) {
                                var x = a.get('uri').split('/').pop();
                                var y = b.get('uri').split('/').pop();
                                if (x === y) {
                                    return 0;
                                }
                                return y < x ? -1 : 1;
                            });
                            $.each(allMembers, function(index, member) {
                                controller.get('content').insertAt(contentIndex + 1, member);
                                controller.get('content')[contentIndex].get('children').pushObject(member);
                            });
                        } else {
                            // api sent false (or it broke!)
                            me.set('fetchingData', false);
                            me.get('content').set('hasChildren', false);
                            me.get('hasChildrenList')[uri] = false;
                        }
                    }
                    searcher.getChildNodes(uri, callback);
                }
            }
        }
    },
    iterateOverChildren: function(child, hidden) {
        var me = this;
        child.get('children').forEach(function(innerChild, index) {
            if (innerChild.get('parent').get('opened') == hidden) {
                innerChild.set('hidden', hidden);
                me.iterateOverChildren(innerChild, hidden);
            }
        });
        child.set('opened', hidden);
    }

});


text:
package com.diffplug.gradle.imagegrinder;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A ref which makes it possible to pass references
 * through a serializable roundtrip.  Value can only
 * be read once per ref, across all serialized copies.
 */
public class SerializableRef<T> implements Serializable {
	private static final long serialVersionUID = -5868935924393148402L;

	private final int key;

	private SerializableRef(int key) {
		this.key = key;
	}

	public static <T> SerializableRef<T> create(T value) {
		Objects.requireNonNull(value);
		SerializableRef<T> ref = new SerializableRef<>(count.incrementAndGet());
		valueMap.put(ref.key, new WeakReference<>(value));
		return ref;
	}

	@SuppressWarnings("unchecked")
	@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
	public T value() {
		WeakReference<Object> ref = valueMap.remove(key);
		Objects.requireNonNull(ref, "You can only read the value from a ref once.");
		return (T) Objects.requireNonNull(ref.get(), "Object was gc'ed earlier than we expected");
	}

	private static final AtomicInteger count = new AtomicInteger();
	static final Map<Integer, WeakReference<Object>> valueMap = new ConcurrentHashMap<>();
}


text:
import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { assert, expect } from 'meteor/practicalmeteor:chai';
import { Match } from 'meteor/check';

//import of tested method
import './phonewordPrediction.js';

/**
 * Tests of Meteor method
 */
if (Meteor.isServer) {
    describe('phoneword', () => {
        describe('methods', () => {
            describe('wordPrediction', () => {
                let validQuery = "23";
                let invalidQuery = "0123";
                let invalidQueryWithLetters = "12a";
                let invalidQueryDataType = true;

                it('can transform numbers to words', () => {
                    const method = Meteor.server.method_handlers['phoneword.prediction'];
                    let response = method.apply("", [validQuery, false]);
                    expect(response).to.eql([ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]);
                });

                it('can not transform numbers to words', () => {
                    const method = Meteor.server.method_handlers['phoneword.prediction'];
                    assert.throws(() => method.apply("", [invalidQuery, false]), Meteor.Error, "bad-value");
                });

                it('can not transform letters with numbers to words', () => {
                    const method = Meteor.server.method_handlers['phoneword.prediction'];
                    assert.throws(() => method.apply("", [invalidQueryWithLetters, false]), Meteor.Error, "bad-value");
                });

                it('can not transform other data types to words', () => {
                    const method = Meteor.server.method_handlers['phoneword.prediction'];
                    assert.throws(() => method.apply("", [invalidQueryDataType, false]), Match.Error);
                });
            });
            describe('wordPredictionExistingWords', () => {

                let validQueryExistingWords = "43";

                it('can transform numbers to existing words', () => {
                    const method = Meteor.server.method_handlers['phoneword.prediction'];
                    let response = method.apply("", [validQueryExistingWords, true]);
                    expect(response).to.eql([ 'he', 'id', 'if']);
                });
            });
        });
    });
}


text:
using UnityEngine;
using System.Collections;

namespace BG.ItemSystem
{
    public class ISObject : IISObject
    {

        [SerializeField]
        string _name;
        [SerializeField]
        int _value;
        [SerializeField]
        Sprite _icon;
        [SerializeField]
        ISQuality _quality;

        public string ISName
        {
            get { return _name; }
            set { _name = value; }
        }

        public int ISValue
        {
            get { return _value; }
            set { _value = value; }
        }

        public Sprite ISIcon
        {
            get { return _icon; }
            set { _icon = value; }
        }

        public ISQuality ISQuality
        {
            get { return _quality; }
            set { _quality = value; }
        }
    }
}


text:
html,
body {
/*css for full size background image*/
  background: url(../img/background.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  color: #fff;
  text-align: center;

}

.select2-container .select2-choice, .select2-result-label {
  font-size: 1.5em;
  height: 45px;
  overflow: auto;
}

.top-search {
  margin-top: 90px;
}

.search-field-wrap {
  margin-top: 30px;
}

.search-btn-wrap {
  margin-top: 60px;
}

.icon-padding{
  margin-left: 20px;
}

.footer {
  position: fixed;
  right: 0;
  bottom: 60px;
  left: 0;
  padding: 1rem;
  text-align: left;
}
/* Experiences */
ul.experiences {
    padding-left: 15px;
    margin-top: -1px;
}

ul.experiences li {
    padding-left: 33px;
    margin-bottom: 2.5em;
    list-style: none;
}
/*
ul.experiences li.green {
    background: url('../img/misc/list-bullet-green.png') no-repeat;
}
ul.experiences li.blue {
    background: url('../img/misc/list-bullet-blue.png') no-repeat;
}
ul.experiences li.pink {
    background: url('../img/misc/list-bullet-pink.png') no-repeat;
}*/
.where {
    font-size: 1.2857em; /* 18/16 -> 18px */
    font-weight: 300;
    display: inline;
    margin-right: 0.5em;
}
.what {
    font-size: 0.75em; /* 12/16 -> 12px */
    font-weight: 700;
    text-transform: uppercase;
    color: #fff;
    background-color: #BBBBBB;
    display: inline-block;
    padding: 0 12px;
    margin: -5px 0.5em 0 0 !important;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}
.what.green {
    background-color: #c4df9b;
}
.what.blue {
    background-color: #6dcff6;
}
.what.pink {
    background-color: #f06eaa;
}
.when {
    float: right;
    color: #b9b9b9;
    font-style: italic;
}
.description {
    display: block;
    margin-top: 0.5em;
}

/* BORDERS AND BULLETS */

p {
    /*CSS reset*/
    margin-bottom: 0;
}

ul.experiences li {
    position:relative; /* so that pseudoelements are positioned relatively to their "li"s*/
    /* use padding-bottom instead of margin-bottom.*/
    margin-bottom: 0; /* This overrides previously specified margin-bottom */
    margin-left: 50px;
    padding-bottom: 2.5em;
    text-align: left;
}

ul.experiences li:last-child:after {
    /* bullets */
    content: url('../img/bullet-red.png');

    position: absolute;
    left: -26px; /*adjust manually*/
    top: 0px;
}

ul.experiences li:first-child:after {
    /* bullets */
    content: url('../img/bullet-green.png');
    position: absolute;
    left: -26px; /*adjust manually*/
    top: 0px;
}

ul.experiences li:after {
    /* bullets */
    content: url('../img/bullet-blue.png');
    position: absolute;
    left: -26px; /*adjust manually*/
    top: 0px;
}

ul.experiences li.details:after {
    /* bullets */
    content: url('../img/bullet-details.png');
    position: absolute;
    left: -26px; /*adjust manually*/
    top: 0px;
}

ul.experiences li:before {
    /* lines */
    content:"";
    position: absolute;
    left: -16px; /* adjust manually */
    border-left: 1px solid black;
    height: 100%;
    width: 1px;
}

ul.experiences li:first-child:before {
   /* first li's line */
   top: 6px; /* moves the line down so that it disappears under the bullet. Adjust manually */
}

ul.experiences li:last-child:before {
    /* last li's line */
   height: 6px; /* shorten the line so it goes only up to the bullet. Is equal to first-child:before's top */
}
ul.experiences li:last-child .description {
  display: none;
}
.route{
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    margin-top: 50px;

}

.leftImages {

    display: block;
    float: left;
    margin-top:100px;
    margin-left: 5%;
}

.routeInfo {
     font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
.results {
  height: 100%;
  min-height: 100vh;
  padding-top: 80px;
  background: rgba(255,255,255,.9);
  color: #000;
}
.total {
  margin-bottom: 20px;
}


text:
package com.google.gerrit.acceptance.rest.change;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static com.google.gerrit.extensions.client.ListChangesOption.DETAILED_LABELS;
import static com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.google.common.collect.Iterables;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.extensions.api.changes.AssigneeInput;
import com.google.gerrit.extensions.client.ReviewerState;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException;
import com.google.gerrit.testing.FakeEmailSender.Message;
import com.google.gerrit.testing.TestTimeUtil;
import com.google.inject.Inject;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jgit.transport.RefSpec;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

@NoHttpd
public class AssigneeIT extends AbstractDaemonTest {
  @Inject private RequestScopeOperations requestScopeOperations;

  @BeforeClass
  public static void setTimeForTesting() {
    TestTimeUtil.resetWithClockStep(1, SECONDS);
  }

  @AfterClass
  public static void restoreTime() {
    TestTimeUtil.useSystemTime();
  }

  @Test
  public void getNoAssignee() throws Exception {
    PushOneCommit.Result r = createChange();
    assertThat(getAssignee(r)).isNull();
  }

  @Test
  public void addGetAssignee() throws Exception {
    PushOneCommit.Result r = createChange();
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
    assertThat(getAssignee(r)._accountId).isEqualTo(user.id().get());

    assertThat(sender.getMessages()).hasSize(1);
    Message m = sender.getMessages().get(0);
    assertThat(m.rcpt()).containsExactly(user.getEmailAddress());
  }

  @Test
  public void setNewAssigneeWhenExists() throws Exception {
    PushOneCommit.Result r = createChange();
    setAssignee(r, user.email());
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
  }

  @Test
  public void getPastAssignees() throws Exception {
    PushOneCommit.Result r = createChange();
    setAssignee(r, user.email());
    setAssignee(r, admin.email());
    List<AccountInfo> assignees = getPastAssignees(r);
    assertThat(assignees).hasSize(2);
    Iterator<AccountInfo> itr = assignees.iterator();
    assertThat(itr.next()._accountId).isEqualTo(user.id().get());
    assertThat(itr.next()._accountId).isEqualTo(admin.id().get());
  }

  @Test
  public void assigneeAddedAsReviewer() throws Exception {
    ReviewerState state = ReviewerState.CC;
    PushOneCommit.Result r = createChange();
    Iterable<AccountInfo> reviewers = getReviewers(r, state);
    assertThat(reviewers).isNull();
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
    reviewers = getReviewers(r, state);
    assertThat(reviewers).hasSize(1);
    AccountInfo reviewer = Iterables.getFirst(reviewers, null);
    assertThat(reviewer._accountId).isEqualTo(user.id().get());
  }

  @Test
  public void setAlreadyExistingAssignee() throws Exception {
    PushOneCommit.Result r = createChange();
    setAssignee(r, user.email());
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
  }

  @Test
  public void deleteAssignee() throws Exception {
    PushOneCommit.Result r = createChange();
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
    assertThat(deleteAssignee(r)._accountId).isEqualTo(user.id().get());
    assertThat(getAssignee(r)).isNull();
  }

  @Test
  public void deleteAssigneeWhenNoAssignee() throws Exception {
    PushOneCommit.Result r = createChange();
    assertThat(deleteAssignee(r)).isNull();
  }

  @Test
  public void setAssigneeToInactiveUser() throws Exception {
    PushOneCommit.Result r = createChange();
    gApi.accounts().id(user.id().get()).setActive(false);
    try {
      setAssignee(r, user.email());
      assert_().fail("expected UnresolvableAccountException");
    } catch (UnresolvableAccountException e) {
      assertThat(e)
          .hasMessageThat()
          .isEqualTo(
              "Account '"
                  + user.email()
                  + "' only matches inactive accounts. To use an inactive account, retry with one"
                  + " of the following exact account IDs:\n"
                  + user.id()
                  + ": User <user@example.com>");
    }
  }

  @Test
  public void setAssigneeToInactiveUserById() throws Exception {
    PushOneCommit.Result r = createChange();
    gApi.accounts().id(user.id().get()).setActive(false);
    setAssignee(r, user.id().toString());
    assertThat(getAssignee(r)._accountId).isEqualTo(user.id().get());
  }

  @Test
  public void setAssigneeForNonVisibleChange() throws Exception {
    git().fetch().setRefSpecs(new RefSpec("refs/meta/config:refs/meta/config")).call();
    testRepo.reset(RefNames.REFS_CONFIG);
    PushOneCommit.Result r = createChange("refs/for/refs/meta/config");
    exception.expect(AuthException.class);
    exception.expectMessage("read not permitted");
    setAssignee(r, user.email());
  }

  @Test
  public void setAssigneeNotAllowedWithoutPermission() throws Exception {
    PushOneCommit.Result r = createChange();
    requestScopeOperations.setApiUser(user.id());
    exception.expect(AuthException.class);
    exception.expectMessage("not permitted");
    setAssignee(r, user.email());
  }

  @Test
  public void setAssigneeAllowedWithPermission() throws Exception {
    PushOneCommit.Result r = createChange();
    grant(project, "refs/heads/master", Permission.EDIT_ASSIGNEE, false, REGISTERED_USERS);
    requestScopeOperations.setApiUser(user.id());
    assertThat(setAssignee(r, user.email())._accountId).isEqualTo(user.id().get());
  }

  private AccountInfo getAssignee(PushOneCommit.Result r) throws Exception {
    return gApi.changes().id(r.getChange().getId().get()).getAssignee();
  }

  private List<AccountInfo> getPastAssignees(PushOneCommit.Result r) throws Exception {
    return gApi.changes().id(r.getChange().getId().get()).getPastAssignees();
  }

  private Iterable<AccountInfo> getReviewers(PushOneCommit.Result r, ReviewerState state)
      throws Exception {
    return get(r.getChangeId(), DETAILED_LABELS).reviewers.get(state);
  }

  private AccountInfo setAssignee(PushOneCommit.Result r, String identifieer) throws Exception {
    AssigneeInput input = new AssigneeInput();
    input.assignee = identifieer;
    return gApi.changes().id(r.getChange().getId().get()).setAssignee(input);
  }

  private AccountInfo deleteAssignee(PushOneCommit.Result r) throws Exception {
    return gApi.changes().id(r.getChange().getId().get()).deleteAssignee();
  }
}


text:
from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.hazmat.primitives import hashes

class ObjectIdentifier(object):
    def __init__(self, dotted_string):
        self._dotted_string = dotted_string

    def __eq__(self, other):
        if not isinstance(other, ObjectIdentifier):
            return NotImplemented

        return self.dotted_string == other.dotted_string

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        return "<ObjectIdentifier(oid={0}, name={1})>".format(
            self.dotted_string,
            _OID_NAMES.get(self, "Unknown OID")
        )

    def __hash__(self):
        return hash(self.dotted_string)

    dotted_string = utils.read_only_property("_dotted_string")

class ExtensionOID(object):
    SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9")
    SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14")
    KEY_USAGE = ObjectIdentifier("2.5.29.15")
    SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17")
    ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18")
    BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19")
    NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30")
    CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31")
    CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32")
    POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33")
    AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35")
    POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36")
    EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37")
    FRESHEST_CRL = ObjectIdentifier("2.5.29.46")
    INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54")
    AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1")
    SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11")
    OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5")

class CRLExtensionOID(object):
    CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29")
    CRL_REASON = ObjectIdentifier("2.5.29.21")
    INVALIDITY_DATE = ObjectIdentifier("2.5.29.24")

class NameOID(object):
    COMMON_NAME = ObjectIdentifier("2.5.4.3")
    COUNTRY_NAME = ObjectIdentifier("2.5.4.6")
    LOCALITY_NAME = ObjectIdentifier("2.5.4.7")
    STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8")
    ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10")
    ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11")
    SERIAL_NUMBER = ObjectIdentifier("2.5.4.5")
    SURNAME = ObjectIdentifier("2.5.4.4")
    GIVEN_NAME = ObjectIdentifier("2.5.4.42")
    TITLE = ObjectIdentifier("2.5.4.12")
    GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44")
    DN_QUALIFIER = ObjectIdentifier("2.5.4.46")
    PSEUDONYM = ObjectIdentifier("2.5.4.65")
    DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25")
    EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1")

class SignatureAlgorithmOID(object):
    RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4")
    RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5")
    RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14")
    RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11")
    RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12")
    RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13")
    ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1")
    ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
    ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
    ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
    ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
    DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3")
    DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1")
    DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2")

_SIG_OIDS_TO_HASH = {
    SignatureAlgorithmOID.RSA_WITH_MD5.dotted_string: hashes.MD5(),
    SignatureAlgorithmOID.RSA_WITH_SHA1.dotted_string: hashes.SHA1(),
    SignatureAlgorithmOID.RSA_WITH_SHA224.dotted_string: hashes.SHA224(),
    SignatureAlgorithmOID.RSA_WITH_SHA256.dotted_string: hashes.SHA256(),
    SignatureAlgorithmOID.RSA_WITH_SHA384.dotted_string: hashes.SHA384(),
    SignatureAlgorithmOID.RSA_WITH_SHA512.dotted_string: hashes.SHA512(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA1.dotted_string: hashes.SHA1(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA224.dotted_string: hashes.SHA224(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA256.dotted_string: hashes.SHA256(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA384.dotted_string: hashes.SHA384(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA512.dotted_string: hashes.SHA512(),
    SignatureAlgorithmOID.DSA_WITH_SHA1.dotted_string: hashes.SHA1(),
    SignatureAlgorithmOID.DSA_WITH_SHA224.dotted_string: hashes.SHA224(),
    SignatureAlgorithmOID.DSA_WITH_SHA256.dotted_string: hashes.SHA256()
}

class ExtendedKeyUsageOID(object):
    SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1")
    CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2")
    CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3")
    EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4")
    TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8")
    OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9")

class AuthorityInformationAccessOID(object):
    CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2")
    OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1")

class CertificatePoliciesOID(object):
    CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1")
    CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2")
    ANY_POLICY = ObjectIdentifier("2.5.29.32.0")

_OID_NAMES = {
    NameOID.COMMON_NAME: "commonName",
    NameOID.COUNTRY_NAME: "countryName",
    NameOID.LOCALITY_NAME: "localityName",
    NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName",
    NameOID.ORGANIZATION_NAME: "organizationName",
    NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName",
    NameOID.SERIAL_NUMBER: "serialNumber",
    NameOID.SURNAME: "surname",
    NameOID.GIVEN_NAME: "givenName",
    NameOID.TITLE: "title",
    NameOID.GENERATION_QUALIFIER: "generationQualifier",
    NameOID.DN_QUALIFIER: "dnQualifier",
    NameOID.PSEUDONYM: "pseudonym",
    NameOID.DOMAIN_COMPONENT: "domainComponent",
    NameOID.EMAIL_ADDRESS: "emailAddress",
    SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption",
    SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption",
    SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption",
    SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption",
    SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption",
    SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption",
    SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1",
    SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224",
    SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256",
    SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384",
    SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512",
    SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1",
    SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224",
    SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256",
    ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth",
    ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth",
    ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning",
    ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection",
    ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping",
    ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning",
    ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes",
    ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier",
    ExtensionOID.KEY_USAGE: "keyUsage",
    ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName",
    ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName",
    ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints",
    CRLExtensionOID.CRL_REASON: "cRLReason",
    CRLExtensionOID.INVALIDITY_DATE: "invalidityDate",
    CRLExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer",
    ExtensionOID.NAME_CONSTRAINTS: "nameConstraints",
    ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints",
    ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies",
    ExtensionOID.POLICY_MAPPINGS: "policyMappings",
    ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier",
    ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints",
    ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage",
    ExtensionOID.FRESHEST_CRL: "freshestCRL",
    ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy",
    ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess",
    ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess",
    ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck",
    AuthorityInformationAccessOID.OCSP: "OCSP",
    AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers",
    CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps",
    CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice",
}


text:
<?php
namespace Application\Controller;

use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Interop\Container\Exception\NotFoundException;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;

class AbstractControllerFactory implements AbstractFactoryInterface {

    /**
     * Can the factory create an instance for the service?
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @return bool
     */
    public function canCreate (ContainerInterface $container, $requestedName) {
        try {
            $reflector = new \ReflectionClass($requestedName);
        }
        catch (\ReflectionException $e) {
            return false;
        }

        return preg_match('/Controller$/', $reflector->getName());
    }

    /**
     * Create an object
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @param  null|array $options
     * @return object
     * @throws ServiceNotFoundException if unable to resolve the service.
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service.
     * @throws ContainerException if any other error occurs
     */
    public function __invoke (ContainerInterface $container, $requestedName, array $options = null) {
        $class = new \ReflectionClass($requestedName);

        $interfaces = $class->getInterfaces();

        $controller = new $requestedName();

        foreach ($interfaces as $interface) {
            $namespaceName = $interface->getNamespaceName();
            $interfaceName = $interface->getName();

            // Only care about matching traits
            if (preg_match('/ServiceInterface$/', $namespaceName) && preg_match('/Interface/', $interfaceName)) {
                $hasMatch = preg_match('/([A-Za-z]*)Interface$/', $interfaceName, $matches);

                if (! $hasMatch) {
                    throw new ServiceNotCreatedException('Cannot determine service name from interface. ' . $interfaceName);
                }

                $serviceName = $matches[1];

                try {
                    $setMethod = $class->getMethod('set' . $serviceName);
                }
                catch (\ReflectionException $e) {
                    throw new ServiceNotCreatedException('Interface for service found, but no setter method exists');
                }

                $parameters = $setMethod->getParameters();

                $requestedService = null;

                foreach ($parameters as $parameter) {
                    $requestedService = $parameter->getClass()->getName();
                }

                if (! $requestedService) {
                    throw new ServiceNotCreatedException('Setter for service exists, but setter method does not accept service class.');
                }

                try {
                    $setMethod->invoke($controller, $container->get($requestedService));
                }
                catch (NotFoundException $e) {
                    throw new ServiceNotCreatedException('Could not get a service for ' . $requestedService);
                }
            }
        }

        return $controller;
    }
}


text:
package net.shmin.core.fileupload;

import javax.annotation.Resource;
import java.io.File;

/**
 * Created by benjamin on 16/7/18.
 */
public abstract class AbstractFileUploadService implements IFileUploadService {

    @Resource(name = "uuidFileNameGenerator")
    protected IFileNameGenerator fileNameGenerator;

    @Resource(name = "simpleFolderGenerator")
    protected IFolderGenerator folderGenerator;

    @Override
    public void setFileNameGenerator(IFileNameGenerator fileNameGenerator) {
        this.fileNameGenerator = fileNameGenerator;
    }

    @Override
    public <T> void setFolderGenerator(IFolderGenerator<T> folderGenerator) {
        this.folderGenerator = folderGenerator;
    }

    @Override
    public String upload(String localFilePath) throws Exception {
        File file = new File(localFilePath);
        String fileName;
        if (file.isFile() && file.exists()) {
            fileName = file.getName();
        } else {
            throw new Exception("上传文件失败, 本地文件不是文件或者不存在");
        }
        String generatedFileName = fileNameGenerator.generate(fileName.substring(fileName.indexOf(".") + 1));
        String path = folderGenerator.getServerURL() + "/" + folderGenerator.getBasePath();
        return uploadInternal(localFilePath, path + generatedFileName);
    }

    public abstract String uploadInternal(String local, String remoteFolder);
}