text:
package homebrew

import (
	"bytes"
	"crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"net"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/op/go-logging"
	"github.com/pd0mz/go-dmr"
)

var log = logging.MustGetLogger("dmr/homebrew")

type AuthStatus uint8

func (a *AuthStatus) String() string {
	switch *a {
	case AuthNone:
		return "none"
	case AuthBegin:
		return "begin"
	case AuthDone:
		return "none"
	case AuthFailed:
		return "failed"
	default:
		return "invalid"
	}
}

const (
	AuthNone AuthStatus = iota
	AuthBegin
	AuthDone
	AuthFailed
)

// Messages as documented by DL5DI, G4KLX and DG1HT, see "DMRplus IPSC Protocol for HB repeater (20150726).pdf".
var (
	DMRData         = []byte("DMRD")
	MasterNAK       = []byte("MSTNAK")
	MasterACK       = []byte("MSTACK")
	RepeaterLogin   = []byte("RPTL")
	RepeaterKey     = []byte("RPTK")
	MasterPing      = []byte("MSTPING")
	RepeaterPong    = []byte("RPTPONG")
	MasterClosing   = []byte("MSTCL")
	RepeaterClosing = []byte("RPTCL")
)

// We ping the peers every minute
var (
	AuthTimeout  = time.Second * 5
	PingInterval = time.Second * 5
	PingTimeout  = time.Second * 15
	SendInterval = time.Millisecond * 30
)

// Homebrew is implements the Homebrew IPSC DMR Air Interface protocol
type Homebrew struct {
	Config *RepeaterConfiguration
	Peer   map[string]*Peer
	PeerID map[uint32]*Peer

	pf     dmr.PacketFunc
	conn   *net.UDPConn
	closed bool
	id     []byte
	last   time.Time   // Record last received frame time
	mutex  *sync.Mutex // Mutex for manipulating peer list or send queue
	rxtx   *sync.Mutex // Mutex for when receiving data or sending data
	stop   chan bool
	queue  []*dmr.Packet
}

// New creates a new Homebrew repeater
func New(config *RepeaterConfiguration, addr *net.UDPAddr) (*Homebrew, error) {
	var err error

	if config == nil {
		return nil, errors.New("homebrew: RepeaterConfiguration can't be nil")
	}
	if addr == nil {
		return nil, errors.New("homebrew: addr can't be nil")
	}

	h := &Homebrew{
		Config: config,
		Peer:   make(map[string]*Peer),
		PeerID: make(map[uint32]*Peer),
		id:     packRepeaterID(config.ID),
		mutex:  &sync.Mutex{},
		rxtx:   &sync.Mutex{},
		queue:  make([]*dmr.Packet, 0),
	}
	if h.conn, err = net.ListenUDP("udp", addr); err != nil {
		return nil, errors.New("homebrew: " + err.Error())
	}

	return h, nil
}

func (h *Homebrew) Active() bool {
	return !h.closed && h.conn != nil
}

// Close stops the active listeners
func (h *Homebrew) Close() error {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	if !h.Active() {
		return nil
	}

	log.Info("closing")

	// Tell peers we're closing
closing:
	for _, peer := range h.Peer {
		if peer.Status == AuthDone {
			if err := h.WriteToPeer(append(RepeaterClosing, h.id...), peer); err != nil {
				break closing
			}
		}
	}

	// Kill keepalive goroutine
	if h.stop != nil {
		close(h.stop)
		h.stop = nil
	}

	// Kill listening socket
	h.closed = true
	return h.conn.Close()
}

// Link establishes a new link with a peer
func (h *Homebrew) Link(peer *Peer) error {
	if peer == nil {
		return errors.New("homebrew: peer can't be nil")
	}
	if peer.Addr == nil {
		return errors.New("homebrew: peer Addr can't be nil")
	}
	if peer.AuthKey == nil || len(peer.AuthKey) == 0 {
		return errors.New("homebrew: peer AuthKey can't be nil")
	}

	h.mutex.Lock()
	defer h.mutex.Unlock()

	// Reset state
	peer.Last.PacketSent = time.Time{}
	peer.Last.PacketReceived = time.Time{}
	peer.Last.PingSent = time.Time{}
	peer.Last.PongReceived = time.Time{}

	// Register our peer
	peer.id = packRepeaterID(peer.ID)
	h.Peer[peer.Addr.String()] = peer
	h.PeerID[peer.ID] = peer

	return h.handleAuth(peer)
}

func (h *Homebrew) Unlink(id uint32) error {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	peer, ok := h.PeerID[id]
	if !ok {
		return fmt.Errorf("homebrew: peer %d not linked", id)
	}

	delete(h.Peer, peer.Addr.String())
	delete(h.PeerID, id)
	return nil
}

func (h *Homebrew) ListenAndServe() error {
	var data = make([]byte, 53)

	h.stop = make(chan bool)
	go h.keepalive(h.stop)

	h.closed = false
	for !h.closed {
		n, peer, err := h.conn.ReadFromUDP(data)
		if err != nil {
			return err
		}
		if err := h.handle(peer, data[:n]); err != nil {
			if h.closed && strings.HasSuffix(err.Error(), "use of closed network connection") {
				break
			}
			return err
		}
	}

	log.Info("listener closed")
	return nil
}

// Send a packet to the peers. Will block until the packet is sent.
func (h *Homebrew) Send(p *dmr.Packet) error {
	h.rxtx.Lock()
	defer h.rxtx.Unlock()

	data := BuildData(p, h.Config.ID)
	for _, peer := range h.getPeers() {
		if err := h.WriteToPeer(data, peer); err != nil {
			return err
		}
	}

	return nil
}

func (h *Homebrew) GetPacketFunc() dmr.PacketFunc {
	return h.pf
}

func (h *Homebrew) SetPacketFunc(f dmr.PacketFunc) {
	h.pf = f
}

func (h *Homebrew) WritePacketToPeer(p *dmr.Packet, peer *Peer) error {
	return h.WriteToPeer(h.parsePacket(p), peer)
}

func (h *Homebrew) WriteToPeer(b []byte, peer *Peer) error {
	if peer == nil {
		return errors.New("homebrew: can't write to nil peer")
	}

	peer.Last.PacketSent = time.Now()
	_, err := h.conn.WriteTo(b, peer.Addr)
	return err
}

func (h *Homebrew) WriteToPeerWithID(b []byte, id uint32) error {
	return h.WriteToPeer(b, h.getPeer(id))
}

func (h *Homebrew) checkRepeaterID(id []byte) bool {
	// BrandMeister release 20190421-185653 switched from upper case to lower case hex digits
	return id != nil && bytes.EqualFold(id, h.id)
}

func (h *Homebrew) getPeer(id uint32) *Peer {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	if peer, ok := h.PeerID[id]; ok {
		return peer
	}

	return nil
}

func (h *Homebrew) getPeerByAddr(addr *net.UDPAddr) *Peer {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	if peer, ok := h.Peer[addr.String()]; ok {
		return peer
	}

	return nil
}

func (h *Homebrew) getPeers() []*Peer {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	var peers = make([]*Peer, 0)
	for _, peer := range h.Peer {
		peers = append(peers, peer)
	}

	return peers
}

func (h *Homebrew) handle(remote *net.UDPAddr, data []byte) error {
	peer := h.getPeerByAddr(remote)
	if peer == nil {
		log.Debugf("ignored packet from unknown peer %s\n", remote)
		return nil
	}

	// Ignore packet that are clearly invalid, this is the minimum packet length for any Homebrew protocol frame
	if len(data) < 14 {
		return nil
	}

	if peer.Status != AuthDone {
		// Ignore DMR data at this stage
		if bytes.Equal(data[:4], DMRData) {
			return nil
		}

		if peer.Incoming {
			switch peer.Status {
			case AuthNone:
				switch {
				case bytes.Equal(data[:4], RepeaterLogin):
					if !peer.CheckRepeaterID(data[4:]) {
						log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[4:]))
						return h.WriteToPeer(append(MasterNAK, h.id...), peer)
					}

					// Peer is verified, generate a nonce
					nonce := make([]byte, 4)
					if _, err := rand.Read(nonce); err != nil {
						log.Errorf("peer %d@%s nonce generation failed: %v\n", peer.ID, remote, err)
						return h.WriteToPeer(append(MasterNAK, h.id...), peer)
					}

					peer.UpdateToken(nonce)
					peer.Status = AuthBegin
					return h.WriteToPeer(append(append(MasterACK, h.id...), nonce...), peer)

				default:
					// Ignore unauthenticated repeater, we're not going to reply unless it's
					// an actual login request; if it was indeed a valid repeater and we missed
					// anything, we rely on the remote end to retry to reconnect if it doesn't
					// get an answer in a timely manner.
					break
				}
				break

			case AuthBegin:
				switch {
				case bytes.Equal(data[:4], RepeaterKey):
					if !peer.CheckRepeaterID(data[4:]) {
						log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[4:]))
						return h.WriteToPeer(append(MasterNAK, h.id...), peer)
					}
					if len(data) != 76 {
						peer.Status = AuthNone
						return h.WriteToPeer(append(MasterNAK, h.id...), peer)
					}
					if !bytes.Equal(data[12:], peer.Token) {
						log.Errorf("peer %d@%s sent invalid key challenge token\n", peer.ID, remote)
						peer.Status = AuthNone
						return h.WriteToPeer(append(MasterNAK, h.id...), peer)
					}

					peer.Last.PingSent = time.Now()
					peer.Last.PongReceived = time.Now()
					peer.Status = AuthDone
					return h.WriteToPeer(append(MasterACK, h.id...), peer)
				}
			}
		} else {
			// Verify we have a matching peer ID
			if !h.checkRepeaterID(data[6:14]) {
				log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[6:14]))
				return nil
			}

			switch peer.Status {
			case AuthNone:
				switch {
				case bytes.Equal(data[:6], MasterACK):
					log.Debugf("peer %d@%s sent nonce\n", peer.ID, remote)
					peer.Status = AuthBegin
					peer.UpdateToken(data[14:])
					return h.handleAuth(peer)

				case bytes.Equal(data[:6], MasterNAK):
					log.Errorf("peer %d@%s refused login\n", peer.ID, remote)
					peer.Status = AuthFailed
					if peer.UnlinkOnAuthFailure {
						h.Unlink(peer.ID)
					}
					break

				default:
					log.Warningf("peer %d@%s sent unexpected login reply (ignored)\n", peer.ID, remote)
					break
				}

			case AuthBegin:
				switch {
				case bytes.Equal(data[:6], MasterACK):
					log.Infof("peer %d@%s accepted login\n", peer.ID, remote)
					peer.Status = AuthDone
					peer.Last.PingSent = time.Now()
					peer.Last.PongReceived = time.Now()
					return h.WriteToPeer(h.Config.Bytes(), peer)

				case bytes.Equal(data[:6], MasterNAK):
					log.Errorf("peer %d@%s refused login\n", peer.ID, remote)
					peer.Status = AuthFailed
					if peer.UnlinkOnAuthFailure {
						h.Unlink(peer.ID)
					}
					break

				default:
					log.Warningf("peer %d@%s sent unexpected login reply (ignored)\n", peer.ID, remote)
					break
				}
			}
		}
	} else {
		// Authentication is done
		if peer.Incoming {
			switch {
			case bytes.Equal(data[:4], DMRData):
				p, err := h.parseData(data)
				if err != nil {
					return err
				}
				return h.handlePacket(p, peer)

			case bytes.Equal(data[:6], MasterACK):
				break

			case len(data) == 15 && bytes.Equal(data[:7], MasterPing):
				return h.WriteToPeer(append(RepeaterPong, data[7:]...), peer)

			default:
				log.Warningf("peer %d@%s sent unexpected packet (status=%s):\n", peer.ID, remote, peer.Status.String())
				log.Debug(hex.Dump(data))
				break
			}
		} else {
			switch {
			case bytes.Equal(data[:4], DMRData):
				p, err := h.parseData(data)
				if err != nil {
					return err
				}
				return h.handlePacket(p, peer)

			case bytes.Equal(data[:6], MasterACK):
				if !h.checkRepeaterID(data[6:]) {
					log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[6:14]))
					return nil
				}
				peer.Last.PingSent = time.Now()
				return h.WriteToPeer(append(MasterPing, h.id...), peer)

			case bytes.Equal(data[:6], MasterNAK):
				if !h.checkRepeaterID(data[6:]) {
					log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[6:14]))
					return nil
				}

				log.Errorf("peer %d@%s deauthenticated us; re-authenticating\n", peer.ID, remote)
				peer.Status = AuthNone
				return h.handleAuth(peer)

			case len(data) == 15 && bytes.Equal(data[:7], RepeaterPong):
				if !h.checkRepeaterID(data[7:]) {
					log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[6:14]))
					return nil
				}
				peer.Last.PongReceived = time.Now()
				break

			case len(data) == 10 && bytes.Equal(data[:6], MasterNAK):
				if !h.checkRepeaterID(data[6:]) {
					log.Warningf("peer %d@%s sent invalid repeater ID %q (ignored)\n", peer.ID, remote, string(data[6:14]))
					return nil
				}
				log.Errorf("peer %d@%s sent NAK; re-establishing link\n", peer.ID, remote)
				peer.Status = AuthNone
				return h.handleAuth(peer)

			default:
				log.Warningf("peer %d@%s sent unexpected packet (status=%s):\n", peer.ID, remote, peer.Status.String())
				log.Debug(hex.Dump(data))
				break
			}
		}
	}

	return nil
}

