text:
package libnetwork

import (
	"fmt"
	"math/rand"
	"net"
	"strings"
	"sync"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/libnetwork/types"
	"github.com/miekg/dns"
)

// Resolver represents the embedded DNS server in Docker. It operates
// by listening on container's loopback interface for DNS queries.
type Resolver interface {
	// Start starts the name server for the container
	Start() error
	// Stop stops the name server for the container. Stopped resolver
	// can be reused after running the SetupFunc again.
	Stop()
	// SetupFunc() provides the setup function that should be run
	// in the container's network namespace.
	SetupFunc() func()
	// NameServer() returns the IP of the DNS resolver for the
	// containers.
	NameServer() string
	// SetExtServers configures the external nameservers the resolver
	// should use to forward queries
	SetExtServers([]string)
	// FlushExtServers clears the cached UDP connections to external
	// nameservers
	FlushExtServers()
	// ResolverOptions returns resolv.conf options that should be set
	ResolverOptions() []string
}

const (
	resolverIP      = "127.0.0.11"
	dnsPort         = "53"
	ptrIPv4domain   = ".in-addr.arpa."
	ptrIPv6domain   = ".ip6.arpa."
	respTTL         = 600
	maxExtDNS       = 3 //max number of external servers to try
	extIOTimeout    = 4 * time.Second
	defaultRespSize = 512
	maxConcurrent   = 100
	logInterval     = 2 * time.Second
	maxDNSID        = 65536
)

type clientConn struct {
	dnsID      uint16
	respWriter dns.ResponseWriter
}

type extDNSEntry struct {
	ipStr   string
	extConn net.Conn
	extOnce sync.Once
}

// resolver implements the Resolver interface
type resolver struct {
	sb         *sandbox
	extDNSList [maxExtDNS]extDNSEntry
	server     *dns.Server
	conn       *net.UDPConn
	tcpServer  *dns.Server
	tcpListen  *net.TCPListener
	err        error
	count      int32
	tStamp     time.Time
	queryLock  sync.Mutex
	client     map[uint16]clientConn
}

func init() {
	rand.Seed(time.Now().Unix())
}

// NewResolver creates a new instance of the Resolver
func NewResolver(sb *sandbox) Resolver {
	return &resolver{
		sb:     sb,
		err:    fmt.Errorf("setup not done yet"),
		client: make(map[uint16]clientConn),
	}
}

func (r *resolver) SetupFunc() func() {
	return (func() {
		var err error

		// DNS operates primarily on UDP
		addr := &net.UDPAddr{
			IP: net.ParseIP(resolverIP),
		}

		r.conn, err = net.ListenUDP("udp", addr)
		if err != nil {
			r.err = fmt.Errorf("error in opening name server socket %v", err)
			return
		}

		// Listen on a TCP as well
		tcpaddr := &net.TCPAddr{
			IP: net.ParseIP(resolverIP),
		}

		r.tcpListen, err = net.ListenTCP("tcp", tcpaddr)
		if err != nil {
			r.err = fmt.Errorf("error in opening name TCP server socket %v", err)
			return
		}
		r.err = nil
	})
}

func (r *resolver) Start() error {
	// make sure the resolver has been setup before starting
	if r.err != nil {
		return r.err
	}

	if err := r.setupIPTable(); err != nil {
		return fmt.Errorf("setting up IP table rules failed: %v", err)
	}

	s := &dns.Server{Handler: r, PacketConn: r.conn}
	r.server = s
	go func() {
		s.ActivateAndServe()
	}()

	tcpServer := &dns.Server{Handler: r, Listener: r.tcpListen}
	r.tcpServer = tcpServer
	go func() {
		tcpServer.ActivateAndServe()
	}()
	return nil
}

func (r *resolver) FlushExtServers() {
	for i := 0; i < maxExtDNS; i++ {
		if r.extDNSList[i].extConn != nil {
			r.extDNSList[i].extConn.Close()
		}

		r.extDNSList[i].extConn = nil
		r.extDNSList[i].extOnce = sync.Once{}
	}
}

func (r *resolver) Stop() {
	r.FlushExtServers()

	if r.server != nil {
		r.server.Shutdown()
	}
	if r.tcpServer != nil {
		r.tcpServer.Shutdown()
	}
	r.conn = nil
	r.tcpServer = nil
	r.err = fmt.Errorf("setup not done yet")
	r.tStamp = time.Time{}
	r.count = 0
	r.queryLock = sync.Mutex{}
}

func (r *resolver) SetExtServers(dns []string) {
	l := len(dns)
	if l > maxExtDNS {
		l = maxExtDNS
	}
	for i := 0; i < l; i++ {
		r.extDNSList[i].ipStr = dns[i]
	}
}

func (r *resolver) NameServer() string {
	return resolverIP
}

func (r *resolver) ResolverOptions() []string {
	return []string{"ndots:0"}
}

func setCommonFlags(msg *dns.Msg) {
	msg.RecursionAvailable = true
}

func shuffleAddr(addr []net.IP) []net.IP {
	for i := len(addr) - 1; i > 0; i-- {
		r := rand.Intn(i + 1)
		addr[i], addr[r] = addr[r], addr[i]
	}
	return addr
}

func createRespMsg(query *dns.Msg) *dns.Msg {
	resp := new(dns.Msg)
	resp.SetReply(query)
	setCommonFlags(resp)

	return resp
}

func (r *resolver) handleIPQuery(name string, query *dns.Msg, ipType int) (*dns.Msg, error) {
	addr, ipv6Miss := r.sb.ResolveName(name, ipType)
	if addr == nil && ipv6Miss {
		// Send a reply without any Answer sections
		log.Debugf("Lookup name %s present without IPv6 address", name)
		resp := createRespMsg(query)
		return resp, nil
	}
	if addr == nil {
		return nil, nil
	}

	log.Debugf("Lookup for %s: IP %v", name, addr)

	resp := createRespMsg(query)
	if len(addr) > 1 {
		addr = shuffleAddr(addr)
	}
	if ipType == types.IPv4 {
		for _, ip := range addr {
			rr := new(dns.A)
			rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL}
			rr.A = ip
			resp.Answer = append(resp.Answer, rr)
		}
	} else {
		for _, ip := range addr {
			rr := new(dns.AAAA)
			rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: respTTL}
			rr.AAAA = ip
			resp.Answer = append(resp.Answer, rr)
		}
	}
	return resp, nil
}

func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) {
	parts := []string{}

	if strings.HasSuffix(ptr, ptrIPv4domain) {
		parts = strings.Split(ptr, ptrIPv4domain)
	} else if strings.HasSuffix(ptr, ptrIPv6domain) {
		parts = strings.Split(ptr, ptrIPv6domain)
	} else {
		return nil, fmt.Errorf("invalid PTR query, %v", ptr)
	}

	host := r.sb.ResolveIP(parts[0])
	if len(host) == 0 {
		return nil, nil
	}

	log.Debugf("Lookup for IP %s: name %s", parts[0], host)
	fqdn := dns.Fqdn(host)

	resp := new(dns.Msg)
	resp.SetReply(query)
	setCommonFlags(resp)

	rr := new(dns.PTR)
	rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
	rr.Ptr = fqdn
	resp.Answer = append(resp.Answer, rr)
	return resp, nil
}

func (r *resolver) handleSRVQuery(svc string, query *dns.Msg) (*dns.Msg, error) {
	srv, ip, err := r.sb.ResolveService(svc)

	if err != nil {
		return nil, err
	}
	if len(srv) != len(ip) {
		return nil, fmt.Errorf("invalid reply for SRV query %s", svc)
	}

	resp := createRespMsg(query)

	for i, r := range srv {
		rr := new(dns.SRV)
		rr.Hdr = dns.RR_Header{Name: svc, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
		rr.Port = r.Port
		rr.Target = r.Target
		resp.Answer = append(resp.Answer, rr)

		rr1 := new(dns.A)
		rr1.Hdr = dns.RR_Header{Name: r.Target, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL}
		rr1.A = ip[i]
		resp.Extra = append(resp.Extra, rr1)
	}
	return resp, nil

}

func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) {
	if !isTCP {
		resp.Truncated = true
	}

	srv := resp.Question[0].Qtype == dns.TypeSRV
	// trim the Answer RRs one by one till the whole message fits
	// within the reply size
	for resp.Len() > maxSize {
		resp.Answer = resp.Answer[:len(resp.Answer)-1]

		if srv && len(resp.Extra) > 0 {
			resp.Extra = resp.Extra[:len(resp.Extra)-1]
		}
	}
}