func (h *Homebrew) handleAuth(peer *Peer) error {
	if !peer.Incoming {
		switch peer.Status {
		case AuthNone:
			// Send login packet
			return h.WriteToPeer(append(RepeaterLogin, h.id...), peer)

		case AuthBegin:
			// Send repeater key exchange packet
			return h.WriteToPeer(append(append(RepeaterKey, h.id...), peer.Token...), peer)
		}
	}
	return nil
}

func (h *Homebrew) handlePacket(p *dmr.Packet, peer *Peer) error {
	h.rxtx.Lock()
	defer h.rxtx.Unlock()

	// Record last received time
	h.last = time.Now()

	// Offload packet to handle callback
	if peer.PacketReceived != nil {
		return peer.PacketReceived(h, p)
	}
	if h.pf == nil {
		return errors.New("homebrew: no PacketReceived func defined to handle DMR packet")
	}

	return h.pf(h, p)
}

func (h *Homebrew) keepalive(stop <-chan bool) {
	for {
		select {
		case <-time.After(time.Second):
			now := time.Now()

			for _, peer := range h.getPeers() {
				// Ping protocol only applies to outgoing links, and also the auth retries
				// are entirely up to the peer.
				if peer.Incoming {
					switch peer.Status {
					case AuthDone:
						switch {
						case now.Sub(peer.Last.PingReceived) > PingTimeout:
							peer.Status = AuthNone
							log.Errorf("peer %d@%s not requesting to ping; dropping connection", peer.ID, peer.Addr)
							if err := h.WriteToPeer(append(MasterClosing, h.id...), peer); err != nil {
								log.Errorf("peer %d@%s close failed: %v\n", peer.ID, peer.Addr, err)
							}
							break
						}
						break
					}
				} else {
					switch peer.Status {
					case AuthNone, AuthBegin:
						switch {
						case now.Sub(peer.Last.PacketReceived) > AuthTimeout:
							peer.Status = AuthNone
							log.Errorf("peer %d@%s not responding to login; retrying\n", peer.ID, peer.Addr)
							if err := h.handleAuth(peer); err != nil {
								log.Errorf("peer %d@%s retry failed: %v\n", peer.ID, peer.Addr, err)
							}
							break
						}

					case AuthDone:
						switch {
						case now.Sub(peer.Last.PongReceived) > PingTimeout:
							peer.Status = AuthNone
							log.Errorf("peer %d@%s not responding to ping; trying to re-establish connection", peer.ID, peer.Addr)
							if err := h.WriteToPeer(append(RepeaterClosing, h.id...), peer); err != nil {
								log.Errorf("peer %d@%s close failed: %v\n", peer.ID, peer.Addr, err)
							}
							if err := h.handleAuth(peer); err != nil {
								log.Errorf("peer %d@%s retry failed: %v\n", peer.ID, peer.Addr, err)
							}
							break

						case now.Sub(peer.Last.PingSent) > PingInterval:
							peer.Last.PingSent = now
							if err := h.WriteToPeer(append(MasterPing, h.id...), peer); err != nil {
								log.Errorf("peer %d@%s ping failed: %v\n", peer.ID, peer.Addr, err)
							}
							break
						}
					}
				}
			}

		case <-stop:
			return
		}
	}
}

// parseData converts Homebrew packet format to DMR packet format
func (h *Homebrew) parseData(data []byte) (*dmr.Packet, error) {
	p, err := ParseData(data)
	if err == nil {
		p.RepeaterID = h.Config.ID
	}
	return p, err
}

// parsePacket converts DMR packet format to Homebrew packet format suitable for sending on the wire
func (h *Homebrew) parsePacket(p *dmr.Packet) []byte {
	var d = make([]byte, 53)

	// Signature, 4 bytes, "DMRD"
	copy(d[0:], DMRData)

	// Seq No, 1 byte
	d[4] = p.Sequence

	// Src ID, 3 bytes
	d[5] = uint8((p.SrcID >> 16) & 0xff)
	d[6] = uint8((p.SrcID >> 8) & 0xff)
	d[7] = uint8((p.SrcID & 0xff))

	// Dst ID, 3 bytes
	d[8] = uint8((p.DstID >> 16) & 0xff)
	d[9] = uint8((p.DstID >> 8) & 0xff)
	d[10] = uint8((p.DstID & 0xff))

	// RptrID, 4 bytes
	binary.LittleEndian.PutUint32(d[11:], p.RepeaterID)

	var s byte
	s |= (p.Timeslot & 0x01)      // Slot no, 1 bit
	s |= (p.CallType & 0x01) << 1 // Call Type, 1 bit
	switch p.DataType {           // Frame Type, 2 bits and Data Type or Voice Seq, 4 bits
	case dmr.VoiceBurstA:
		s |= 0x01 << 2 // Voice sync
		s |= (p.DataType - dmr.VoiceBurstA) << 4
	case dmr.VoiceBurstB, dmr.VoiceBurstC, dmr.VoiceBurstD, dmr.VoiceBurstE, dmr.VoiceBurstF:
		s |= 0x00 << 2 // Voice (no-op)
		s |= (p.DataType - dmr.VoiceBurstA) << 4
	default:
		s |= 0x02 << 2 // Data
		s |= p.DataType << 4
	}

	// StreamID, 4 bytes
	binary.BigEndian.PutUint32(d[16:], p.StreamID)

	// DMR Data, 33 bytes
	copy(d[20:], p.Data)
	return d
}

func (h *Homebrew) parseRepeaterID(data []byte) (uint32, error) {
	id, err := strconv.ParseUint(string(data), 16, 32)
	if err != nil {
		return 0, err
	}
	return uint32(id), nil
}

// Interface compliance check
var _ dmr.Repeater = (*Homebrew)(nil)

func packRepeaterID(id uint32) []byte {
	return []byte(fmt.Sprintf("%08X", id))
}

// BuildData converts DMR packet format to Homebrew packet format.
func BuildData(p *dmr.Packet, repeaterID uint32) []byte {
	var data = make([]byte, 53)
	copy(data[:4], DMRData)
	data[4] = p.Sequence
	data[5] = uint8(p.SrcID >> 16)
	data[6] = uint8(p.SrcID >> 8)
	data[7] = uint8(p.SrcID)
	data[8] = uint8(p.DstID >> 16)
	data[9] = uint8(p.DstID >> 8)
	data[10] = uint8(p.DstID)
	data[11] = uint8(repeaterID >> 24)
	data[12] = uint8(repeaterID >> 16)
	data[13] = uint8(repeaterID >> 8)
	data[14] = uint8(repeaterID)
	data[15] = p.Timeslot | (p.CallType << 1)
	data[16] = uint8(p.StreamID >> 24)
	data[17] = uint8(p.StreamID >> 16)
	data[18] = uint8(p.StreamID >> 8)
	data[19] = uint8(p.StreamID)
	copy(data[20:], p.Data)

	switch p.DataType {
	case dmr.VoiceBurstB, dmr.VoiceBurstC, dmr.VoiceBurstD, dmr.VoiceBurstE, dmr.VoiceBurstF:
		data[15] |= (0x00 << 2)
		data[15] |= (p.DataType - dmr.VoiceBurstA) << 4
		break
	case dmr.VoiceBurstA:
		data[15] |= (0x01 << 2)
		break
	default:
		data[15] |= (0x02 << 2)
		data[15] |= (p.DataType) << 4
	}

	return data
}

// ParseData converts Homebrew packet format to DMR packet format.
func ParseData(data []byte) (*dmr.Packet, error) {
	if len(data) != 53 {
		return nil, fmt.Errorf("homebrew: expected 53 data bytes, got %d", len(data))
	}

	var p = &dmr.Packet{
		Sequence:   data[4],
		SrcID:      uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7]),
		DstID:      uint32(data[8])<<16 | uint32(data[9])<<8 | uint32(data[10]),
		RepeaterID: uint32(data[11])<<24 | uint32(data[12])<<16 | uint32(data[13])<<8 | uint32(data[14]),
		Timeslot:   (data[15] >> 0) & 0x01,
		CallType:   (data[15] >> 1) & 0x01,
		StreamID:   uint32(data[16])<<24 | uint32(data[17])<<16 | uint32(data[18])<<8 | uint32(data[19]),
	}
	p.SetData(data[20:])

	switch (data[15] >> 2) & 0x03 {
	case 0x00, 0x01: // voice (B-F), voice sync (A)
		p.DataType = dmr.VoiceBurstA + (data[15] >> 4)
		break
	case 0x02: // data sync
		p.DataType = (data[15] >> 4)
		break
	default: // unknown/unused
		return nil, errors.New("homebrew: unexpected frame type 0b11")
	}

	return p, nil
}


text:
/**
 * @author Wesley Egberto de Brito Objetivo: Teste com a classe DateFormat
 */

package formatador;

import static java.lang.System.out;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

public class DateFormatTest {
	public static void main(String[] args) {
		Calendar c = Calendar.getInstance();

		c.set(Calendar.DAY_OF_MONTH, 21);
		c.set(Calendar.DATE, 21); // Idem ao anterior
		c.set(Calendar.MONTH, 11); // 0 -> Janeiro, ..., 11 -> Dezembro
		c.set(Calendar.YEAR, 2012);

		c.set(Calendar.HOUR, 10); // Hora da manhã ou tarde (12h e am/pm)
		c.set(Calendar.HOUR_OF_DAY, 10); // Hora do dia (24h)
		c.set(Calendar.MINUTE, 45);
		c.set(Calendar.SECOND, 59);
		c.set(Calendar.MILLISECOND, 899);

		Date d = c.getTime();
		DateFormat f = DateFormat.getDateInstance();
		out.println("DateInstance - MEDIUM => " + f.format(d));

		// Usa o formator para a localidade e style default, SHORT (ex.: 21/12/12 10:45 AM)
		f = DateFormat.getInstance();
		out.println("SHORT => " + f.format(d));

		// Usa o formator para a localidade default e o style recebido, MEDIUM (ex.: Dec 21, 2012)
		f = DateFormat.getDateInstance(DateFormat.MEDIUM);
		out.println("MEDIUM => " + f.format(d));

		// Usa o formator para a localidade default e o style recebido, LONG (ex.: 21 de Dezembro de 2012)
		f = DateFormat.getDateInstance(DateFormat.LONG);
		out.println("LONG => " + f.format(d));

		// Usa o formator para a localidade default e o style recebido, FULL (ex.: Sexta-feira, 21 de Dezembro de 2012)
		f = DateFormat.getDateInstance(DateFormat.FULL);
		out.println("FULL => " + f.format(d));

		System.out.println("\nTestes com Locale");
		Locale loc = new Locale("en", "Us"); // Lingua e pais

		// Usa o formatador para o style e a localidade recebida
		f = DateFormat.getDateInstance(DateFormat.LONG, loc);
		out.println("LONG e Locale => " + f.format(d));

		Properties myConfig = System.getProperties();

		String defLang = myConfig.getProperty("user.language");
		String defCountry = myConfig.getProperty("user.country");

		System.out.println("\nUser languange: " + defLang);
		System.out.println("User country: " + defCountry);

		Locale.setDefault(new Locale(defLang, defCountry));

		f = DateFormat.getDateInstance(DateFormat.MEDIUM, loc);
		out.println("MEDIUM LOC => " + f.format(d));

	}

}