func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
	var (
		extConn net.Conn
		resp    *dns.Msg
		err     error
		writer  dns.ResponseWriter
	)

	if query == nil || len(query.Question) == 0 {
		return
	}
	name := query.Question[0].Name

	switch query.Question[0].Qtype {
	case dns.TypeA:
		resp, err = r.handleIPQuery(name, query, types.IPv4)
	case dns.TypeAAAA:
		resp, err = r.handleIPQuery(name, query, types.IPv6)
	case dns.TypePTR:
		resp, err = r.handlePTRQuery(name, query)
	case dns.TypeSRV:
		resp, err = r.handleSRVQuery(name, query)
	}

	if err != nil {
		log.Error(err)
		return
	}

	proto := w.LocalAddr().Network()
	maxSize := 0
	if proto == "tcp" {
		maxSize = dns.MaxMsgSize - 1
	} else if proto == "udp" {
		optRR := query.IsEdns0()
		if optRR != nil {
			maxSize = int(optRR.UDPSize())
		}
		if maxSize < defaultRespSize {
			maxSize = defaultRespSize
		}
	}

	if resp != nil {
		if resp.Len() > maxSize {
			truncateResp(resp, maxSize, proto == "tcp")
		}
		writer = w
	} else {
		queryID := query.Id
		for i := 0; i < maxExtDNS; i++ {
			extDNS := &r.extDNSList[i]
			if extDNS.ipStr == "" {
				break
			}
			extConnect := func() {
				addr := fmt.Sprintf("%s:%d", extDNS.ipStr, 53)
				extConn, err = net.DialTimeout(proto, addr, extIOTimeout)
			}

			// For udp clients connection is persisted to reuse for further queries.
			// Accessing extDNS.extConn be a race here between go rouines. Hence the
			// connection setup is done in a Once block and fetch the extConn again
			extConn = extDNS.extConn
			if extConn == nil || proto == "tcp" {
				if proto == "udp" {
					extDNS.extOnce.Do(func() {
						r.sb.execFunc(extConnect)
						extDNS.extConn = extConn
					})
					extConn = extDNS.extConn
				} else {
					r.sb.execFunc(extConnect)
				}
				if err != nil {
					log.Debugf("Connect failed, %s", err)
					continue
				}
			}
			// If two go routines are executing in parralel one will
			// block on the Once.Do and in case of error connecting
			// to the external server it will end up with a nil err
			// but extConn also being nil.
			if extConn == nil {
				continue
			}
			log.Debugf("Query %s[%d] from %s, forwarding to %s:%s", name, query.Question[0].Qtype,
				extConn.LocalAddr().String(), proto, extDNS.ipStr)

			// Timeout has to be set for every IO operation.
			extConn.SetDeadline(time.Now().Add(extIOTimeout))
			co := &dns.Conn{Conn: extConn}

			// forwardQueryStart stores required context to mux multiple client queries over
			// one connection; and limits the number of outstanding concurrent queries.
			if r.forwardQueryStart(w, query, queryID) == false {
				old := r.tStamp
				r.tStamp = time.Now()
				if r.tStamp.Sub(old) > logInterval {
					log.Errorf("More than %v concurrent queries from %s", maxConcurrent, extConn.LocalAddr().String())
				}
				continue
			}

			defer func() {
				if proto == "tcp" {
					co.Close()
				}
			}()
			err = co.WriteMsg(query)
			if err != nil {
				r.forwardQueryEnd(w, query)
				log.Debugf("Send to DNS server failed, %s", err)
				continue
			}

			resp, err = co.ReadMsg()
			if err != nil {
				r.forwardQueryEnd(w, query)
				log.Debugf("Read from DNS server failed, %s", err)
				continue
			}

			// Retrieves the context for the forwarded query and returns the client connection
			// to send the reply to
			writer = r.forwardQueryEnd(w, resp)
			if writer == nil {
				continue
			}

			resp.Compress = true
			break
		}
		if resp == nil || writer == nil {
			return
		}
	}

	if writer == nil {
		return
	}
	if err = writer.WriteMsg(resp); err != nil {
		log.Errorf("error writing resolver resp, %s", err)
	}
}

func (r *resolver) forwardQueryStart(w dns.ResponseWriter, msg *dns.Msg, queryID uint16) bool {
	proto := w.LocalAddr().Network()
	dnsID := uint16(rand.Intn(maxDNSID))

	cc := clientConn{
		dnsID:      queryID,
		respWriter: w,
	}

	r.queryLock.Lock()
	defer r.queryLock.Unlock()

	if r.count == maxConcurrent {
		return false
	}
	r.count++

	switch proto {
	case "tcp":
		break
	case "udp":
		for ok := true; ok == true; dnsID = uint16(rand.Intn(maxDNSID)) {
			_, ok = r.client[dnsID]
		}
		log.Debugf("client dns id %v, changed id %v", queryID, dnsID)
		r.client[dnsID] = cc
		msg.Id = dnsID
	default:
		log.Errorf("Invalid protocol..")
		return false
	}

	return true
}

func (r *resolver) forwardQueryEnd(w dns.ResponseWriter, msg *dns.Msg) dns.ResponseWriter {
	var (
		cc clientConn
		ok bool
	)
	proto := w.LocalAddr().Network()

	r.queryLock.Lock()
	defer r.queryLock.Unlock()

	if r.count == 0 {
		log.Errorf("Invalid concurrent query count")
	} else {
		r.count--
	}

	switch proto {
	case "tcp":
		break
	case "udp":
		if cc, ok = r.client[msg.Id]; ok == false {
			log.Debugf("Can't retrieve client context for dns id %v", msg.Id)
			return nil
		}
		log.Debugf("dns msg id %v, client id %v", msg.Id, cc.dnsID)
		delete(r.client, msg.Id)
		msg.Id = cc.dnsID
		w = cc.respWriter
	default:
		log.Errorf("Invalid protocol")
		return nil
	}
	return w
}


text:
using System;
using System.Diagnostics;
using System.IO;

using Org.BouncyCastle.Crypto;

namespace Org.BouncyCastle.Crypto.IO
{
    public class CipherStream
        : Stream
    {
        internal Stream stream;
        internal IBufferedCipher inCipher, outCipher;
        private byte[] mInBuf;
        private int mInPos;
        private bool inStreamEnded;

        public CipherStream(
            Stream stream,
            IBufferedCipher readCipher,
            IBufferedCipher writeCipher)
        {
            this.stream = stream;

            if (readCipher != null)
            {
                this.inCipher = readCipher;
                mInBuf = null;
            }

            if (writeCipher != null)
            {
                this.outCipher = writeCipher;
            }
        }

        public IBufferedCipher ReadCipher
        {
            get { return inCipher; }
        }

        public IBufferedCipher WriteCipher
        {
            get { return outCipher; }
        }

        public override int ReadByte()
        {
            if (inCipher == null)
                return stream.ReadByte();

            if (mInBuf == null || mInPos >= mInBuf.Length)
            {
                if (!FillInBuf())
                    return -1;
            }

            return mInBuf[mInPos++];
        }

        public override int Read(
            byte[] buffer,
            int offset,
            int count)
        {
            if (inCipher == null)
                return stream.Read(buffer, offset, count);

            int num = 0;
            while (num < count)
            {
                if (mInBuf == null || mInPos >= mInBuf.Length)
                {
                    if (!FillInBuf())
                        break;
                }

                int numToCopy = System.Math.Min(count - num, mInBuf.Length - mInPos);
                Array.Copy(mInBuf, mInPos, buffer, offset + num, numToCopy);
                mInPos += numToCopy;
                num += numToCopy;
            }

            return num;
        }

        private bool FillInBuf()
        {
            if (inStreamEnded)
                return false;

            mInPos = 0;

            do
            {
                mInBuf = ReadAndProcessBlock();
            }
            while (!inStreamEnded && mInBuf == null);

            return mInBuf != null;
        }

        private byte[] ReadAndProcessBlock()
        {
            int blockSize = inCipher.GetBlockSize();
            int readSize = (blockSize == 0) ? 256 : blockSize;

            byte[] block = new byte[readSize];
            int numRead = 0;
            do
            {
                int count = stream.Read(block, numRead, block.Length - numRead);
                if (count < 1)
                {
                    inStreamEnded = true;
                    break;
                }
                numRead += count;
            }
            while (numRead < block.Length);

            Debug.Assert(inStreamEnded || numRead == block.Length);

            byte[] bytes = inStreamEnded
                ? inCipher.DoFinal(block, 0, numRead)
                : inCipher.ProcessBytes(block);

            if (bytes != null && bytes.Length == 0)
            {
                bytes = null;
            }

            return bytes;
        }

        public override void Write(
            byte[] buffer,
            int offset,
            int count)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(0 <= offset && offset <= buffer.Length);
            Debug.Assert(count >= 0);

            int end = offset + count;

            Debug.Assert(0 <= end && end <= buffer.Length);

            if (outCipher == null)
            {
                stream.Write(buffer, offset, count);
                return;
            }

            byte[] data = outCipher.ProcessBytes(buffer, offset, count);
            if (data != null)
            {
                stream.Write(data, 0, data.Length);
            }
        }