redpajama_set_name: RedPajamaGithub


text: Rails.application.config.session_store :cookie_store, key: '_personal-site_session'


text:
var express = require('express'),
    http = require('http'),
    path = require('path'),
    MongoStore = require('connect-mongo')(express),
    pkg = require('./lib/pkg'),
    sys = require('./package.json'),
    errors = require('./lib/error');

var Server = function(params) {

    if (params) {

        var app = express(),
            self = this;

        pkg.set(path.join(__dirname, '/database.json'), params.database);

        // routers
        var index = require('./routes/index'),
            sign = require('./routes/sign'),
            thread = require('./routes/thread'),
            user = require('./routes/user');

        // all environments
        app.set('env', params.env ? params.env : 'development');
        app.set('views', __dirname + '/views');
        app.set('view engine', 'jade');
        app.use(express.favicon());
        app.use(express.logger('dev'));
        app.use(express.bodyParser({
            keepExtensions: true,
            uploadDir: path.join(__dirname, '/public/uploads')
        }));
        app.use(express.methodOverride());
        app.use(express.cookieParser(params.database.name));
        app.use(express.session({
            secret: params.database.name,
            store: new MongoStore({
                db: params.database.name,
                collection: 'sessions'
            })
        }));
        app.use(function(req, res, next) {
            if (!res.locals._app) res.locals._app = self.app;
            next();
        });
        app.use(require('less-middleware')({
            src: __dirname + '/public'
        }));
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(app.router);

        // locals
        app.locals.sys = sys;
        app.locals.site = params;

        // errors
        app.use(errors.logger);
        app.use(errors.xhr);
        app.use(errors.common);

        // home
        app.get('/', sign.passport, index);

        // signin & signout
        app.get('/signin', sign.signin);
        app.get('/signout', sign.signout);

        // thread
        app.get('/submit', sign.check, thread.submit);
        app.post('/thread/new', sign.checkJSON, thread.create);
        app.get('/thread/list', sign.checkJSON, thread.ls);
        app.get('/thread/:id', sign.passport, thread.read);
        app.get('/thread/:id/edit', sign.check, thread.edit);
        app.post('/thread/:id/update', sign.checkJSON, thread.update);
        app.post('/thread/:id/vote', sign.checkJSON, thread.vote);
        app.delete('/thread/:id/remove', sign.checkJSON, thread.remove);

        // user
        app.get('/user/:id', sign.passport, user.read);
        app.post('/user/sync', sign.check, user.sync);
        app.post('/user/:id', user.update);
        app.delete('/user/remove', user.remove);

        // user center
        app.get('/member/:id', sign.passport, user.mime);

        self.app = app;
        self.params = params;

    }

}

Server.prototype.run = function(port) {
    var defaultPort = 3000;
    this.app.set('port', (port && !isNaN(parseInt(port, 10))) ? parseInt(port, 10) : defaultPort);
    this.app.locals.root = (this.app.get('env') === 'production') ? this.params.url : 'http://localhost:' + this.app.get('port');
    http.createServer(this.app).listen(this.app.get('port'));
}

module.exports = Server;


text:
Mif.Tree.implement({

	initSortable: function(sortFunction){
		this.sortable = true;
		this.sortFunction = sortFunction||function(node1, node2){
			if(node1.name > node2.name){
				return 1;
			}else if(node1.name < node2.name){
				return -1;
			}else{
				return 0;
			}
		};
		this.addEvent('loadChildren', function(parent){
			if(parent) parent.sort();
		});
		this.addEvent('structureChange', function(from, to, where, type){
			from.sort();
		});
		return this;
	}

});

Mif.Tree.Node.implement({

	sort: function(sortFunction){
		this.children.sort(sortFunction||this.tree.sortFunction);
		return this;
	}

});


text:
package dao

import (
	"bytes"
	"context"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"time"

	"go-common/library/log"
)

// wechatResp 企业微信的响应
type wechatResp struct {
	Msg    string `json:"msg"`
	Status int    `json:"status"`
}

// WechatMessage 发送企业微信消息
func (d *Dao) WechatMessage(content string) (err error) {
	params := map[string]string{
		"content":   content,
		"timestamp": strconv.FormatInt(time.Now().Unix(), 10),
		"title":     "",
		"token":     d.c.Wechat.Token,
		"type":      "wechat",
		"username":  d.c.Wechat.UserName,
		"url":       "",
	}
	params["signature"] = d.signature(params, d.c.Wechat.Secret)
	b, err := json.Marshal(params)
	if err != nil {
		log.Error("WechatMessage json.Marshal error(%v)", err)
		return
	}
	req, err := http.NewRequest(http.MethodPost, "http://bap.bilibili.co/api/v1/message/add", bytes.NewReader(b))
	if err != nil {
		log.Error("WechatMessage NewRequest error(%v), params(%s)", err, string(b))
		return
	}
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	res := wechatResp{}
	if err = d.httpClient.Do(context.TODO(), req, &res); err != nil {
		log.Error("WechatMessage Do error(%v), params(%s)", err, string(b))
		return
	}
	if res.Status != 0 {
		err = fmt.Errorf("status(%d) msg(%s)", res.Status, res.Msg)
		log.Error("WechatMessage response error(%v), params(%s)", err, string(b))
		return
	}
	return
}

// signature 加密算法
func (d *Dao) signature(params map[string]string, secret string) string {
	// content=xxx&timestamp=xxx格式
	keys := []string{}
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	buf := bytes.Buffer{}
	for _, k := range keys {
		if buf.Len() > 0 {
			buf.WriteByte('&')
		}
		buf.WriteString(url.QueryEscape(k) + "=")
		buf.WriteString(url.QueryEscape(params[k]))
	}
	// 加密
	h := md5.New()
	io.WriteString(h, buf.String()+secret)
	return fmt.Sprintf("%x", h.Sum(nil))
}


text:
/** @jsx React.DOM */

var progressInstance = (
    <ProgressBar>
      <ProgressBar bsStyle="success" now={35} key={1} />
      <ProgressBar bsStyle="warning" now={20} key={2}  />
      <ProgressBar bsStyle="danger" now={10} key={3}  />
    </ProgressBar>
  );

React.renderComponent(progressInstance, mountNode);


text:
require 'rails_helper'
RSpec.describe "TrainNotifier" do
  it "correctly evaluates the returned JSON" do
  end

  it "notifies the correct train if there is a new service outage" do
    j = instance_double("JSONParser")
    allow(j).to receive(:parse) { {"responsecode"=>"0", "timestamp"=>"3/1/2015 11:10:00 AM", "subway"=> {"line"=>[{"name"=>"123", "status"=>"DELAYS", "text"=>{}, "Date"=>{}, "Time"=>{}}]}} }
    t = double('Train', :name => '123', :current_outage => false)
    allow(t).to receive(:set_current_outage=)
    allow(t).to receive(:save)
    notifier = TrainNotifier.new(j)
    notifier.trains << t
    notifier.evaluate!
    expect(t).to have_received(:set_current_outage=).with(true)
  end

  it "notifies the correct train if a service outage has ended" do
    j = instance_double("JSONParser")
    allow(j).to receive(:parse) { {"responsecode"=>"0", "timestamp"=>"3/1/2015 11:10:00 AM", "subway"=> {"line"=>[{"name"=>"123", "status"=>"GOOD SERVICE", "text"=>{}, "Date"=>{}, "Time"=>{}}]}} }
    t = double('Train', :name => '123', :current_outage => true)
    allow(t).to receive(:set_current_outage=)
    allow(t).to receive(:save)
    notifier = TrainNotifier.new(j)
    notifier.trains << t
    notifier.evaluate!
    expect(t).to have_received(:set_current_outage=).with(false)
  end

  it "changes a train's status if specified" do
    t = double('Train', :current_outage => false)
    j = instance_double("JSONParser")
    allow(j).to receive(:parse)
    allow(t).to receive(:set_current_outage=)
    allow(t).to receive(:save)
    notifier = TrainNotifier.new(j).change_train_status(t)
    expect(t).to have_received(:set_current_outage=).with(true)
  end
end


text:
/*
 *  Desenvolvido pela equipe Super-Bits.com CNPJ 20.019.971/0001-90

 */
package com.super_bits.modulosSB.webPaginas.JSFBeans.modal;

import com.super_bits.modulosSB.SBCore.ConfigGeral.SBCore;
import com.super_bits.modulosSB.SBCore.modulos.TratamentoDeErros.FabErro;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

/**
 *
 * @author desenvolvedor
 */
@Named
@ViewScoped
public class PgModalArquivoDeEntidade extends PgModalDados {

    @PostConstruct
    public void inicioArqEntidade() {
        try {

            setCampoSelecionado(getPaginaVinculada().getCampoInstSelecionado());

            if (getCampoSelecionado() == null) {
                throw new UnsupportedOperationException("O campo instanciado selecionado não foi configurado antes de chamar o modal");
            }
        } catch (Throwable t) {
            SBCore.RelatarErro(FabErro.SOLICITAR_REPARO, "Erro obetendo campo instanciado da pagina", t);
        }
    }

}