        public override void WriteByte(
            byte b)
        {
            if (outCipher == null)
            {
                stream.WriteByte(b);
                return;
            }

            byte[] data = outCipher.ProcessByte(b);
            if (data != null)
            {
                stream.Write(data, 0, data.Length);
            }
        }

        public override bool CanRead
        {
            get { return stream.CanRead && (inCipher != null); }
        }

        public override bool CanWrite
        {
            get { return stream.CanWrite && (outCipher != null); }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public sealed override long Length
        {
            get { throw new NotSupportedException(); }
        }

        public sealed override long Position
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

#if !NETFX_CORE
		public override void Close()
        {
			if (outCipher != null)
			{
				byte[] data = outCipher.DoFinal();
				stream.Write(data, 0, data.Length);
				stream.Flush();
			}
			stream.Close();
        }
#else
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (outCipher != null)
                {
                    byte[] data = outCipher.DoFinal();
                    stream.Write(data, 0, data.Length);
                    stream.Flush();
                }
                stream.Dispose();
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
#endif

        public override void Flush()
        {
            // Note: outCipher.DoFinal is only called during Close()
            stream.Flush();
        }

        public sealed override long Seek(
            long offset,
            SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public sealed override void SetLength(
            long length)
        {
            throw new NotSupportedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __SNOW__SYS_MAIN_HH__
#define __SNOW__SYS_MAIN_HH__

#include "config.hh"

namespace snow {

/*==============================================================================
  sys_init

    Initializes external libraries and any shared global data.
==============================================================================*/
S_EXPORT void sys_init(int argc, const char **argv);
/*==============================================================================
  sys_quit

    Shuts down external libraries and frees any resources necessary.
==============================================================================*/
S_EXPORT void sys_quit();
/*==============================================================================
  sys_set_physfs_config

    Initializes PhysFS. Is called by sys_init. If not using sys_init, this
    should be called on its own to mount the game directory and any snowballs.
*==============================================================================*/
S_EXPORT void sys_set_physfs_config(int argc, const char **argv, const char *in_base_dir);

} // namespace snow

#endif /* end __SNOW__SYS_MAIN_HH__ include guard */


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/KWBeMemberOfClassMatcher.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/KWBeMemberOfClassMatcher</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWBeMemberOfClassMatcher.h</DeclaredIn>

			<NodeRef refid="9"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/KWBeMemberOfClassMatcher/beMemberOfClass:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWBeMemberOfClassMatcher.h</DeclaredIn>

			<Declaration>- (void)beMemberOfClass:(Class)aClass</Declaration>

			<Anchor>//api/name/beMemberOfClass:</Anchor>
		</Token>

	</File>
</Tokens>


text:
#ifndef EXAMPLES_RNNLM_RNNLM_H_
#define EXAMPLES_RNNLM_RNNLM_H_
#include <vector>
#include "./singa.h"
#include "./rnnlm.pb.h"

namespace rnnlm {
using singa::LayerProto;
using singa::Layer;
using singa::Param;
using singa::Blob;
using singa::Metric;
/**
 * Base RNN layer. May make it a base layer of SINGA.
 */
class RNNLayer : virtual public Layer {
 public:
  /**
   * The recurrent layers may be unrolled different times for different
   * iterations, depending on the applications. For example, the ending word
   * of a sentence may stop the unrolling; unrolling also stops when the max
   * window size is reached. Every layer must reset window_ in its
   * ComputeFeature function.
   *
   * @return the effective BPTT length, which is <= max_window.
   */
  inline int window() { return window_; }

 protected:
  //!< effect window size for BPTT
  int window_;
};

/**
 * Input layer that get read records from data shard
 */
class DataLayer : public RNNLayer, public singa::DataLayer {
 public:
  ~DataLayer();
  void Setup(const LayerProto& proto, int npartitions) override;
  void ComputeFeature(int flag, Metric *perf) override;
  int max_window() const {
    return max_window_;
  }

 private:
  int max_window_;
  singa::DataShard* shard_;
};

/**
 * LabelLayer that read records_[1] to records_[window_] from DataLayer to
 * offer label information
 */
class LabelLayer : public RNNLayer {
 public:
  void Setup(const LayerProto& proto, int npartitions) override;
  void ComputeFeature(int flag, Metric *perf) override;
  void ComputeGradient(int flag, Metric* perf) override {}
};

/**
 * Word embedding layer that get one row from the embedding matrix for each
 * word based on the word index
 */
class EmbeddingLayer : public RNNLayer {
 public:
  ~EmbeddingLayer();
  void Setup(const LayerProto& proto, int npartitions) override;
  void ComputeFeature(int flag, Metric *perf) override;
  void ComputeGradient(int flag, Metric* perf) override;
  const std::vector<Param*> GetParams() const override {
    std::vector<Param*> params{embed_};
    return params;
  }

 private:
  int word_dim_;
  int vocab_size_;
  //!< word embedding matrix of size vocab_size_ x word_dim_
  Param* embed_;
};

/**
 * hid[t] = sigmoid(hid[t-1] * W + src[t])
 */
class HiddenLayer : public RNNLayer {
 public:
  ~HiddenLayer();
  void Setup(const LayerProto& proto, int npartitions) override;
  void ComputeFeature(int flag, Metric *perf) override;
  void ComputeGradient(int flag, Metric* perf) override;
  const std::vector<Param*> GetParams() const override {
    std::vector<Param*> params{weight_};
    return params;
  }

 private:
  Param* weight_;
};

/**
 * p(word at t+1 is from class c) = softmax(src[t]*Wc)[c]
 * p(w|c) = softmax(src[t]*Ww[Start(c):End(c)])
 * p(word at t+1 is w)=p(word at t+1 is from class c)*p(w|c)
 */
class LossLayer : public RNNLayer {
 public:
  ~LossLayer();
  void Setup(const LayerProto& proto, int npartitions) override;
  void ComputeFeature(int flag, Metric *perf) override;
  void ComputeGradient(int flag, Metric* perf) override;
  const std::vector<Param*> GetParams() const override {
    std::vector<Param*> params{word_weight_, class_weight_};
    return params;
  }

 private:
  std::vector<Blob<float>> pword_;
  Blob<float> pclass_;
  Param* word_weight_, *class_weight_;
};
}  // namespace rnnlm
#endif  // EXAMPLES_RNNLM_RNNLM_H_


text: ALTER TABLE AdminSettings ADD COLUMN LastSyncTime STRING;


text:
Rule ID | Missing Help Link | Title |
--------|-------------------|-------|
RS1001 |  | Missing diagnostic analyzer attribute. |
RS1002 |  | Missing kind argument when registering an analyzer action. |
RS1003 |  | Unsupported SymbolKind argument when registering a symbol analyzer action. |
RS1004 |  | Recommend adding language support to diagnostic analyzer. |
RS1005 |  | ReportDiagnostic invoked with an unsupported DiagnosticDescriptor. |
RS1006 |  | Invalid type argument for DiagnosticAnalyzer's Register method. |
RS1007 |  | Provide localizable arguments to diagnostic descriptor constructor. |
RS1008 |  | Avoid storing per-compilation data into the fields of a diagnostic analyzer. |
RS1009 |  | Only internal implementations of this interface are allowed. |
RS1010 |  | Create code actions should have a unique EquivalenceKey for FixAll occurrences support. |
RS1011 |  | Use code actions that have a unique EquivalenceKey for FixAll occurrences support. |
RS1012 |  | Start action has no registered actions. |
RS1013 |  | Start action has no registered non-end actions. |
RS1014 |  | Do not ignore values returned by methods on immutable objects. |
RS1015 |  | Provide non-null 'helpLinkUri' value to diagnostic descriptor constructor. |
RS1016 |  | Code fix providers should provide FixAll support. |
RS1017 |  | DiagnosticId for analyzers must be a non-null constant. |
RS1018 |  | DiagnosticId for analyzers must be in specified format. |
RS1019 |  | DiagnosticId must be unique across analyzers. |
RS1020 |  | Category for analyzers must be from the specified values. |
RS1021 |  | Invalid entry in analyzer category and diagnostic ID range specification file. |
RS1022 |  | Do not use types from Workspaces assembly in an analyzer |
RS1024 |  | Compare symbols correctly |
RS1025 |  | Configure generated code analysis |
RS1026 |  | Enable concurrent execution |
RS1027 |  | Types marked with DiagnosticAnalyzerAttribute(s) should inherit from DiagnosticAnalyzer. |
RS1028 |  | Provide non-null 'customTags' value to diagnostic descriptor constructor. |
RS1029 |  | Do not use reserved diagnostic IDs. |
RS1030 |  | Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer |
RS1031 |  | Define diagnostic title correctly |
RS1032 |  | Define diagnostic message correctly |
RS1033 |  | Define diagnostic description correctly |


text:
require 'spec_helper'

module GatesOfMoria
  describe REPL do
    describe '#answer_question' do
      let(:questions) { File.read('spec/fixtures/one_question.json') }
      let(:output) {  mock('output').as_null_object }
      let(:input) {  mock('input').as_null_object }
      let(:expected_answer) { '@a == 5' }

      context 'given correct answer' do

        it 'should be true (correct)' do
          repl = GatesOfMoria::REPL.new(output, input, questions)
          user_input = "@a = 5"
          repl.answer_question(expected_answer, user_input).should be_true
        end
      end

      context 'given wrong answer' do
        it 'should be false (incorrect)' do
          repl = GatesOfMoria::REPL.new(output, input, questions)
          user_input = "@a = 1"
          repl.answer_question(expected_answer, user_input).should be_false
        end
      end

      context 'given invalid ruby' do
        ["foo", "foo = ", "lambda { ", ")"].each do |user_input|
          it 'should be false (incorrect)' do
            repl = GatesOfMoria::REPL.new(output, input, questions)
            repl.answer_question(expected_answer, user_input).should be_false
          end
        end
      end
    end
  end
end


text:
FROM ubuntu:18.04

# update system
RUN apt-get update

# install dependencies
RUN apt-get -qqy install git zlib1g zlib1g-dev libomp-dev

# install build tools
RUN apt-get -qqy install build-essential software-properties-common && \
    add-apt-repository -y ppa:ubuntu-toolchain-r/test && \
    apt-get update > /dev/null && \
    apt-get -qqy install gcc-snapshot && \
    apt-get update > /dev/null && \
    apt-get -qqy install gcc-8 g++-8 && \
    update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 80 --slave /usr/bin/g++ g++ /usr/bin/g++-8 && \
    apt-get -qqy install cmake git

# copy over current directory to container
RUN git clone --recursive https://github.com/ekg/seqwish.git

# set working directory
WORKDIR seqwish

# build
RUN cmake -H. -Bbuild && cmake --build build -- -j3

# cleanup
RUN apt-get -qy autoremove

# add seqwish to the PATH
ENV PATH /seqwish/bin:$PATH


text:
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#ifndef BDG_PALO_BE_EXPRS_MY_AES_IMPL_H
#define BDG_PALO_BE_EXPRS_MY_AES_IMPL_H

/** Maximum supported key kength */
const int MAX_AES_KEY_LENGTH = 256;

/* TODO: remove in a future version */
/* Guard against using an old export control restriction #define */
#ifdef AES_USE_KEY_BITS
#error AES_USE_KEY_BITS not supported
#endif
typedef uint32_t uint;
typedef uint8_t uint8;

namespace palo {

extern uint *my_aes_opmode_key_sizes;
void my_aes_create_key(const unsigned char *key, uint key_length,
                       uint8 *rkey, enum my_aes_opmode opmode);
}

#endif


text:
'use strict';

module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.addColumn('Purchasables', 'purchaser_limit', {
            type: Sequelize.INTEGER,
            validate: {
                min: 0
            }
        });
    },

    down: (queryInterface) => {
        return queryInterface.removeColumn('Purchasables', 'purchaser_limit');
    }
};


text:
package io.pravega.shared.protocol.netty;

import io.pravega.shared.protocol.netty.WireCommands.Hello;

/**
 * A class that handles each type of reply. (Visitor pattern)
 */
public interface ReplyProcessor {

    default void process(Reply reply) {
        reply.process(this);
    }

    void hello(Hello hello);

    void wrongHost(WireCommands.WrongHost wrongHost);

    void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists);

    void segmentIsSealed(WireCommands.SegmentIsSealed segmentIsSealed);

    void segmentIsTruncated(WireCommands.SegmentIsTruncated segmentIsTruncated);

    void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment);