text:
module Mongoid
  module Association
    module Referenced

      # This module handles the behavior for synchronizing foreign keys between
      # both sides of a many to many associations.
      module Syncable

        # Is the document able to be synced on the inverse side? This is only if
        # the key has changed and the association bindings have not been run.
        #
        # @example Are the foreign keys syncable?
        #   document._syncable?(association)
        #
        # @param [ Association ] association The association metadata.
        #
        # @return [ true, false ] If we can sync.
        #
        # @since 2.1.0
        def _syncable?(association)
          !_synced?(association.foreign_key) && send(association.foreign_key_check)
        end

        # Get the synced foreign keys.
        #
        # @example Get the synced foreign keys.
        #   document._synced
        #
        # @return [ Hash ] The synced foreign keys.
        #
        # @since 2.1.0
        def _synced
          @_synced ||= {}
        end

        # Has the document been synced for the foreign key?
        #
        # @example Has the document been synced?
        #   document._synced?
        #
        # @param [ String ] foreign_key The foreign key.
        #
        # @return [ true, false ] If we can sync.
        #
        # @since 2.1.0
        def _synced?(foreign_key)
          !!_synced[foreign_key]
        end

        # Update the inverse keys on destroy.
        #
        # @example Update the inverse keys.
        #   document.remove_inverse_keys(association)
        #
        # @param [ Association ] association The association.
        #
        # @return [ Object ] The updated values.
        #
        # @since 2.2.1
        def remove_inverse_keys(association)
          foreign_keys = send(association.foreign_key)
          unless foreign_keys.nil? || foreign_keys.empty?
            association.criteria(self, foreign_keys).pull(association.inverse_foreign_key => _id)
          end
        end

        # Update the inverse keys for the association.
        #
        # @example Update the inverse keys
        #   document.update_inverse_keys(association)
        #
        # @param [ Association ] association The document association.
        #
        # @return [ Object ] The updated values.
        #
        # @since 2.1.0
        def update_inverse_keys(association)
          if changes.has_key?(association.foreign_key)
            old, new = changes[association.foreign_key]
            adds, subs = new - (old || []), (old || []) - new

            # If we are autosaving we don't want a duplicate to get added - the
            # $addToSet would run previously and then the $push and $each from the
            # inverse on the autosave would cause this. We delete each id from
            # what's in memory in case a mix of id addition and object addition
            # had occurred.
            if association.autosave?
              send(association.name).in_memory.each do |doc|
                adds.delete_one(doc._id)
              end
            end

            unless adds.empty?
              association.criteria(self, adds).without_options.add_to_set(association.inverse_foreign_key => _id)
            end
            unless subs.empty?
              association.criteria(self, subs).without_options.pull(association.inverse_foreign_key => _id)
            end
          end
        end

        module ClassMethods

          # Set up the syncing of many to many foreign keys.
          #
          # @example Set up the syncing.
          #   Person._synced(association)
          #
          # @param [ Association ] association The association metadata.
          #
          # @since 2.1.0
          def _synced(association)
            unless association.forced_nil_inverse?
              synced_save(association)
              synced_destroy(association)
            end
          end

          private

          # Set up the sync of inverse keys that needs to happen on a save.
          #
          # If the foreign key field has changed and the document is not
          # synced, $addToSet the new ids, $pull the ones no longer in the
          # array from the inverse side.
          #
          # @example Set up the save syncing.
          #   Person.synced_save(association)
          #
          # @param [ Association ] association The association metadata.
          #
          # @return [ Class ] The class getting set up.
          #
          # @since 2.1.0
          def synced_save(association)
            set_callback(
                :save,
                :after,
                if: ->(doc) { doc._syncable?(association) }
            ) do |doc|
              doc.update_inverse_keys(association)
            end
            self
          end

          # Set up the sync of inverse keys that needs to happen on a destroy.
          #
          # @example Set up the destroy syncing.
          #   Person.synced_destroy(association)
          #
          # @param [ Association ] association The association metadata.
          #
          # @return [ Class ] The class getting set up.
          #
          # @since 2.2.1
          def synced_destroy(association)
            set_callback(
                :destroy,
                :after
            ) do |doc|
              doc.remove_inverse_keys(association)
            end
            self
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="#FFFFFF"
        app:itemIconTint="@color/nav_menu_icon_color"
        app:itemTextColor="@color/nav_menu_text_color"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>


text:
<?php declare(strict_types=1);
/**
 * PHP version 7.4
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */

namespace Behat\Ewallet\ManageWallet\TransferFunds;

use Ewallet\Memberships\Member;
use Money\Money;
use PHPUnit\Framework\Assert;

final class TransferFundsResponderHelper
{
    private bool $senderHasEnoughFunds = true;

    public function assertBalanceIs(Money $expectedAmount, Member $forMember): void
    {
        Assert::assertTrue(
            $expectedAmount->equals($forMember->accountBalance()),
            sprintf(
                'Final balance does not match, expecting %.2f, found %.2f',
                $expectedAmount->getAmount() / 100,
                $forMember->accountBalance()->getAmount() / 100
            )
        );
    }

    public function assertSenderDoesNotHaveEnoughFunds(): void
    {
        Assert::assertTrue($this->senderHasEnoughFunds, 'Sender should not have enough funds.');
    }
}


text:
				People

    <button type="button" class="btn btn-primary btn-sm">
      AddPerson
    </button>

          Name
          Phone #
          State
          Action

          {{person.name}}
          {{person.phoneNumber}}
          {{person.state}}


text:
require 'sinatra/base'
require 'haml'

require 'todo/db'
require 'todo/task'

module Todo
  class Application < Sinatra::Base

    use Rack::MethodOverride
    set :haml, escape_html: true

    helpers do
      def options_for_task_status(task)
        Task::STATUS.map { |key, value|
          selected = (value == task.status) ? ' selected' : ''
          %(<option value="#{value}"#{selected}>#{key}</option>)
        }.join
      end

      def error_class(task, name)
        task.errors.has_key?(name) ? 'error' : ''
      end
    end

    configure do
      DB.prepare
    end

    configure :development do
      require 'sinatra/reloader'
      register Sinatra::Reloader
    end

    get '/' do
      redirect '/tasks'
    end

    get '/tasks' do
      @tasks = Task.order('created_at DESC')
      if @status = params[:status]
        case @status
        when 'not_yet'
          @tasks = @tasks.status_is_not_yet
        when 'done'
          @tasks = @tasks.status_is_done
        when 'pending'
          @tasks = @tasks.status_is_pending
        else
          @status = nil
        end
      end

      haml :index
    end

    get '/tasks/new' do
      @task = Task.new

      haml :new
    end

    get '/tasks/:id/edit' do
      @task = Task.find(params[:id])

      haml :edit
    end

    put '/tasks/:id' do
      begin
        task = Task.find(params[:id])
        task.update_attributes!(
          name:    params[:name],
          content: params[:content],
          status:  params[:status],
        )

        redirect '/'
      rescue ActiveRecord::RecordInvalid => e
        @task = e.record

        haml :edit
      end
    end

    post '/tasks' do
      begin
        Task.create!(name: params[:name], content: params[:content])

        redirect '/'
      rescue ActiveRecord::RecordInvalid => e
        @task = e.record

        haml :new
      end
    end

    delete '/tasks/:id' do
      task = Task.find(params[:id])
      task.destroy

      redirect '/'
    end

    not_found do
      haml :not_found
    end

  end
end


text:
CoreDataHelpers
===============


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 7/19/14
 * Time: 2:03 PM
 */

namespace IAS\IntellectualPropertyBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ExecuteGetTradeMarkNameCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('ias:execute.Get.Trade.Mark.Name')
            //->setDescription('Greet someone')
            ->addArgument('limit', InputArgument::REQUIRED, 'Who do you want to greet?')
            ->addArgument('parts', InputArgument::REQUIRED, 'Who do you want to greet?');
            //->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);

        $limit = $input->getArgument('limit');
        $parts = $input->getArgument('parts');

        set_time_limit($limit * 20);

        $partLength = $limit / $parts;

        for ($i = 0; $i < $parts; $i++) {
            $command = sprintf(
                'php /var/www/patents/app/console ias:Get.Trade.Mark.Name %s',
                $partLength
            );

            $output->writeln($command);

            exec($command);
        }

        $time = sprintf (
            '%02s:%02s min for %s trade marks',
            round((microtime(true) - $start)/60),
            round((microtime(true) - $start)%60),
            $limit
        );

        $output->writeln($time);
    }
}


text:
package com.kevin.mirs.enums;

/**
 * 邮件验证状态枚举
 */
public enum EVTypeEnum {
    REG('1', "注册"),
    RESET('2', "找回密码"),
    UNUSUAL_LOGIN('3', "异地登陆")
    ;

    private Character type;
    private String description;

    EVTypeEnum(Character type, String description) {
        this.type = type;
        this.description = description;
    }

    public Character getType() {
        return type;
    }

    public String getDescription() {
        return description;
    }
}


text:
package org.apache.spark.scheduler.cluster.mesos

import java.util.Collections

import scala.collection.JavaConverters._

import org.apache.mesos.Protos._
import org.apache.mesos.Protos.Value.{Range => MesosRange, Ranges, Scalar}
import org.apache.mesos.SchedulerDriver
import org.apache.mesos.protobuf.ByteString
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.{any, eq => meq}
import org.mockito.Mockito.{times, verify}
import org.scalatest.Assertions._

import org.apache.spark.deploy.mesos.config.MesosSecretConfig

object Utils {

  val TEST_FRAMEWORK_ID = FrameworkID.newBuilder()
    .setValue("test-framework-id")
    .build()

  val TEST_MASTER_INFO = MasterInfo.newBuilder()
    .setId("test-master")
    .setIp(0)
    .setPort(0)
    .build()

  def createOffer(
                   offerId: String,
                   agentId: String,
                   mem: Int,
                   cpus: Int,
                   ports: Option[(Long, Long)] = None,
                   gpus: Int = 0,
                   attributes: List[Attribute] = List.empty): Offer = {
    val builder = Offer.newBuilder()
    builder.addResourcesBuilder()
      .setName("mem")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(mem))
    builder.addResourcesBuilder()
      .setName("cpus")
      .setType(Value.Type.SCALAR)
      .setScalar(Scalar.newBuilder().setValue(cpus))
    ports.foreach { resourcePorts =>
      builder.addResourcesBuilder()
        .setName("ports")
        .setType(Value.Type.RANGES)
        .setRanges(Ranges.newBuilder().addRange(MesosRange.newBuilder()
        .setBegin(resourcePorts._1).setEnd(resourcePorts._2).build()))
    }
    if (gpus > 0) {
      builder.addResourcesBuilder()
        .setName("gpus")
        .setType(Value.Type.SCALAR)
        .setScalar(Scalar.newBuilder().setValue(gpus))
    }
    builder.setId(createOfferId(offerId))
      .setFrameworkId(FrameworkID.newBuilder()
      .setValue("f1"))
      .setSlaveId(SlaveID.newBuilder().setValue(agentId))
      .setHostname(s"host${agentId}")
      .addAllAttributes(attributes.asJava)
      .build()
  }

  def verifyTaskLaunched(driver: SchedulerDriver, offerId: String): List[TaskInfo] = {
    val captor = ArgumentCaptor.forClass(classOf[java.util.Collection[TaskInfo]])
    verify(driver, times(1)).launchTasks(
      meq(Collections.singleton(createOfferId(offerId))),
      captor.capture())
    captor.getValue.asScala.toList
  }

  def verifyTaskNotLaunched(driver: SchedulerDriver, offerId: String): Unit = {
    verify(driver, times(0)).launchTasks(
      meq(Collections.singleton(createOfferId(offerId))),
      any(classOf[java.util.Collection[TaskInfo]]))
  }

  def createOfferId(offerId: String): OfferID = {
    OfferID.newBuilder().setValue(offerId).build()
  }

  def createAgentId(agentId: String): SlaveID = {
    SlaveID.newBuilder().setValue(agentId).build()
  }

  def createExecutorId(executorId: String): ExecutorID = {
    ExecutorID.newBuilder().setValue(executorId).build()
  }

  def createTaskId(taskId: String): TaskID = {
    TaskID.newBuilder().setValue(taskId).build()
  }

  def configEnvBasedRefSecrets(secretConfig: MesosSecretConfig): Map[String, String] = {
    val secretName = "/path/to/secret,/anothersecret"
    val envKey = "SECRET_ENV_KEY,PASSWORD"
    Map(
      secretConfig.SECRET_NAMES.key -> secretName,
      secretConfig.SECRET_ENVKEYS.key -> envKey
    )
  }

  def verifyEnvBasedRefSecrets(launchedTasks: List[TaskInfo]): Unit = {
    val envVars = launchedTasks.head
      .getCommand
      .getEnvironment
      .getVariablesList
      .asScala
    assert(envVars.count { x =>
      !x.getName.startsWith("SPARK_") && x.getName != "OMP_NUM_THREADS"
    } == 2) // user-defined secret env vars
    val variableOne = envVars.filter(_.getName == "SECRET_ENV_KEY").head
    assert(variableOne.getSecret.isInitialized)
    assert(variableOne.getSecret.getType == Secret.Type.REFERENCE)
    assert(variableOne.getSecret.getReference.getName == "/path/to/secret")
    assert(variableOne.getType == Environment.Variable.Type.SECRET)
    val variableTwo = envVars.filter(_.getName == "PASSWORD").head
    assert(variableTwo.getSecret.isInitialized)
    assert(variableTwo.getSecret.getType == Secret.Type.REFERENCE)
    assert(variableTwo.getSecret.getReference.getName == "/anothersecret")
    assert(variableTwo.getType == Environment.Variable.Type.SECRET)
  }

  def configEnvBasedValueSecrets(secretConfig: MesosSecretConfig): Map[String, String] = {
    val secretValues = "user,password"
    val envKeys = "USER,PASSWORD"
    Map(
      secretConfig.SECRET_VALUES.key -> secretValues,
      secretConfig.SECRET_ENVKEYS.key -> envKeys
    )
  }

  def verifyEnvBasedValueSecrets(launchedTasks: List[TaskInfo]): Unit = {
    val envVars = launchedTasks.head
      .getCommand
      .getEnvironment
      .getVariablesList
      .asScala
    assert(envVars.count { x =>
      !x.getName.startsWith("SPARK_") && x.getName != "OMP_NUM_THREADS"
    } == 2) // user-defined secret env vars
    val variableOne = envVars.filter(_.getName == "USER").head
    assert(variableOne.getSecret.isInitialized)
    assert(variableOne.getSecret.getType == Secret.Type.VALUE)
    assert(variableOne.getSecret.getValue.getData ==
      ByteString.copyFrom("user".getBytes))
    assert(variableOne.getType == Environment.Variable.Type.SECRET)
    val variableTwo = envVars.filter(_.getName == "PASSWORD").head
    assert(variableTwo.getSecret.isInitialized)
    assert(variableTwo.getSecret.getType == Secret.Type.VALUE)
    assert(variableTwo.getSecret.getValue.getData ==
      ByteString.copyFrom("password".getBytes))
    assert(variableTwo.getType == Environment.Variable.Type.SECRET)
  }

  def configFileBasedRefSecrets(secretConfig: MesosSecretConfig): Map[String, String] = {
    val secretName = "/path/to/secret,/anothersecret"
    val secretPath = "/topsecret,/mypassword"
    Map(
      secretConfig.SECRET_NAMES.key -> secretName,
      secretConfig.SECRET_FILENAMES.key -> secretPath
    )
  }

  def verifyFileBasedRefSecrets(launchedTasks: List[TaskInfo]): Unit = {
    val volumes = launchedTasks.head.getContainer.getVolumesList
    assert(volumes.size() == 2)
    val secretVolOne = volumes.get(0)
    assert(secretVolOne.getContainerPath == "/topsecret")
    assert(secretVolOne.getSource.getSecret.getType == Secret.Type.REFERENCE)
    assert(secretVolOne.getSource.getSecret.getReference.getName == "/path/to/secret")
    val secretVolTwo = volumes.get(1)
    assert(secretVolTwo.getContainerPath == "/mypassword")
    assert(secretVolTwo.getSource.getSecret.getType == Secret.Type.REFERENCE)
    assert(secretVolTwo.getSource.getSecret.getReference.getName == "/anothersecret")
  }

  def configFileBasedValueSecrets(secretConfig: MesosSecretConfig): Map[String, String] = {
    val secretValues = "user,password"
    val secretPath = "/whoami,/mypassword"
    Map(
      secretConfig.SECRET_VALUES.key -> secretValues,
      secretConfig.SECRET_FILENAMES.key -> secretPath
    )
  }

  def verifyFileBasedValueSecrets(launchedTasks: List[TaskInfo]): Unit = {
    val volumes = launchedTasks.head.getContainer.getVolumesList
    assert(volumes.size() == 2)
    val secretVolOne = volumes.get(0)
    assert(secretVolOne.getContainerPath == "/whoami")
    assert(secretVolOne.getSource.getSecret.getType == Secret.Type.VALUE)
    assert(secretVolOne.getSource.getSecret.getValue.getData ==
      ByteString.copyFrom("user".getBytes))
    val secretVolTwo = volumes.get(1)
    assert(secretVolTwo.getContainerPath == "/mypassword")
    assert(secretVolTwo.getSource.getSecret.getType == Secret.Type.VALUE)
    assert(secretVolTwo.getSource.getSecret.getValue.getData ==
      ByteString.copyFrom("password".getBytes))
  }

  def createTextAttribute(name: String, value: String): Attribute = {
    Attribute.newBuilder()
      .setName(name)
      .setType(Value.Type.TEXT)
      .setText(Value.Text.newBuilder().setValue(value))
      .build()
  }
}


text:
"""Wrapper functions for the f5-sdk network config"""

import logging
try:
    from urllib import quote
except ImportError:
    from urllib.parse import quote

LOGGER = logging.getLogger(__name__)

class PartitionNameError(Exception):
    """Exception type for F5 resource name."""

    def __init__(self, msg):
        """Create partition name exception object."""
        Exception.__init__(self, msg)

class IPV4FormatError(Exception):
    """Exception type for improperly formatted IPv4 address."""

    def __init__(self, msg):
        """Create ipv4 format exception object."""
        Exception.__init__(self, msg)

def apply_network_fdb_config(mgmt_root, fdb_config):
    """Apply the network fdb configuration to the BIG-IP.

    Args:
        config: BIG-IP network fdb config dict
    """
    req_vxlan_name = fdb_config['vxlan-name']
    req_fdb_record_endpoint_list = fdb_config['vxlan-node-ips']
    try:
        f5_fdb_record_endpoint_list = _get_fdb_records(mgmt_root,
                                                       req_vxlan_name)

        _log_sequence('req_fdb_record_list', req_fdb_record_endpoint_list)
        _log_sequence('f5_fdb_record_list', f5_fdb_record_endpoint_list)

        # See if the list of records is different.
        # If so, update with new list.
        if _list_diff_exclusive(f5_fdb_record_endpoint_list,
                                req_fdb_record_endpoint_list):
            _fdb_records_update(mgmt_root,
                                req_vxlan_name,
                                req_fdb_record_endpoint_list)
        return 0
    except (PartitionNameError, IPV4FormatError) as e:
        LOGGER.error(e)
        return 0
    except Exception as e:  # pylint: disable=broad-except
        LOGGER.error('Failed to configure the FDB for VxLAN tunnel %s: %s',
                     req_vxlan_name, e)
        return 1

def _get_vxlan_tunnel(mgmt_root, vxlan_name):
    """Get a vxlan tunnel object.

    Args:
        vxlan_name: Name of the vxlan tunnel
    """
    partition, name = _extract_partition_and_name(vxlan_name)
    vxlan_tunnel = mgmt_root.tm.net.fdb.tunnels.tunnel.load(
        partition=partition, name=quote(name))
    return vxlan_tunnel

def _get_fdb_records(mgmt_root, vxlan_name):
    """Get a list of FDB records (just the endpoint list) for the vxlan.

    Args:
        vxlan_name: Name of the vxlan tunnel
    """
    endpoint_list = []
    vxlan_tunnel = _get_vxlan_tunnel(mgmt_root, vxlan_name)
    if hasattr(vxlan_tunnel, 'records'):
        for record in vxlan_tunnel.records:
            endpoint_list.append(record['endpoint'])

    return endpoint_list

def _fdb_records_update(mgmt_root, vxlan_name, endpoint_list):
    """Update the fdb records for a vxlan tunnel.

    Args:
        vxlan_name: Name of the vxlan tunnel
        fdb_record_list: IP address associated with the fdb record
    """
    vxlan_tunnel = _get_vxlan_tunnel(mgmt_root, vxlan_name)
    data = {'records': []}
    records = data['records']
    for endpoint in endpoint_list:
        record = {'name': _ipv4_to_mac(endpoint), 'endpoint': endpoint}
        records.append(record)
    LOGGER.debug("Updating records for vxlan tunnel %s: %s",
                 vxlan_name, data['records'])
    vxlan_tunnel.update(**data)

def _extract_partition_and_name(f5_partition_name):
    """Separate partition and name components for a Big-IP resource."""
    parts = f5_partition_name.split('/')
    count = len(parts)
    if f5_partition_name[0] == '/' and count == 3:
        # leading slash
        partition = parts[1]
        name = parts[2]
    elif f5_partition_name[0] != '/' and count == 2:
        # leading slash missing
        partition = parts[0]
        name = parts[1]
    else:
        raise PartitionNameError('Bad F5 resource name encountered: '
                                 '{}'.format(f5_partition_name))
    return partition, name

def _log_sequence(prefix, sequence_to_log):
    """Helper function to log a sequence.

    Dump a sequence to the logger, skip if it is empty

    Args:
        prefix: The prefix string to describe what's being logged
        sequence_to_log: The sequence being logged
    """
    if sequence_to_log:
        LOGGER.debug(prefix + ': %s', (', '.join(sequence_to_log)))

def _list_diff_exclusive(list1, list2):
    """Return items found only in list1 or list2."""
    return list(set(list1) ^ set(list2))

def _ipv4_to_mac(ip_str):
    """Convert an IPV4 string to a fake MAC address."""
    ip = ip_str.split('.')
    if len(ip) != 4:
        raise IPV4FormatError('Bad IPv4 address format specified for '
                              'FDB record: {}'.format(ip_str))

    return "0a:0a:%02x:%02x:%02x:%02x" % (
        int(ip[0]), int(ip[1]), int(ip[2]), int(ip[3]))


text:
/*
Package gbytes provides a buffer that supports incrementally detecting input.

You use gbytes.Buffer with the gbytes.Say matcher.  When Say finds a match, it fastforwards the buffer's read cursor to the end of that match.

Subsequent matches against the buffer will only operate against data that appears *after* the read cursor.

The read cursor is an opaque implementation detail that you cannot access.  You should use the Say matcher to sift through the buffer.  You can always
access the entire buffer's contents with Contents().

*/
package gbytes

import (
	"errors"
	"fmt"
	"io"
	"regexp"
	"sync"
	"time"
)

/*
gbytes.Buffer implements an io.Writer and can be used with the gbytes.Say matcher.

You should only use a gbytes.Buffer in test code.  It stores all writes in an in-memory buffer - behavior that is inappropriate for production code!
*/
type Buffer struct {
	contents     []byte
	readCursor   uint64
	lock         *sync.Mutex
	detectCloser chan interface{}
	closed       bool
}

/*
NewBuffer returns a new gbytes.Buffer
*/
func NewBuffer() *Buffer {
	return &Buffer{
		lock: &sync.Mutex{},
	}
}

/*
BufferWithBytes returns a new gbytes.Buffer seeded with the passed in bytes
*/
func BufferWithBytes(bytes []byte) *Buffer {
	return &Buffer{
		lock:     &sync.Mutex{},
		contents: bytes,
	}
}

/*
BufferReader returns a new gbytes.Buffer that wraps a reader.  The reader's contents are read into
the Buffer via io.Copy
*/
func BufferReader(reader io.Reader) *Buffer {
	b := &Buffer{
		lock: &sync.Mutex{},
	}

	go func() {
		io.Copy(b, reader)
		b.Close()
	}()

	return b
}

/*
Write implements the io.Writer interface
*/
func (b *Buffer) Write(p []byte) (n int, err error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.closed {
		return 0, errors.New("attempt to write to closed buffer")
	}

	b.contents = append(b.contents, p...)
	return len(p), nil
}

/*
Read implements the io.Reader interface. It advances the
cursor as it reads.
*/
func (b *Buffer) Read(d []byte) (int, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	if uint64(len(b.contents)) <= b.readCursor {
		return 0, io.EOF
	}

	n := copy(d, b.contents[b.readCursor:])
	b.readCursor += uint64(n)

	return n, nil
}

/*
Clear clears out the buffer's contents
*/
func (b *Buffer) Clear() error {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.closed {
		return errors.New("attempt to clear closed buffer")
	}

	b.contents = []byte{}
	b.readCursor = 0
	return nil
}

/*
Close signifies that the buffer will no longer be written to
*/
func (b *Buffer) Close() error {
	b.lock.Lock()
	defer b.lock.Unlock()

	b.closed = true

	return nil
}

/*
Closed returns true if the buffer has been closed
*/
func (b *Buffer) Closed() bool {
	b.lock.Lock()
	defer b.lock.Unlock()

	return b.closed
}