    void tableSegmentNotEmpty(WireCommands.TableSegmentNotEmpty tableSegmentNotEmpty);

    void invalidEventNumber(WireCommands.InvalidEventNumber invalidEventNumber);

    void appendSetup(WireCommands.AppendSetup appendSetup);

    void dataAppended(WireCommands.DataAppended dataAppended);

    void conditionalCheckFailed(WireCommands.ConditionalCheckFailed dataNotAppended);

    void storageFlushed(WireCommands.StorageFlushed storageFlushed);

    void storageChunksListed(WireCommands.StorageChunksListed storageChunksListed);

    void segmentRead(WireCommands.SegmentRead segmentRead);

    void segmentAttributeUpdated(WireCommands.SegmentAttributeUpdated segmentAttributeUpdated);

    void segmentAttribute(WireCommands.SegmentAttribute segmentAttribute);

    void streamSegmentInfo(WireCommands.StreamSegmentInfo streamInfo);

    void segmentCreated(WireCommands.SegmentCreated segmentCreated);

    void segmentsMerged(WireCommands.SegmentsMerged segmentsMerged);

    void segmentsBatchMerged(WireCommands.SegmentsBatchMerged segmentsMerged);

    void segmentSealed(WireCommands.SegmentSealed segmentSealed);

    void segmentTruncated(WireCommands.SegmentTruncated segmentTruncated);

    void segmentDeleted(WireCommands.SegmentDeleted segmentDeleted);

    void operationUnsupported(WireCommands.OperationUnsupported operationUnsupported);

    void keepAlive(WireCommands.KeepAlive keepAlive);

    void connectionDropped();

    void segmentPolicyUpdated(WireCommands.SegmentPolicyUpdated segmentPolicyUpdated);

    void processingFailure(Exception error);

    void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed);

    void tableSegmentInfo(WireCommands.TableSegmentInfo info);

    void tableEntriesUpdated(WireCommands.TableEntriesUpdated tableEntriesUpdated);

    void tableKeysRemoved(WireCommands.TableKeysRemoved tableKeysRemoved);

    void tableRead(WireCommands.TableRead tableRead);

    void tableKeyDoesNotExist(WireCommands.TableKeyDoesNotExist tableKeyDoesNotExist);

    void tableKeyBadVersion(WireCommands.TableKeyBadVersion tableKeyBadVersion);

    void tableKeysRead(WireCommands.TableKeysRead tableKeysRead);

    void tableEntriesRead(WireCommands.TableEntriesRead tableEntriesRead);

    void tableEntriesDeltaRead(WireCommands.TableEntriesDeltaRead tableEntriesDeltaRead);

    void errorMessage(WireCommands.ErrorMessage errorMessage);
}


text:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath*:config/springAnnotation-*.xml</param-value>
  </context-param>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
	  <param-name>encoding</param-name>
	  <param-value>UTF-8</param-value>
	</init-param>
	<init-param>
	  <param-name>forceEncoding</param-name>
	  <param-value>true</param-value>
	</init-param>
  </filter>
  <filter>
  	<filter-name>openSession</filter-name>
  	<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.springmvc.ketao.interceptor.LoginFilter</filter-class>
	<init-param>
	  <param-name>excludedUrls</param-name>
	  <param-value>/login, /mobile</param-value>
	</init-param>
  </filter>

  <!-- encoding filter for jsp page -->
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
  	<filter-name>openSession</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
  	 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
  	<servlet-name>springMVC</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
  			<param-name>contextConfigLocation</param-name>
  			<param-value>classpath*:config/springMVC-*.xml</param-value>
  		</init-param>
  	 <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springMVC</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


text:
package org.jivesoftware.openfire.fastpath.util;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Performs tasks using worker threads. It also allows tasks to be scheduled to be
 * run at future dates. This class mimics relevant methods in both
 * {@link ExecutorService} and {@link Timer}. Any {@link TimerTask} that's
 * scheduled to be run in the future will automatically be run using the thread
 * executor's thread pool. This means that the standard restriction that TimerTasks
 * should run quickly does not apply.
 *
 * @author Matt Tucker
 */
public class TaskEngine {

    private static TaskEngine instance = new TaskEngine();

    /**
     * Returns a task engine instance (singleton).
     *
     * @return a task engine.
     */
    public static TaskEngine getInstance() {
        return instance;
    }

    private Timer timer;
    private ExecutorService executor;
    private final Map<TimerTask, TimerTaskWrapper> wrappedTasks = new HashMap<TimerTask, TimerTaskWrapper>();