/*
Contents returns all data ever written to the buffer.
*/
func (b *Buffer) Contents() []byte {
	b.lock.Lock()
	defer b.lock.Unlock()

	contents := make([]byte, len(b.contents))
	copy(contents, b.contents)
	return contents
}

/*
Detect takes a regular expression and returns a channel.

The channel will receive true the first time data matching the regular expression is written to the buffer.
The channel is subsequently closed and the buffer's read-cursor is fast-forwarded to just after the matching region.

You typically don't need to use Detect and should use the ghttp.Say matcher instead.  Detect is useful, however, in cases where your code must
be branch and handle different outputs written to the buffer.

For example, consider a buffer hooked up to the stdout of a client library.  You may (or may not, depending on state outside of your control) need to authenticate the client library.

You could do something like:

select {
case <-buffer.Detect("You are not logged in"):
	//log in
case <-buffer.Detect("Success"):
	//carry on
case <-time.After(time.Second):
	//welp
}
buffer.CancelDetects()

You should always call CancelDetects after using Detect.  This will close any channels that have not detected and clean up the goroutines that were spawned to support them.

Finally, you can pass detect a format string followed by variadic arguments.  This will construct the regexp using fmt.Sprintf.
*/
func (b *Buffer) Detect(desired string, args ...interface{}) chan bool {
	formattedRegexp := desired
	if len(args) > 0 {
		formattedRegexp = fmt.Sprintf(desired, args...)
	}
	re := regexp.MustCompile(formattedRegexp)

	b.lock.Lock()
	defer b.lock.Unlock()

	if b.detectCloser == nil {
		b.detectCloser = make(chan interface{})
	}

	closer := b.detectCloser
	response := make(chan bool)
	go func() {
		ticker := time.NewTicker(10 * time.Millisecond)
		defer ticker.Stop()
		defer close(response)
		for {
			select {
			case <-ticker.C:
				b.lock.Lock()
				data, cursor := b.contents[b.readCursor:], b.readCursor
				loc := re.FindIndex(data)
				b.lock.Unlock()

				if loc != nil {
					response <- true
					b.lock.Lock()
					newCursorPosition := cursor + uint64(loc[1])
					if newCursorPosition >= b.readCursor {
						b.readCursor = newCursorPosition
					}
					b.lock.Unlock()
					return
				}
			case <-closer:
				return
			}
		}
	}()

	return response
}

/*
CancelDetects cancels any pending detects and cleans up their goroutines.  You should always call this when you're done with a set of Detect channels.
*/
func (b *Buffer) CancelDetects() {
	b.lock.Lock()
	defer b.lock.Unlock()

	close(b.detectCloser)
	b.detectCloser = nil
}

func (b *Buffer) didSay(re *regexp.Regexp) (bool, []byte) {
	b.lock.Lock()
	defer b.lock.Unlock()

	unreadBytes := b.contents[b.readCursor:]
	copyOfUnreadBytes := make([]byte, len(unreadBytes))
	copy(copyOfUnreadBytes, unreadBytes)

	loc := re.FindIndex(unreadBytes)

	if loc != nil {
		b.readCursor += uint64(loc[1])
		return true, copyOfUnreadBytes
	}
	return false, copyOfUnreadBytes
}


text:
using System.Collections.Generic;
using System.Data.Entity;
using EntityFX.Gdcame.Common.Contract.Counters;
using EntityFX.Gdcame.Common.Contract.Incrementors;
using EntityFX.Gdcame.Common.Contract.Items;
using EntityFX.Gdcame.Common.Contract.UserRating;
using EntityFX.Gdcame.DataAccess.Contract.User;
using EntityFX.Gdcame.DataAccess.Model.Ef;
using EntityFX.Gdcame.DataAccess.Repository.Contract;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.Counters;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.CustomRule;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.FundsDriver;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.User;
using EntityFX.Gdcame.DataAccess.Repository.Contract.Criterions.UserGameSnapshot;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Mappers;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.Counetrs;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.CustomRule;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.FundsDriver;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.User;
using EntityFX.Gdcame.DataAccess.Repository.Ef.Queries.UserGameSnapshot;
using EntityFX.Gdcame.Infrastructure.Common;
using EntityFX.Gdcame.Infrastructure.Repository.EF;
using EntityFX.Gdcame.Infrastructure.Repository.Query;
using EntityFX.Gdcame.Infrastructure.Repository.UnitOfWork;
using Microsoft.Practices.Unity;

namespace EntityFX.Gdcame.DataAccess.Repository.Ef
{
    public class ContainerBootstrapper : IContainerBootstrapper
    {
        public IUnityContainer Configure(IUnityContainer container)
        {
            container.RegisterType<DbContext, EconomicsArcadeDbContext>(
                new InjectionConstructor("name=EconomicsArcadeDbContext"));
            container.RegisterType<IQueryBuilder, QueryBuilder>();
            container.RegisterType<IUnitOfWork, EfUnitOfWork>();
            container.RegisterType<IUnitOfWorkFactory, UnitOfWorkFactory>();

            container.RegisterType<IQuery<GetUserByIdCriterion, UserEntity>, GetUserByIdQuery>();
            container.RegisterType<IQuery<GetUserByNameCriterion, UserEntity>, GetUserByNameQuery>();
            container.RegisterType<IQuery<GetAllUsersCriterion, IEnumerable<UserEntity>>, GetAllUsersQuery>();
            container.RegisterType<IQuery<GetUsersBySearchStringCriterion, IEnumerable<UserEntity>>, GetUsersBySearchStringQuery>();
            container
                .RegisterType
                <IQuery<GetAllFundsDriversCriterion, IEnumerable<FundsDriverEntity>>, GetAllFundsDriversQuery>();
            container.RegisterType<IQuery<GetAllCountersCriterion, IEnumerable<CounterEntity>>, GetAllCountersQuery>();

            container
                .RegisterType<IQuery<GetAllCustomRulesCriterion, IEnumerable<CustomRuleEntity>>, GetAllCustomRuleQuery>();
            container
                .RegisterType
                <IQuery<GetUserGameSnapshotByIdCriterion, UserGameDataSnapshotEntity>, GetUserGameSnapshotByIdQuery>();

            container.RegisterType<IMapper<User, UserEntity>, UserEntityMapper>();
            container.RegisterType<IMapper<UserEntity, User>, UserContractMapper>();
            container.RegisterType<IMapper<FundsDriverEntity, Item>, FundsDriverContractMapper>();
            container.RegisterType<IMapper<IncrementorEntity, Incrementor>, IncrementorContractMapper>();
            container.RegisterType<IMapper<CounterEntity, CounterBase>, CountersContractMapper>();
            container.RegisterType<IMapper<CustomRuleEntity, CustomRule>, CustomRuleContractMapper>();

            container.RegisterType<IUserRepository, UserRepository>();
            container.RegisterType<IItemRepository, ItemRepository>();
            container.RegisterType<ICountersRepository, CountersRepository>();
            container.RegisterType<ICustomRuleRepository, CustomRuleRepository>();
            container.RegisterType<IUserGameSnapshotRepository, UserGameSnapshotRepository>();
            return container;
        }
    }
}


text:
/**
 * Sends new value to the form so that we can submit it.
 *
 * @param {object} props component props
 * @param {number} newValue value to be sent to Form wrapper
 */
export const notify = (props, newValue) => {
  const { name, value, onChange } = props;
  if (typeof onChange === "function") {
    onChange(newValue, {
      name,
      initialValue: value,
      formValue: newValue
    });
  }
};

// We only set the state on change, don't validate or persist yet
export const handleChange = setValue => event => {
  setValue(event.target.value);
};

// On blur, validate what the user typed
export const handleBlur = (props, value, setValue) => () => {
  const { min, max, step } = props;
  const newValue = validate(min, max, value, step);
  persistChange(props, newValue, setValue);
};

export const decrease = (props, value, setValue) => () => {
  const { min, max, step } = props;
  const newValue = validate(min, max, value - step, step);
  persistChange(props, newValue, setValue);
};

export const increase = (props, value, setValue) => () => {
  const { min, max, step } = props;
  const newValue = validate(min, max, value + step, step);
  persistChange(props, newValue, setValue);
};

// Sets state and notifies form wrapper of the change
export const persistChange = (props, value, setValue) => {
  setValue(value);
  notify(props, value);
};

/**
 * Given a number,it checks whether it's smaller or bigger than max & min.
 * It also converts to the closest half step.
 *
 * @param {number} min Minimum value
 * @param {number} max Maximum value
 * @param {number} newValue Number to be validated
 */
export const validate = (min, max, newValue, step) => {
  const value = Number(newValue);

  let cleanValue;
  if (isNaN(value)) {
    cleanValue = 0;
  } else {
    cleanValue = roundValue(value, step);
  }

  if (cleanValue > max) {
    return max;
  }
  if (cleanValue < min) {
    return min;
  }

  return cleanValue;
};

/**
 * Converts a given number to the closest valid value.
 * eg. If step is 0.5 and the user types 0.7, we'll convert to 0.5.
 *
 * @param {number} num Number to be rounded
 * @param {number} step Increment value, accepts any int or float with one decimal.
 */
export const roundValue = (num, step) => {
  // Remove the remainder of the division and round it to nearest decimal
  return Math.round((num - (num % step)) * 10) / 10;
};

// We empty values when users click / tap on the input to make it easier for them (no backspace needed).
export const emptyValue = setValue => () => setValue("");


text:
function [I_sp] = model_interpolation_isp(data)

%% James Pavek, Noel Puldon, Haoyu Li, Jake Harrell, Nick Monahan, Aaron McCusker
%% ASEN2004 - Lab 2 - Simulated Bottle Rocket
%% Interpolation Model Function

%% Purpose: To use static test data to calculate Isp

%{
| Inputs      | Units | Description           |
|-------------+-------+-----------------------|
| filename    | N/A   | Static test data file |

| Outputs | Units | Description              |
|---------+-------+--------------------------|
| isp     | s     | Rocket thrust efficiency |
%}

    global pressure_ambient density_water volume_bottle discharge_coeff pressure_absolute gravity drag_coeff gas_constant volume_initial mass_air_initial pressure_end bottle_area throat_area temperature_initial density_air velocity_wind mass_rocket_initial pressure_absolute launch_angle launch_rail_length mass_water_initial test_data sample_freq

    sample_t = 1/(sample_freq); % sample interval [s]

    % identify thrust phase of sample data
    count = length(data);
    x_axis = 1:count;

    % determine specific impulse of adjusted data using numerical integration
    x_sp = linspace(0,(count*sample_t),count);
    I_sp = abs(trapz(x_sp,data)./(gravity*mass_water_initial)); % [s]

end


text:
<?php

namespace craft\migrations;

use Craft;
use craft\db\Migration;
use craft\db\Query;
use craft\elements\Asset;
use craft\helpers\Assets as AssetsHelper;
use craft\helpers\Db;
use craft\helpers\ElementHelper;
use craft\helpers\FileHelper;
use craft\helpers\Image;
use craft\helpers\Json;
use craft\volumes\Local;
use yii\base\Exception;

/**
 * m160804_110002_userphotos_to_assets migration.
 */
class m160804_110002_userphotos_to_assets extends Migration
{
    /**
     * @var string|null
     */
    private $_basePath;

    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->_basePath = Craft::$app->getPath()->getStoragePath().DIRECTORY_SEPARATOR.'userphotos';

        // Make sure the userphotos folder actually exists
        FileHelper::createDirectory($this->_basePath);

        echo "    > Removing __default__ folder\n";
        FileHelper::removeDirectory($this->_basePath.DIRECTORY_SEPARATOR.'__default__');

        echo "    > Changing the relative path from username/original.ext to original.ext\n";
        $affectedUsers = $this->_moveUserphotos();

        echo "    > Creating a private Volume as default for Users\n";
        $volumeId = $this->_createUserphotoVolume();

        echo "    > Setting the Volume as the default one for userphoto uploads\n";
        $this->_setUserphotoVolume($volumeId);

        echo "    > Converting photos to Assets\n";
        $affectedUsers = $this->_convertPhotosToAssets($volumeId, $affectedUsers);

        echo "    > Updating Users table to drop the photo column and add photoId column.\n";
        $this->dropColumn('{{%users}}', 'photo');
        $this->addColumn('{{%users}}', 'photoId', $this->integer()->after('username')->null());
        $this->addForeignKey(null, '{{%users}}', ['photoId'], '{{%assets}}', ['id'], 'SET NULL', null);

        echo "    > Setting the photoId value\n";
        $this->_setPhotoIdValues($affectedUsers);

        echo "    > Removing all the subfolders.\n";
        $this->_removeSubdirectories();

        return true;
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        echo "m160804_110002_userphotos_to_assets cannot be reverted.\n";

        return false;
    }

    // Private methods
    // =========================================================================

    /**
     * Move user photos from subfolders to root.
     *
     * @return array
     * @throws Exception in case of failure
     */
    private function _moveUserphotos(): array
    {
        $handle = opendir($this->_basePath);
        if ($handle === false) {
            throw new Exception("Unable to open directory: {$this->_basePath}");
        }

        $affectedUsers = [];

        // Grab the users with photos
        while (($subDir = readdir($handle)) !== false) {
            if ($subDir === '.' || $subDir === '..') {
                continue;
            }
            $path = $this->_basePath.DIRECTORY_SEPARATOR.$subDir;
            if (is_file($path)) {
                continue;
            }

            $user = (new Query())
                ->select(['id', 'photo'])
                ->from(['{{%users}}'])
                ->where(['username' => $subDir])
                ->one($this->db);

            // Make sure the user still exists and has a photo
            if (!$user || empty($user['photo'])) {
                continue;
            }

            // Make sure the original file still exists
            $sourcePath = $this->_basePath.DIRECTORY_SEPARATOR.$subDir.DIRECTORY_SEPARATOR.'original'.DIRECTORY_SEPARATOR.$user['photo'];
            if (!is_file($sourcePath)) {
                continue;
            }

            // Make sure that the filename is unique
            $counter = 0;

            $baseFilename = pathinfo($user['photo'], PATHINFO_FILENAME);
            $extension = pathinfo($user['photo'], PATHINFO_EXTENSION);
            $filename = $baseFilename.'.'.$extension;

            while (is_file($this->_basePath.DIRECTORY_SEPARATOR.$filename)) {
                $filename = $baseFilename.'_'.++$counter.'.'.$extension;
            }

            // In case the filename changed
            $user['photo'] = $filename;

            // Store for reference
            $affectedUsers[] = $user;

            $targetPath = $this->_basePath.DIRECTORY_SEPARATOR.$filename;

            // Move the file to the new location
            rename($sourcePath, $targetPath);
        }

        return $affectedUsers;
    }

    /**
     * Create the user photo volume.
     *
     * @return int volume id
     */
    private function _createUserphotoVolume(): int
    {
        // Safety first!
        $handle = 'userPhotos';
        $name = 'User Photos';

        $counter = 0;

        $existingVolume = (new Query())
            ->select(['id'])
            ->from(['{{%volumes}}'])
            ->where(['handle' => $handle])
            ->one($this->db);

        while ($existingVolume !== null) {
            $handle = 'userPhotos'.++$counter;
            $name = 'User Photos '.$counter;
            $existingVolume = (new Query())
                ->select(['id'])
                ->from(['{{%volumes}}'])
                ->where([
                    'or',
                    ['handle' => $handle],
                    ['name' => $name]
                ])
                ->one($this->db);
        }

        // Set the sort order
        $maxSortOrder = (new Query())
            ->from(['{{%volumes}}'])
            ->max('[[sortOrder]]', $this->db);

        $volumeData = [
            'type' => Local::class,
            'name' => $name,
            'handle' => $handle,
            'hasUrls' => false,
            'url' => null,
            'settings' => Json::encode(['path' => '@storage/userphotos']),
            'fieldLayoutId' => null,
            'sortOrder' => $maxSortOrder + 1
        ];

        $db = Craft::$app->getDb();
        $db->createCommand()
            ->insert('{{%volumes}}', $volumeData)
            ->execute();

        $volumeId = $db->getLastInsertID();

        $folderData = [
            'parentId' => null,
            'volumeId' => $volumeId,
            'name' => $name,
            'path' => null
        ];
        $db->createCommand()
            ->insert('{{%volumefolders}}', $folderData)
            ->execute();

        return $volumeId;
    }

    /**
     * Set the photo volume setting for users.
     *
     * @param int $volumeId
     */
    private function _setUserphotoVolume(int $volumeId)
    {
        $systemSettings = Craft::$app->getSystemSettings();
        $settings = $systemSettings->getSettings('users');
        $settings['photoVolumeId'] = $volumeId;
        $systemSettings->saveSettings('users', $settings);
    }

    /**
     * Convert matching user photos to Assets in a Volume and add that information
     * to the array passed in.
     *
     * @param int $volumeId
     * @param array $userList
     * @return array $userList
     */
    private function _convertPhotosToAssets(int $volumeId, array $userList): array
    {
        $db = Craft::$app->getDb();

        $locales = (new Query())
            ->select(['locale'])
            ->from(['{{%locales}}'])
            ->column($this->db);

        $folderId = (new Query())
            ->select(['id'])
            ->from(['{{%volumefolders}}'])
            ->where([
                'parentId' => null,
                'volumeId' => $volumeId
            ])
            ->scalar($this->db);

        $changes = [];

        foreach ($userList as $user) {
            $filePath = $this->_basePath.DIRECTORY_SEPARATOR.$user['photo'];

            $assetExists = (new Query())
                ->select(['assets.id'])
                ->from(['{{%assets}} assets'])
                ->innerJoin('{{%volumefolders}} volumefolders', '[[volumefolders.id]] = [[assets.folderId]]')
                ->where([
                    'assets.folderId' => $folderId,
                    'filename' => $user['photo']
                ])
                ->exists($this->db);

            if (!$assetExists && is_file($filePath)) {
                $elementData = [
                    'type' => Asset::class,
                    'enabled' => 1,
                    'archived' => 0
                ];
                $db->createCommand()
                    ->insert('{{%elements}}', $elementData)
                    ->execute();

                $elementId = $db->getLastInsertID();

                foreach ($locales as $locale) {
                    $elementI18nData = [
                        'elementId' => $elementId,
                        'locale' => $locale,
                        'slug' => ElementHelper::createSlug($user['photo']),
                        'uri' => null,
                        'enabled' => 1
                    ];
                    $db->createCommand()
                        ->insert('{{%elements_i18n}}', $elementI18nData)
                        ->execute();

                    $contentData = [
                        'elementId' => $elementId,
                        'locale' => $locale,
                        'title' => AssetsHelper::filename2Title(pathinfo($user['photo'], PATHINFO_FILENAME))
                    ];
                    $db->createCommand()
                        ->insert('{{%content}}', $contentData)
                        ->execute();
                }

                $imageSize = Image::imageSize($filePath);
                $assetData = [
                    'id' => $elementId,
                    'volumeId' => $volumeId,
                    'folderId' => $folderId,
                    'filename' => $user['photo'],
                    'kind' => Asset::KIND_IMAGE,
                    'size' => filesize($filePath),
                    'width' => $imageSize[0],
                    'height' => $imageSize[1],
                    'dateModified' => Db::prepareDateForDb(filemtime($filePath))
                ];
                $db->createCommand()
                    ->insert('{{%assets}}', $assetData)
                    ->execute();

                $changes[$user['id']] = $elementId;
            }
        }

        return $changes;
    }

    /**
     * Set photo ID values for the user array passed in.
     *
     * @param array $userlist userId => assetId
     */
    private function _setPhotoIdValues(array $userlist)
    {
        if (is_array($userlist)) {
            $db = Craft::$app->getDb();
            foreach ($userlist as $userId => $assetId) {
                $db->createCommand()
                    ->update('{{%users}}', ['photoId' => $assetId], ['id' => $userId])
                    ->execute();
            }
        }
    }

    /**
     * Remove all the subdirectories in the userphotos folder.
     */
    private function _removeSubdirectories()
    {
        $subDirs = glob($this->_basePath.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);

        foreach ($subDirs as $dir) {
            FileHelper::removeDirectory($dir);
        }
    }
}