    /**
     * Constructs a new task engine.
     */
    private TaskEngine() {
        timer = new Timer("timer-fastpath", true);
        executor = Executors.newCachedThreadPool(new ThreadFactory() {

            final AtomicInteger threadNumber = new AtomicInteger(1);

            public Thread newThread(Runnable runnable) {
                // Use our own naming scheme for the threads.
                Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable,
                                      "pool-fastpath" + threadNumber.getAndIncrement(), 0);
                // Make workers daemon threads.
                thread.setDaemon(true);
                if (thread.getPriority() != Thread.NORM_PRIORITY) {
                    thread.setPriority(Thread.NORM_PRIORITY);
                }
                return thread;
            }
        });
    }

    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task.
     *
     * @param task the task to submit.
     * @return a Future representing pending completion of the task,
     *      and whose <tt>get()</tt> method will return <tt>null</tt>
     *      upon completion.
     * @throws java.util.concurrent.RejectedExecutionException if task cannot be scheduled
     *      for execution.
     * @throws NullPointerException if task null.
     */
    public Future<?> submit(Runnable task) {
        return executor.submit(task);
    }

    /**
     * Schedules the specified task for execution after the specified delay.
     *
     * @param task  task to be scheduled.
     * @param delay delay in milliseconds before task is to be executed.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *         <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, or timer was cancelled.
     */
    public void schedule(TimerTask task, long delay) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.schedule(taskWrapper, delay);
    }

    /**
     * Schedules the specified task for execution at the specified time.  If
     * the time is in the past, the task is scheduled for immediate execution.
     *
     * @param task task to be scheduled.
     * @param time time at which task is to be executed.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, Date time) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.schedule(taskWrapper, time);
    }

    /**
     * Schedules the specified task for repeated fixed-delay execution,
     * beginning after the specified delay.  Subsequent executions take place
     * at approximately regular intervals separated by the specified period.
     *
     *
In fixed-delay execution, each execution is scheduled relative to
     * the actual execution time of the previous execution.  If an execution
     * is delayed for any reason (such as garbage collection or other
     * background activity), subsequent executions will be delayed as well.
     * In the long run, the frequency of execution will generally be slightly
     * lower than the reciprocal of the specified period (assuming the system
     * clock underlying <tt>Object.wait(long)</tt> is accurate).
     *
     *
Fixed-delay execution is appropriate for recurring activities
     * that require "smoothness."  In other words, it is appropriate for
     * activities where it is more important to keep the frequency accurate
     * in the short run than in the long run.  This includes most animation
     * tasks, such as blinking a cursor at regular intervals.  It also includes
     * tasks wherein regular activity is performed in response to human
     * input, such as automatically repeating a character as long as a key
     * is held down.
     *
     * @param task   task to be scheduled.
     * @param delay  delay in milliseconds before task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *         <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, long delay, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.schedule(taskWrapper, delay, period);
    }

    /**
     * Schedules the specified task for repeated fixed-delay execution,
     * beginning at the specified time. Subsequent executions take place at
     * approximately regular intervals, separated by the specified period.
     *
     *
In fixed-delay execution, each execution is scheduled relative to
     * the actual execution time of the previous execution.  If an execution
     * is delayed for any reason (such as garbage collection or other
     * background activity), subsequent executions will be delayed as well.
     * In the long run, the frequency of execution will generally be slightly
     * lower than the reciprocal of the specified period (assuming the system
     * clock underlying <tt>Object.wait(long)</tt> is accurate).
     *
     *
Fixed-delay execution is appropriate for recurring activities
     * that require "smoothness."  In other words, it is appropriate for
     * activities where it is more important to keep the frequency accurate
     * in the short run than in the long run.  This includes most animation
     * tasks, such as blinking a cursor at regular intervals.  It also includes
     * tasks wherein regular activity is performed in response to human
     * input, such as automatically repeating a character as long as a key
     * is held down.
     *
     * @param task   task to be scheduled.
     * @param firstTime First time at which task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    public void schedule(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.schedule(taskWrapper, firstTime, period);
    }

    /**
     * Schedules the specified task for repeated fixed-rate execution,
     * beginning after the specified delay.  Subsequent executions take place
     * at approximately regular intervals, separated by the specified period.
     *
     *
In fixed-rate execution, each execution is scheduled relative to the
     * scheduled execution time of the initial execution.  If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), two or more executions will occur in rapid succession to
     * "catch up."  In the long run, the frequency of execution will be
     * exactly the reciprocal of the specified period (assuming the system
     * clock underlying <tt>Object.wait(long)</tt> is accurate).
     *
     *
Fixed-rate execution is appropriate for recurring activities that
     * are sensitive to absolute time, such as ringing a chime every
     * hour on the hour, or running scheduled maintenance every day at a
     * particular time.  It is also appropriate for recurring activities
     * where the total time to perform a fixed number of executions is
     * important, such as a countdown timer that ticks once every second for
     * ten seconds.  Finally, fixed-rate execution is appropriate for
     * scheduling multiple repeating timer tasks that must remain synchronized
     * with respect to one another.
     *
     * @param task   task to be scheduled.
     * @param delay  delay in milliseconds before task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *         <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.scheduleAtFixedRate(taskWrapper, delay, period);
    }

    /**
     * Schedules the specified task for repeated fixed-rate execution,
     * beginning at the specified time. Subsequent executions take place at
     * approximately regular intervals, separated by the specified period.
     *
     *
In fixed-rate execution, each execution is scheduled relative to the
     * scheduled execution time of the initial execution.  If an execution is
     * delayed for any reason (such as garbage collection or other background
     * activity), two or more executions will occur in rapid succession to
     * "catch up."  In the long run, the frequency of execution will be
     * exactly the reciprocal of the specified period (assuming the system
     * clock underlying <tt>Object.wait(long)</tt> is accurate).
     *
     *
Fixed-rate execution is appropriate for recurring activities that
     * are sensitive to absolute time, such as ringing a chime every
     * hour on the hour, or running scheduled maintenance every day at a
     * particular time.  It is also appropriate for recurring activities
     * where the total time to perform a fixed number of executions is
     * important, such as a countdown timer that ticks once every second for
     * ten seconds.  Finally, fixed-rate execution is appropriate for
     * scheduling multiple repeating timer tasks that must remain synchronized
     * with respect to one another.
     *
     * @param task   task to be scheduled.
     * @param firstTime First time at which task is to be executed.
     * @param period time in milliseconds between successive task executions.
     * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     */
    public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        synchronized (wrappedTasks) {
            wrappedTasks.put(task, taskWrapper);
        }
        timer.scheduleAtFixedRate(taskWrapper, firstTime, period);
    }

    /**
     * Cancels the execution of a scheduled task. {@link java.util.TimerTask#cancel()}
     *
     * @param task the scheduled task to cancel.
     */
    public void cancelScheduledTask(TimerTask task) {
        TaskEngine.TimerTaskWrapper taskWrapper;
        synchronized (wrappedTasks) {
            taskWrapper = wrappedTasks.remove(task);
        }
        if (taskWrapper != null) {
            taskWrapper.cancel();
            task.cancel();
        }
    }

    public void dispose() {
        executor.shutdownNow();
        executor = null;

        timer.cancel();
        timer = null;

        instance = null;
        wrappedTasks.clear();
    }

    /**
     * Wrapper class for a standard TimerTask. It simply executes the TimerTask
     * using the executor's thread pool.
     */
    private class TimerTaskWrapper extends TimerTask {

        private TimerTask task;

        public TimerTaskWrapper(TimerTask task) {
            this.task = task;
        }

        @Override
		public void run() {
            executor.submit(task);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace phpDocumentor\Descriptor;

use Mockery as m;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use phpDocumentor\Reflection\Fqsen;
use stdClass;

/**
 * Tests the functionality for the ClassDescriptor class.
 *
 * @coversDefaultClass \phpDocumentor\Descriptor\ClassDescriptor
 */
final class ClassDescriptorTest extends MockeryTestCase
{
    /** @var ClassDescriptor $fixture */
    protected $fixture;
    use MagicPropertyContainerTests;
    use MagicMethodContainerTests;

    /**
     * Creates a new (emoty) fixture object.
     */
    protected function setUp() : void
    {
        $this->fixture = new ClassDescriptor();
        $this->fixture->setFullyQualifiedStructuralElementName(new Fqsen('\My\Class'));
    }

    /**
     * @covers ::setParent
     * @covers ::getParent
     */
    public function testSettingAndGettingAParent() : void
    {
        $this->assertNull($this->fixture->getParent());

        $mock = m::mock(ClassDescriptor::class);

        $this->fixture->setParent($mock);

        $this->assertSame($mock, $this->fixture->getParent());
    }

    /**
     * @covers ::setParent
     */
    public function testSettingNoParent() : void
    {
        $mock = null;

        $this->fixture->setParent($mock);

        $this->assertSame($mock, $this->fixture->getParent());
    }

    /**
     * @covers ::setInterfaces
     * @covers ::getInterfaces
     */
    public function testSettingAndGettingInterfaces() : void
    {
        $this->assertInstanceOf(Collection::class, $this->fixture->getInterfaces());

        $mock = m::mock(Collection::class);

        $this->fixture->setInterfaces($mock);

        $this->assertSame($mock, $this->fixture->getInterfaces());
    }

    /**
     * @covers ::setConstants
     * @covers ::getConstants
     */
    public function testSettingAndGettingConstants() : void
    {
        $this->assertInstanceOf(Collection::class, $this->fixture->getConstants());

        $mock = m::mock(Collection::class);

        $this->fixture->setConstants($mock);

        $this->assertSame($mock, $this->fixture->getConstants());
    }

    /**
     * @covers ::setProperties
     * @covers ::getProperties
     */
    public function testSettingAndGettingProperties() : void
    {
        $this->assertInstanceOf(Collection::class, $this->fixture->getProperties());

        $mock = m::mock(Collection::class);

        $this->fixture->setProperties($mock);

        $this->assertSame($mock, $this->fixture->getProperties());
    }

    /**
     * @covers ::setMethods
     * @covers ::getMethods
     */
    public function testSettingAndGettingMethods() : void
    {
        $this->assertInstanceOf(Collection::class, $this->fixture->getMethods());

        $mock = m::mock(Collection::class);

        $this->fixture->setMethods($mock);

        $this->assertSame($mock, $this->fixture->getMethods());
    }

    /**
     * @covers ::getInheritedMethods
     */
    public function testRetrievingInheritedMethodsReturnsEmptyCollectionWithoutParent() : void
    {
        $inheritedMethods = $this->fixture->getInheritedMethods();
        $this->assertInstanceOf(Collection::class, $inheritedMethods);
        $this->assertCount(0, $inheritedMethods);
    }

    /**
     * @covers ::getInheritedMethods
     */
    public function testRetrievingInheritedMethodsReturnsCollectionWithParent() : void
    {
        $mock = m::mock(ClassDescriptor::class);
        $mock->shouldReceive('getMethods')->andReturn(new Collection(['methods']));
        $mock->shouldReceive('getInheritedMethods')->andReturn(new Collection(['inherited']));

        $this->fixture->setParent($mock);
        $result = $this->fixture->getInheritedMethods();

        $this->assertInstanceOf(Collection::class, $result);

        $expected = ['methods', 'inherited'];
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::getInheritedMethods
     */
    public function testRetrievingInheritedMethodsReturnsTraitMethods() : void
    {
        // Arrange
        $expected = ['methods'];
        $traitDescriptorMock = m::mock(TraitDescriptor::class);
        $traitDescriptorMock->shouldReceive('getMethods')->andReturn(new Collection(['methods']));
        $this->fixture->setUsedTraits(new Collection([$traitDescriptorMock]));

        // Act
        $result = $this->fixture->getInheritedMethods();

        // Assert
        $this->assertInstanceOf(Collection::class, $result);
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::getInheritedMethods
     * @ticket https://github.com/phpDocumentor/phpDocumentor2/issues/1307
     */
    public function testRetrievingInheritedMethodsDoesNotCrashWhenUsedTraitIsNotInProject() : void
    {
        // Arrange
        $expected = [];
        // unknown traits are not converted to TraitDescriptors but kept as strings
        $this->fixture->setUsedTraits(new Collection(['unknownTrait']));

        // Act
        $result = $this->fixture->getInheritedMethods();

        // Assert
        $this->assertInstanceOf(Collection::class, $result);
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::isAbstract
     * @covers ::setAbstract
     */
    public function testSettingAndGettingWhetherClassIsAbstract() : void
    {
        $this->assertFalse($this->fixture->isAbstract());

        $this->fixture->setAbstract(true);

        $this->assertTrue($this->fixture->isAbstract());
    }

    /**
     * @covers ::isFinal
     * @covers ::setFinal
     */
    public function testSettingAndGettingWhetherClassIsFinal() : void
    {
        $this->assertFalse($this->fixture->isFinal());

        $this->fixture->setFinal(true);

        $this->assertTrue($this->fixture->isFinal());
    }

    /**
     * @covers ::getInheritedConstants
     */
    public function testGetInheritedConstantsNoParent() : void
    {
        $descriptor = new ClassDescriptor();
        $this->assertInstanceOf(Collection::class, $descriptor->getInheritedConstants());

        $descriptor->setParent(new stdClass());
        $this->assertInstanceOf(Collection::class, $descriptor->getInheritedConstants());
    }

    /**
     * @covers ::getInheritedConstants
     */
    public function testGetInheritedConstantsWithClassDescriptorParent() : void
    {
        $collectionMock = m::mock(Collection::class);
        $collectionMock->shouldReceive('get');
        $mock = m::mock(ClassDescriptor::class);
        $mock->shouldReceive('getConstants')->andReturn(new Collection(['constants']));
        $mock->shouldReceive('getInheritedConstants')->andReturn(new Collection(['inherited']));

        $this->fixture->setParent($mock);
        $result = $this->fixture->getInheritedConstants();

        $this->assertInstanceOf(Collection::class, $result);

        $expected = ['constants', 'inherited'];
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::getInheritedProperties
     */
    public function testGetInheritedPropertiesNoParent() : void
    {
        $descriptor = new ClassDescriptor();
        $this->assertInstanceOf(Collection::class, $descriptor->getInheritedProperties());

        $descriptor->setParent(new stdClass());
        $this->assertInstanceOf(Collection::class, $descriptor->getInheritedProperties());
    }

    /**
     * @covers ::getInheritedProperties
     */
    public function testGetInheritedPropertiesWithClassDescriptorParent() : void
    {
        $collectionMock = m::mock(Collection::class);
        $collectionMock->shouldReceive('get');
        $mock = m::mock(ClassDescriptor::class);
        $mock->shouldReceive('getProperties')->andReturn(new Collection(['properties']));
        $mock->shouldReceive('getInheritedProperties')->andReturn(new Collection(['inherited']));

        $this->fixture->setParent($mock);
        $result = $this->fixture->getInheritedProperties();

        $this->assertInstanceOf(Collection::class, $result);

        $expected = ['properties', 'inherited'];
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::getInheritedProperties
     */
    public function testRetrievingInheritedPropertiesReturnsTraitProperties() : void
    {
        // Arrange
        $expected = ['properties'];
        $traitDescriptorMock = m::mock(TraitDescriptor::class);
        $traitDescriptorMock->shouldReceive('getProperties')->andReturn(new Collection(['properties']));
        $this->fixture->setUsedTraits(new Collection([$traitDescriptorMock]));

        // Act
        $result = $this->fixture->getInheritedProperties();

        // Assert
        $this->assertInstanceOf(Collection::class, $result);
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::getInheritedProperties
     * @ticket https://github.com/phpDocumentor/phpDocumentor2/issues/1307
     */
    public function testRetrievingInheritedPropertiesDoesNotCrashWhenUsedTraitIsNotInProject() : void
    {
        // Arrange
        $expected = [];
        // unknown traits are not converted to TraitDescriptors but kept as strings
        $this->fixture->setUsedTraits(new Collection(['unknownTrait']));

        // Act
        $result = $this->fixture->getInheritedProperties();

        // Assert
        $this->assertInstanceOf(Collection::class, $result);
        $this->assertSame($expected, $result->getAll());
    }

    /**
     * @covers ::setPackage
     */
    public function testSetPackage() : void
    {
        $package = 'Package';

        $mock = m::mock(ClassDescriptor::class);
        $mock->shouldDeferMissing();

        $constantDescriptor = m::mock(ConstantDescriptor::class);

        /** @var m\mockInterface|Collection $constantCollection */
        $constantCollection = m::mock(Collection::class);
        $constantCollection->shouldDeferMissing();
        $constantCollection->add($constantDescriptor);

        $propertyDescriptor = m::mock(PropertyDescriptor::class);

        /** @var m\mockInterface|Collection $propertyCollection */
        $propertyCollection = m::mock(Collection::class);
        $propertyCollection->shouldDeferMissing();
        $propertyCollection->add($propertyDescriptor);

        $methodDescriptor = m::mock(MethodDescriptor::class);

        /** @var m\mockInterface|Collection $methodCollection */
        $methodCollection = m::mock(Collection::class);
        $methodCollection->shouldDeferMissing();
        $methodCollection->add($methodDescriptor);

        /** @var m\mockInterface|ClassDescriptor $mock */
        $mock = m::mock(ClassDescriptor::class);
        $mock->shouldDeferMissing();
        $mock->shouldReceive('getProperties')->andReturn($propertyCollection);

        $mock->shouldReceive('getConstants')->andReturn($constantCollection);
        $constantDescriptor->shouldReceive('setPackage')->with($package);

        $mock->shouldReceive('getProperties')->andReturn($propertyCollection);
        $propertyDescriptor->shouldReceive('setPackage')->with($package);

        $mock->shouldReceive('getMethods')->andReturn($methodCollection);
        $methodDescriptor->shouldReceive('setPackage')->with($package);

        $mock->setPackage($package);

        $this->assertTrue(true);
    }

    /**
     * Test to cover magic method of parent abstract class
     *
     * @covers \phpDocumentor\Descriptor\DescriptorAbstract::__call
     */
    public function testCall() : void
    {
        $this->assertNull($this->fixture->__call('notexisting', []));
        $this->assertInstanceOf(Collection::class, $this->fixture->__call('getNotexisting', []));
    }

    /**
     * @covers \phpDocumentor\Descriptor\DescriptorAbstract::getSummary
     */
    public function testSummaryInheritsWhenNoneIsPresent() : void
    {
        // Arrange
        $summary = 'This is a summary';
        $this->fixture->setSummary('');
        $parentInterface = $this->whenFixtureHasParentClass();
        $parentInterface->setSummary($summary);

        // Act
        $result = $this->fixture->getSummary();

        // Assert
        $this->assertSame($summary, $result);
    }

    protected function whenFixtureHasParentClass() : ClassDescriptor
    {
        $class = new ClassDescriptor();
        $this->fixture->setParent($class);

        return $class;
    }
}


text:
include $(THEOS)/makefiles/common.mk

BUNDLE_NAME = MobileNotifierSettings
MobileNotifierSettings_FILES = MobileNotifierSettings.mm
MobileNotifierSettings_INSTALL_PATH = /Library/PreferenceBundles
MobileNotifierSettings_FRAMEWORKS = UIKit
MobileNotifierSettings_PRIVATE_FRAMEWORKS = Preferences

include $(FW_MAKEDIR)/bundle.mk

internal-stage::
	$(ECHO_NOTHING)mkdir -p $(FW_STAGING_DIR)/Library/PreferenceLoader/Preferences$(ECHO_END)
	$(ECHO_NOTHING)cp entry.plist $(FW_STAGING_DIR)/Library/PreferenceLoader/Preferences/MobileNotifierSettings.plist$(ECHO_END)


text:
//
//  ========================================================================
//  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.websocket.common.annotations;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

/**
 * Invalid Socket: Annotate a message interest on a method with a return type.
 */
@WebSocket
public class BadBinarySignatureSocket
{
    /**
     * Declaring a non-void return type
     */
    @OnWebSocketMessage
    public boolean onBinary(Session session, byte buf[], int offset, int len)
    {
        return false;
    }
}


text:
package com.evolveum.midpoint.web.component.menu;

import com.evolveum.midpoint.gui.api.GuiStyleConstants;
import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.security.SecurityUtils;
import com.evolveum.midpoint.web.session.SessionStorage;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import java.util.List;
import java.util.Map;

/**
 * @author Viliam Repan (lazyman)
 */
public class SideBarMenuPanel extends BasePanel<List<SideBarMenuItem>> {
    private static final long serialVersionUID = 1L;

    private static final String ID_SIDEBAR = "sidebar";
    private static final String ID_MENU_ITEMS = "menuItems";
    private static final String ID_NAME = "name";
    private static final String ID_ITEMS = "items";
    private static final String ID_ITEM = "item";
    private static final String ID_MINIMIZED_ICON = "minimizedIcon";

    public SideBarMenuPanel(String id, IModel<List<SideBarMenuItem>> model) {
        super(id, model);

        setOutputMarkupId(true);
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();
        initLayout();
    }

    protected void initLayout() {
        WebMarkupContainer sidebar = new WebMarkupContainer(ID_SIDEBAR);
        sidebar.setOutputMarkupId(true);
        add(sidebar);

        ListView<SideBarMenuItem> menuItems = new ListView<SideBarMenuItem>(ID_MENU_ITEMS, getModel()) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void populateItem(final ListItem<SideBarMenuItem> item) {
                Label name = new Label(ID_NAME, item.getModelObject().getName());
                name.add(new AjaxEventBehavior("click") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected void onEvent(AjaxRequestTarget target) {
                        onMenuClick(sidebar, item, target);
                    }
                });
                item.add(name);

                WebMarkupContainer icon = new WebMarkupContainer(ID_MINIMIZED_ICON);
                icon.add(new AjaxEventBehavior("click") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected void onEvent(AjaxRequestTarget target) {
                        onMenuClick(sidebar, item, target);
                    }
                });
                icon.add(AttributeModifier.append("class", new IModel<String>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String getObject() {
                        SideBarMenuItem mainMenu = item.getModelObject();
                        if (isMenuExpanded(mainMenu)) {
                            return GuiStyleConstants.CLASS_ICON_COLLAPSE;
                        }

                        return GuiStyleConstants.CLASS_ICON_EXPAND;
                    }
                }));
//                icon.add(new VisibleEnableBehaviour() {
//
//                    @Override
//                    public boolean isVisible() {
//                        SideBarMenuItem mainMenu = item.getModelObject();
//
//                        return !isMenuExpanded(mainMenu);
//                    }
//                });
                item.add(icon);

                ListView<MainMenuItem> items = new ListView<MainMenuItem>(ID_ITEMS,
                    new PropertyModel<>(item.getModel(), SideBarMenuItem.F_ITEMS)) {

                    @Override
                    protected void populateItem(final ListItem<MainMenuItem> listItem) {
                        MainMenuPanel item = new MainMenuPanel(ID_ITEM, listItem.getModel());
                        listItem.add(item);

                        listItem.add(new VisibleEnableBehaviour() {

                            @Override
                            public boolean isVisible() {
                                MainMenuItem mmi = listItem.getModelObject();
                                if (!SecurityUtils.isMenuAuthorized(mmi)) {
                                    return false;
                                }

                                if (mmi.getItems().isEmpty()) {
                                    return true;
                                }

                                for (MenuItem i : mmi.getItems()) {
                                    if (SecurityUtils.isMenuAuthorized(i)) {
                                        return true;
                                    }
                                }
                                return false;
                            }
                        });
                    }
                };
                item.add(items);

                item.add(new VisibleEnableBehaviour() {

                    @Override
                    public boolean isVisible() {
                        SideBarMenuItem mainMenu = item.getModelObject();

                        for (MainMenuItem i : mainMenu.getItems()) {
                            boolean visible = true;
                            if (i.getVisibleEnable() != null) {
                                visible = i.getVisibleEnable().isVisible();
                            }

                            if (visible && SecurityUtils.isMenuAuthorized(i)) {
                                return true;
                            }
                        }

                        return false;
                    }
                });

                items.add(new VisibleEnableBehaviour() {

                    @Override
                    public boolean isVisible() {
                        SideBarMenuItem mainMenu = item.getModelObject();
                        return isMenuExpanded(mainMenu);
                    }
                });
            }
        };
        sidebar.add(menuItems);
    }

    private void onMenuClick(final WebMarkupContainer sidebar, final ListItem<SideBarMenuItem> item, AjaxRequestTarget target) {
        SideBarMenuItem mainMenu = item.getModelObject();

        SessionStorage storage = getPageBase().getSessionStorage();
        Map<String, Boolean> menuState = storage.getMainMenuState();

        String menuLabel = mainMenu.getName().getObject();
        // we'll use menu label as key
        Boolean expanded = menuState.get(menuLabel);

        if (expanded == null) {
            expanded = true;
        }

        menuState.put(menuLabel, !expanded);

        target.add(sidebar);
    }

    private boolean isMenuExpanded(SideBarMenuItem mainMenu) {
        SessionStorage storage = getPageBase().getSessionStorage();
        Map<String, Boolean> menuState = storage.getMainMenuState();

        String menuLabel = mainMenu.getName().getObject();
        // we'll use menu label as key
        Boolean expanded = menuState.get(menuLabel);

        return expanded != null ? expanded : true;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
          <token id="1">
            <word>bitter</word>
            <lemma>bitter</lemma>
            <CharacterOffsetBegin>0</CharacterOffsetBegin>
            <CharacterOffsetEnd>6</CharacterOffsetEnd>
            <POS>JJ</POS>
          </token>
          <token id="2">
            <word>pill</word>
            <lemma>pill</lemma>
            <CharacterOffsetBegin>7</CharacterOffsetBegin>
            <CharacterOffsetEnd>11</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="3">
            <word>to</word>
            <lemma>to</lemma>
            <CharacterOffsetBegin>12</CharacterOffsetBegin>
            <CharacterOffsetEnd>14</CharacterOffsetEnd>
            <POS>TO</POS>
          </token>
          <token id="4">
            <word>swallow</word>
            <lemma>swallow</lemma>
            <CharacterOffsetBegin>15</CharacterOffsetBegin>
            <CharacterOffsetEnd>22</CharacterOffsetEnd>
            <POS>VB</POS>
          </token>
          <token id="5">
            <word>crack</word>
            <lemma>crack</lemma>
            <CharacterOffsetBegin>23</CharacterOffsetBegin>
            <CharacterOffsetEnd>28</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
        </tokens>
        <parse>(ROOT (FRAG (NP (JJ bitter) (NN pill)) (S (VP (TO to) (VP (VB swallow) (NP (NN crack))))))) </parse>
        <dependencies type="basic-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">pill</dependent>
          </dep>
          <dep type="amod">
            <governor idx="2">pill</governor>
            <dependent idx="1">bitter</dependent>
          </dep>
          <dep type="aux">
            <governor idx="4">swallow</governor>
            <dependent idx="3">to</dependent>
          </dep>
          <dep type="dep">
            <governor idx="2">pill</governor>
            <dependent idx="4">swallow</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">swallow</governor>
            <dependent idx="5">crack</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">pill</dependent>
          </dep>
          <dep type="amod">
            <governor idx="2">pill</governor>
            <dependent idx="1">bitter</dependent>
          </dep>
          <dep type="aux">
            <governor idx="4">swallow</governor>
            <dependent idx="3">to</dependent>
          </dep>
          <dep type="dep">
            <governor idx="2">pill</governor>
            <dependent idx="4">swallow</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">swallow</governor>
            <dependent idx="5">crack</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-ccprocessed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">pill</dependent>
          </dep>
          <dep type="amod">
            <governor idx="2">pill</governor>
            <dependent idx="1">bitter</dependent>
          </dep>
          <dep type="aux">
            <governor idx="4">swallow</governor>
            <dependent idx="3">to</dependent>
          </dep>
          <dep type="dep">
            <governor idx="2">pill</governor>
            <dependent idx="4">swallow</dependent>
          </dep>
          <dep type="dobj">
            <governor idx="4">swallow</governor>
            <dependent idx="5">crack</dependent>
          </dep>
        </dependencies>
      </sentence>
    </sentences>
  </document>
</root>


text:
package org.tresamigos.smv

class SmvHDFSTest extends SmvTestUtil {

  test("Test HDFS delete file operation") {
    resetTestcaseTempDir()
    val outFilePath = createTempFile("out.csv")

    // confirm csv file now exists.
    assert(outFilePath.canRead())

    // delete the generated file and confirm we get true from delete op
    val res1 = SmvHDFS.deleteFile(outFilePath.getAbsolutePath())
    assert(res1)

    // confirm csv file no longer exists.
    assert(!outFilePath.canRead())

    // second delete should just return false silently.
    val res2 = SmvHDFS.deleteFile(outFilePath.getAbsolutePath())
    assert(!res2)
  }

  test("Test HDFS list directory operation") {
    resetTestcaseTempDir()

    createTempFile("F3.csv")
    createTempFile("F1.csv")
    createTempFile("F2.csv")

    val files = SmvHDFS.dirList(testcaseTempDir)
    assertUnorderedSeqEqual(files, Seq("F1.csv", "F2.csv", "F3.csv"))
  }

  test("Test HDFS list non-existent directory") {
    resetTestcaseTempDir()
    val files = SmvHDFS.dirList("/Some_Directory_That_Does_Not_Exist")
    assert(files === Seq.empty[String])
  }

  test("Test the basename function in HDFS") {
    assert(SmvHDFS.baseName("/tmp/a/x.csv") === "x.csv")
    assert(SmvHDFS.baseName("file://tmp/a/y.csv") === "y.csv")
    assert(SmvHDFS.baseName("hdfs:localhost:4040/tmp/a/z.csv") === "z.csv")
  }

  test("Test purging old files from directory") {
    resetTestcaseTempDir
    createTempFile("F1.csv")
    createTempFile("F2.csv")
    createTempFile("F3.csv")

    SmvHDFS.purgeDirectory(testcaseTempDir, Seq("F3.csv"))

    // only F3.csv should remain in the dir now.
    val files = SmvHDFS.dirList(testcaseTempDir)
    assertUnorderedSeqEqual(files, Seq("F3.csv"))
  }

  test("Test file modificationTime") {
    resetTestcaseTempDir
    createTempFile("F1.csv")

    val mt0 = SmvHDFS.modificationTime("target")
    val mt1 = SmvHDFS.modificationTime(s"${testcaseTempDir}/F1.csv")
    assert(mt0 < mt1)
  }

  test("Test HDFS file read") {
    resetTestcaseTempDir()

    createTempFile("F1", "hahahaha")
    val res = SmvHDFS.readFromFile(testcaseTempDir + "/F1")
    assert(res === "hahahaha")
  }

  test("Test HDFS file write") {
    resetTestcaseTempDir()

    SmvHDFS.writeToFile("test contents", testcaseTempDir + "/F2")
    val res = SmvHDFS.readFromFile(testcaseTempDir + "/F2")
    assert(res === "test contents")
  }

}