text:
TEST_CASE("memento client", "[client]") {
        client();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpTestFrameworkVersionCache">
    <tools_cache>
      <tool tool_name="PHPUnit">
        <cache>
          <versions>
            <info id="Local" version="6.4.2" />
          </versions>
        </cache>
      </tool>
    </tools_cache>
  </component>
</project>


text:
This library was generated with [Nx](https://nx.dev).

## Building

Run `nx build e2e-schematics` to build the library.

## Running unit tests

Run `nx test e2e-schematics` to execute the unit tests via [Jest](https://jestjs.io).


text:
package coyote.commons;

import static org.junit.Assert.assertNotNull;

import java.util.Date;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 */
public class DateUtilTest {

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {}

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {}

  @Test
  public void test() {

    Date date = DateUtil.parse( "2017-06-16T13:32:19.504-04" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16T13:32:19.504" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16T13:32:19" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16T13:32:19" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16 13:32:19.504-04" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16 13:32:19.504" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16 13:32:19" );
    assertNotNull( date );

    date = DateUtil.parse( "2017-06-16" );
    assertNotNull( date );

    String text = date.toString();
    date = DateUtil.parse( text );
    assertNotNull( date );

  }

}


text:
XBL_API XSAPI_RESULT XBL_CALLING_CONV
XBLGlobalInitialize() XSAPI_NOEXCEPT
try
{
    auto singleton = get_xsapi_singleton(true);
    auto hcr = HCGlobalInitialize();
    if (hcr != HC_OK)
    {
        return utils::xsapi_result_from_hc_result(hcr);
    }
    singleton->m_threadPool->start_threads();

    return XSAPI_OK;
}
CATCH_RETURN()

XBL_API void XBL_CALLING_CONV
XBLGlobalCleanup() XSAPI_NOEXCEPT
try
{
    cleanup_xsapi_singleton();
    HCGlobalCleanup();
}
CATCH_RETURN_WITH(;)


text:
<?php

namespace Omnipay\Stripe\Message;

use Omnipay\TestCase;

class AuthorizeRequestTest extends TestCase
{
    public function setUp()
    {
        $this->request = new AuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->request->initialize(
            array(
                'amount' => 1200,
                'currency' => 'USD',
                'card' => $this->getValidCard(),
            )
        );
    }

    public function testCaptureIsFalse()
    {
        $data = $this->request->getData();
        $this->assertSame('false', $data['capture']);
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     * @expectedExceptionMessage The card parameter is required
     */
    public function testCardRequired()
    {
        $this->request->setCard(null);
        $this->request->getData();
    }

    public function testDataWithCardReference()
    {
        $this->request->setCardReference('xyz');
        $data = $this->request->getData();

        $this->assertSame('xyz', $data['customer']);
    }

    public function testDataWithToken()
    {
        $this->request->setToken('xyz');
        $data = $this->request->getData();

        $this->assertSame('xyz', $data['card']);
    }

    public function testDataWithCard()
    {
        $card = $this->getValidCard();
        $this->request->setCard($card);
        $data = $this->request->getData();

        $this->assertSame($card['number'], $data['card']['number']);
    }

    public function testSendSuccess()
    {
        $this->setMockHttpResponse('PurchaseSuccess.txt');
        $response = $this->request->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertSame('ch_1IU9gcUiNASROd', $response->getTransactionReference());
        $this->assertNull($response->getCardReference());
        $this->assertNull($response->getMessage());
    }

    public function testSendError()
    {
        $this->setMockHttpResponse('PurchaseFailure.txt');
        $response = $this->request->send();

        $this->assertFalse($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertNull($response->getTransactionReference());
        $this->assertNull($response->getCardReference());
        $this->assertSame('Your card was declined', $response->getMessage());
    }
}


text:
class SessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    session[:access_token] = auth["credentials"]["token"]
    redirect_to root_url
  end

  def destroy
    session[:user_id] = nil
    session[:access_token] = nil
    redirect_to root_url
  end
end


text:
namespace media {

class AudioRendererMixer;

class MEDIA_EXPORT AudioRendererMixerInput
    : NON_EXPORTED_BASE(public AudioRendererSink),
      public AudioConverter::InputCallback {
 public:
  typedef base::Callback<AudioRendererMixer*(
      const AudioParameters& params)> GetMixerCB;
  typedef base::Callback<void(const AudioParameters& params)> RemoveMixerCB;

  AudioRendererMixerInput(
      const GetMixerCB& get_mixer_cb, const RemoveMixerCB& remove_mixer_cb);

  // AudioRendererSink implementation.
  virtual void Start() OVERRIDE;
  virtual void Stop() OVERRIDE;
  virtual void Play() OVERRIDE;
  virtual void Pause(bool flush) OVERRIDE;
  virtual bool SetVolume(double volume) OVERRIDE;
  virtual void Initialize(const AudioParameters& params,
                          AudioRendererSink::RenderCallback* renderer) OVERRIDE;

  // Called by AudioRendererMixer when new delay information is available.
  void set_audio_delay_milliseconds(int audio_delay_milliseconds) {
    current_audio_delay_milliseconds_ = audio_delay_milliseconds;
  }

  // Called by AudioRendererMixer when an error occurs.
  void OnRenderError();

 protected:
  virtual ~AudioRendererMixerInput();

 private:
  friend class AudioRendererMixerInputTest;

  bool playing_;
  bool initialized_;
  bool started_;
  double volume_;

  // AudioConverter::InputCallback implementation.
  virtual double ProvideInput(AudioBus* audio_bus,
                              base::TimeDelta buffer_delay) OVERRIDE;

  // Callbacks provided during construction which allow AudioRendererMixerInput
  // to retrieve a mixer during Initialize() and notify when it's done with it.
  GetMixerCB get_mixer_cb_;
  RemoveMixerCB remove_mixer_cb_;

  // AudioParameters received during Initialize().
  AudioParameters params_;

  // AudioRendererMixer provided through |get_mixer_cb_| during Initialize(),
  // guaranteed to live (at least) until |remove_mixer_cb_| is called.
  AudioRendererMixer* mixer_;

  // Source of audio data which is provided to the mixer.
  AudioRendererSink::RenderCallback* callback_;

  // The current audio delay as last provided by AudioRendererMixer.
  int current_audio_delay_milliseconds_;

  DISALLOW_COPY_AND_ASSIGN(AudioRendererMixerInput);
};

}  // namespace media

#endif  // MEDIA_BASE_AUDIO_RENDERER_MIXER_INPUT_H_


text:
<?php

namespace Drupal\workbench_moderation;

use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;

/**
 * Provides a listing of Moderation state entities.
 */
class ModerationStateListBuilder extends ConfigEntityListBuilder {
  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = $this->t('Moderation state');
    $header['id'] = $this->t('Machine name');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $entity->label();
    $row['id'] = $entity->id();
    // You probably want a few more properties here...
    return $row + parent::buildRow($entity);
  }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

-->

<gateway-config xmlns="http://xmlns.kaazing.org/2014/09/gateway">

    <properties>
        <property>
            <name>gateway.hostname</name>
            <value>localhost</value>
        </property>
        <property>
            <name>gateway.base.port</name>
            <value>8000</value>
        </property>
        <property>
            <name>gateway.extras.port</name>
            <value>8001</value>
        </property>
    </properties>

    <service>
        <name>proxy</name>
        <accept>wss://localhost:8000/freenodeProxy</accept>
        <connect>wss://localhost:9000/freenode</connect>

        <type>proxy</type>

        <connect-options>
            <ssl.ciphers>HIGH</ssl.ciphers>
        </connect-options>
    </service>

    <!-- Security configuration -->
    <security>
        <!--
        The keystore element is used to configure the keystore that contains
        encryption keys for secure communications with Kaazing WebSocket Gateway.
        -->
        <keystore>
            <type>JCEKS</type>
            <file>keystore.db</file>
            <password-file>keystore.pw</password-file>
        </keystore>

        <!--
        The truststore element is used to configure the truststore that
        contains digital certificates for certificate authorities
        trusted by Kaazing WebSocket Gateway.
        -->
        <truststore>
            <file>truststore.db</file>
        </truststore>
    </security>
</gateway-config>


text:
using HisFeldLibrary.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace HisFeldLibrary.Model
{
    [DataContract]
    public class TaskBook : ModelBase
    {
        public TaskBook()
        {
            taskCollection = new ObservableCollection<Task>();
            taskCollection.CollectionChanged += taskCollection_CollectionChanged;
            FinishedFromSerialization = true;
        }

        public override void ReHookEvents()
        {
            taskCollection.CollectionChanged += taskCollection_CollectionChanged;

            foreach (Task inTask in taskCollection)
            {
                inTask.ReHookEvents();
            }
        }

        void taskCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RaisePropertyChanged("TaskCollection");
        }

        public bool FinishedFromSerialization = false;

        [DataMember]
        private ObservableCollection<Task> taskCollection;

        public ObservableCollection<Task> TaskCollection
        {
            get { return taskCollection; }
            set
            {
                taskCollection = value;
                RaisePropertyChanged("TaskCollection");
            }
        }

        private Task selectedTask;

        public Task SelectedTask
        {
            get { return selectedTask; }
            set
            {
                if (selectedTask != null)
                {
                    selectedTask.PropertyChanged -= selectedTask_PropertyChanged;
                }
                selectedTask = value;

                if (selectedTask != null)
                {
                    selectedTask.PropertyChanged += selectedTask_PropertyChanged;
                }

                RaisePropertyChanged("SelectedTask");
            }
        }

        void selectedTask_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            RaisePropertyChanged("SelectedTask");
        }

    }
}


text:
import sys
import os
from pathlib import Path

# set settings for django to work
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cavstudio_backend.settings")

# ensure that cavstudio_backend can be imported
BACKEND_DIR = Path(__file__).resolve().parent.parent
sys.path.append(str(BACKEND_DIR))

import django
from django.apps import apps as django_apps
import tempfile
from urllib.request import urlretrieve
from urllib.parse import urlparse
import shutil
import json
from tqdm import tqdm
import textwrap
from cavstudio_backend.image_reference import precalculate_activations, ImageReference
from django.core.management import call_command as django_call_command

FEATURE_CONCEPTS_URL = 'https://services.google.com/fh/files/misc/featured_concepts_v2.zip'
SCOUT_IMAGES_URL = 'https://services.google.com/fh/files/misc/cavstudio_image_bank_sample_set_v2.zip'

STATIC_CAV_CONTENT_DIR = BACKEND_DIR / 'static-cav-content'

def main():
    print(textwrap.dedent('''
        ##########################
        # CAVstudio setup script #
        ##########################

        This script will download and prepare all the data required to use
        CAVstudio. This comprises the image bank, which provides a dataset for
        your concepts to search, and our featured concepts.

        It will download ~1.1GB of data, and then will preprocess the images
        to create activations. The whole process should take around 10-15
        minutes.

        Please note: the images inside the featured concepts are made publicly
        available for use in CAVstudio only. Copyright is retained by the
        owners of these images.

        Press 'y' followed by 'Enter' to continue.
    '''))

    answer = input('Continue [y/N]: ')

    if answer not in ['Y', 'y']:
        sys.exit('Aborted.')

    with tempfile.TemporaryDirectory() as tmpdirname:
        temp_dir = Path(tmpdirname)

        print('------> 1/8 Downloading featured concept archive...')
        concept_archive_filename = os.path.basename(urlparse(FEATURE_CONCEPTS_URL).path)
        concept_archive = temp_dir / concept_archive_filename
        download_file(FEATURE_CONCEPTS_URL, destination=concept_archive)

        print('------> 2/8 Unpacking concept archive...')
        concept_archive_dir = temp_dir / 'featured_concepts'
        concept_archive_dir.mkdir()
        shutil.unpack_archive(concept_archive, extract_dir=concept_archive_dir)

        print('------> 3/8 Downloading image bank archive...')
        scout_archive_filename = os.path.basename(urlparse(SCOUT_IMAGES_URL).path)
        scout_archive = temp_dir / scout_archive_filename
        download_file(SCOUT_IMAGES_URL, destination=scout_archive)

        print('------> 4/8 Unpacking image bank archive...')
        scout_archive_dir = temp_dir / 'scout_images'
        scout_archive_dir.mkdir()
        shutil.unpack_archive(scout_archive, extract_dir=scout_archive_dir)

        print('------> 5/8 Copying files into place...')
        STATIC_CAV_CONTENT_DIR.mkdir(exist_ok=True)
        file_list = list(concept_archive_dir.iterdir()) + list(scout_archive_dir.iterdir())
        image_ids = set()

        # copy all the images
        for file in tqdm(file_list, unit='file'):
            if file.name in ['snapshots.json', 'manifests']:
                continue

            # record image ids so we can compute activations later
            if file.suffix == '.png':
                image_id = file.name.split('.')[0]
                image_ids.add(image_id)

            dst_path = STATIC_CAV_CONTENT_DIR / file.name
            if not dst_path.exists():
                shutil.copy2(src=file, dst=dst_path)

        # copy the image bank manifests
        shutil.copytree(
            src=scout_archive_dir / 'manifests',
            dst=STATIC_CAV_CONTENT_DIR / 'manifests',
            dirs_exist_ok=True,
        )

        print('------> 6/8 Adding concept metadata to database...')
        django.setup()
        django_call_command('migrate')
        Snapshot = django_apps.get_model('cavstudio_db', 'Snapshot')

        snapshots_file = concept_archive_dir / 'snapshots.json'
        snapshots = json.loads(snapshots_file.read_text())

        print('adding featured snapshots...')
        for snapshot in snapshots:
            snapshot['featured'] = True
            Snapshot.objects.update_or_create(id=snapshot['snapshotId'], defaults={'data': snapshot})

        print('------> 7/8 Precomputing activations...')
        image_refs = [ImageReference(id=id, user_generated=False) for id in image_ids]
        # this function shows its own progress bar
        precalculate_activations(image_refs=image_refs)

        print('------> 8/8 Done!')

def download_file(url, destination):
    class TqdmUpTo(tqdm):
        # from tqdm readme
        def update_to(self, b=1, bsize=1, tsize=None):
            if tsize is not None:
                self.total = tsize
            return self.update(b * bsize - self.n)

    url_filename = url.split('/')[-1]

    with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, desc=url_filename) as t:
        urlretrieve(url, filename=destination, reporthook=t.update_to, data=None)

    t.total = t.n

if __name__ == '__main__':
    main()


text:
module Byebug
  #
  # Reopens the +var+ command to define the +global+ subcommand
  #
  class VarCommand < Command
    #
    # Shows global variables
    #
    class GlobalCommand < Command
      include Helpers::VarHelper

      self.allow_in_post_mortem = true

      def self.regexp
        /^\s* g(?:lobal)? \s*$/x
      end

      def self.description
        <<-DESCRIPTION
          v[ar] g[lobal]

          #{short_description}
        DESCRIPTION
      end

      def self.short_description
        "Shows global variables."
      end

      def execute
        var_global
      end
    end
  end
end


text:
namespace quark {

class CouchDBLogProvider: public ILogProviderFactory {
public:

	void sendLog(ILogProvider::LogType type, json::Value message);
	virtual PLogProvider createLogProvider();

protected:
	std::mutex lock;
};

}