text:
class LinearVelocity():

    def __family__(self):
        return "LinearVelocity"

    def __getMeterPerSecondX__(self):
        raise NotImplementedError

    def __getMeterPerSecondY__(self):
        raise NotImplementedError

    def __getMeterPerSecondZ__(self):
        raise NotImplementedError

    def MeterPerSecond2KmPerHour(self, value=0):
        return value * 3.6

    def KmPerHour2MeterPerSecond(self, value=0):
        return value / 3.6

    @api("LinearVelocity", 0)
    @request("GET", "sensor/velocity/linear/*")
    @response(contentType=M_JSON)
    def linearVelocityWildcard(self):
        values = {}
        x = self.getMeterPerSecondX()
        y = self.getMeterPerSecondY()
        z = self.getMeterPerSecondZ()
        values["x.m/s"] = "%.3f" % x
        values["y.m/s"] = "%.3f" % y
        values["z.m/s"] = "%.3f" % z
        return values

    @api("LinearVelocity", 0)
    @request("GET", "sensor/velocity/speed/*")
    @response(contentType=M_JSON)
    def speedWildcard(self):
        values = {}
        x = self.MeterPerSecond2KmPerHour(self.getMeterPerSecondX())
        y = self.MeterPerSecond2KmPerHour(self.getMeterPerSecondY())
        z = self.MeterPerSecond2KmPerHour(self.getMeterPerSecondZ())
        values["x.km/h"] = "%.3f" % x
        values["y.km/h"] = "%.3f" % y
        values["z.km/h"] = "%.3f" % z
        return values

    @request("GET", "sensor/velocity/linear/x/m_s")
    @response("%.3f")
    def getMeterPerSecondX(self):
        return self.__getMeterPerSecondX__()

    @request("GET", "sensor/velocity/linear/y/m_s")
    @response("%.3f")
    def getMeterPerSecondY(self):
        return self.__getMeterPerSecondY__()

    @request("GET", "sensor/velocity/linear/z/m_s")
    @response("%.3f")
    def getMeterPerSecondZ(self):
        return self.__getMeterPerSecondZ__()

class AngularVelocity():

    def PI(self):
        return 3.141592653589793

    def __family__(self):
        return "AngularVelocity"

    def __getRadianPerSecondX__(self):
        raise NotImplementedError

    def __getRadianPerSecondY__(self):
        raise NotImplementedError

    def __getRadianPerSecondZ__(self):
        raise NotImplementedError

    def RadianPerSecond2DegreePerSecond(self, value=0):
        return value / self.PI() * 180

    def DegreePerSecond2RadianPerSecond(self, value=0):
        return value * self.PI() / 180

    def RadianPerSecond2Hertz(self, value=0):
        return value / self.PI() / 2

    def Hertz2RadianPerSecond(self, value=0):
        return value * self.PI() * 2

    @api("AngularVelocity", 0)
    @request("GET", "sensor/velocity/angular/*")
    @response(contentType=M_JSON)
    def angularVelocityWildcard(self):
        values = {}
        x = self.getRadianPerSecondX()
        y = self.getRadianPerSecondY()
        z = self.getRadianPerSecondZ()
        values["x.rad/s"] = "%.3f" % x
        values["y.rad/s"] = "%.3f" % y
        values["z.rad/s"] = "%.3f" % z
        return values

    @api("AngularVelocity", 0)
    @request("GET", "sensor/velocity/rotation/*")
    @response(contentType=M_JSON)
    def rotationWildcard(self):
        values = {}
        x = self.RadianPerSecond2Hertz(self.getRadianPerSecondX())
        y = self.RadianPerSecond2Hertz(self.getRadianPerSecondY())
        z = self.RadianPerSecond2Hertz(self.getRadianPerSecondZ())
        values["x.Hz"] = "%.3f" % x
        values["y.Hz"] = "%.3f" % y
        values["z.Hz"] = "%.3f" % z
        return values

    @request("GET", "sensor/velocity/angular/x/rad_s")
    @response("%.3f")
    def getRadianPerSecondX(self):
        return self.__getRadianPerSecondX__()

    @request("GET", "sensor/velocity/angular/y/rad_s")
    @response("%.3f")
    def getRadianPerSecondY(self):
        return self.__getRadianPerSecondY__()

    @request("GET", "sensor/velocity/angular/z/rad_s")
    @response("%.3f")
    def getRadianPerSecondZ(self):
        return self.__getRadianPerSecondZ__()

class Velocity(LinearVelocity, AngularVelocity):

    def __family__(self):
        return [LinearVelocity.__family__(self), AngularVelocity.__family__(self)]


text:
<?php

namespace vxPHP\Debug;

/**
 * custom error handling and debugging functionality
 *
 * @author Gregor Kofler
 * @version 0.3.0 2022-03-06
 */
class Debug
{
	private static bool $enabled = false;

    /**
     * activate custom debugging
     * registers error handler and exception handler
     *
     * @param int|null $reportingLevel
     * @param boolean $displayErrors
     */
	public static function enable(int $reportingLevel = null, bool $displayErrors = null): void
    {
        if (!static::$enabled) {

			static::$enabled = true;
			error_reporting(E_ALL);

			ErrorHandler::register($reportingLevel, $displayErrors);

			if (PHP_SAPI !== 'cli') {
				ExceptionHandler::register();
			}
			elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) {
				ini_set('display_errors', 1);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.soujava.exchange.ecb;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@Stateless
public class ECBRepository {

    private static final Logger LOGGER = Logger.getLogger(ECBRepository.class.getName());
    private static final int MAX_RESULT = 100;

    @PersistenceContext(unitName = "exchange-unit")
    private EntityManager entityManager;

    @Inject
    private ECBSQuery ecbsQuery;

    public void save(ECBRate rate) {
        entityManager.persist(rate);
    }

    public List<ECBRate> getRates(LocalDate date) {
        LOGGER.info("finding rates from day: " + date);
        Query query = entityManager.createQuery(ecbsQuery.getQueryRate());
        query.setParameter("time", java.sql.Date.valueOf(date));
        return query.getResultList();
    }

    public void save(List<ECBRate> rates) {
        LOGGER.info("Saving rate: " + rates.size());
        rates.forEach(this::save);
    }

    public void update(List<ECBRate> rates) {
        entityManager.merge(rates);
    }

    public boolean isNotEmpty() {
        Query query = entityManager.createNativeQuery(ecbsQuery.getCountQuery());
        Number count = (Number) query.getSingleResult();
        return count.intValue() > 0;
    }

    private Number getCountRange(LocalDate date, LocalDate date1) {
        Query query = entityManager.createNativeQuery(ecbsQuery.getCountRange());
        query.setParameter(1, java.sql.Date.valueOf(date));
        query.setParameter(2, java.sql.Date.valueOf(date1));
        return (Number) query.getSingleResult();
    }

    public ECBResult getRates(LocalDate date, LocalDate date1, int offset) {
        Query query = entityManager.createQuery(ecbsQuery.getQueryHistoric());
        query.setParameter("time", java.sql.Date.valueOf(date));
        query.setParameter("time1", java.sql.Date.valueOf(date1));
        query.setFirstResult(offset);
        query.setMaxResults(MAX_RESULT);
        int countRange = getCountRange(date, date1).intValue();
        int pos = offset + MAX_RESULT;
        if (pos >= countRange) {
            pos = countRange;
        }
        return new ECBResult(countRange, pos, query.getResultList());
    }

    public List<ECBRate> getMostRecentRates() {
        Query query = entityManager.createQuery(ecbsQuery.getDateMostRecent());
        query.setMaxResults(1);
        Date date = (Date) query.getSingleResult();
        LocalDate localDate = new java.sql.Date(date.getTime()).toLocalDate();
        return getRates(localDate);
    }
}


text:
package com.google.devtools.cdbg.debuglets.java;

/** Custom data structure corresponding to FormatMessage proto. */
final class FormatMessage {
  private final String format;
  private final String[] parameters;

  public FormatMessage(String format, String... parameters) {
    this.format = format;
    this.parameters = parameters;
  }

  public String getFormat() {
    return format;
  }

  public String[] getParameters() {
    return parameters;
  }
}


text:
package rdict // import "go-hep.org/x/hep/groot/rdict"

import (
	"fmt"
	"math"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"text/tabwriter"

	"go-hep.org/x/hep/groot/rbase"
	"go-hep.org/x/hep/groot/rbytes"
	"go-hep.org/x/hep/groot/rcont"
	"go-hep.org/x/hep/groot/rmeta"
	"go-hep.org/x/hep/groot/root"
	"go-hep.org/x/hep/groot/rtypes"
	"go-hep.org/x/hep/groot/rvers"
)

var (
	ptrSize = 4 << (^uintptr(0) >> 63)
	intSize = int(reflect.TypeOf(int(0)).Size())
)

type StreamerInfo struct {
	named  rbase.Named
	chksum uint32
	clsver int32
	objarr *rcont.ObjArray
	elems  []rbytes.StreamerElement

	init  sync.Once
	descr []elemDescr
	roops []rstreamer // read-stream object-wise operations
	woops []wstreamer // write-stream object-wise operations
	rmops []rstreamer // read-stream member-wise operations
	wmops []wstreamer // write-stream member-wise operations
}

// NewStreamerInfo creates a new StreamerInfo from Go provided informations.
func NewStreamerInfo(name string, version int, elems []rbytes.StreamerElement) *StreamerInfo {
	sinfos := &StreamerInfo{
		named:  *rbase.NewNamed(GoName2Cxx(name), "Go;"+name),
		chksum: genChecksum(name, elems),
		clsver: int32(version),
		objarr: rcont.NewObjArray(),
		elems:  elems,
	}
	return sinfos
}

// NewCxxStreamerInfo creates a new StreamerInfo from C++ provided informations.
func NewCxxStreamerInfo(name string, version int32, chksum uint32, elems []rbytes.StreamerElement) *StreamerInfo {
	sinfos := &StreamerInfo{
		named:  *rbase.NewNamed(name, ""),
		chksum: chksum,
		clsver: version,
		objarr: rcont.NewObjArray(),
		elems:  elems,
	}
	return sinfos
}

func (*StreamerInfo) RVersion() int16 { return rvers.StreamerInfo }

func (tsi *StreamerInfo) Class() string {
	return "TStreamerInfo"
}

func (tsi *StreamerInfo) Name() string {
	return tsi.named.Name()
}

func (tsi *StreamerInfo) Title() string {
	return tsi.named.Title()
}

func (tsi *StreamerInfo) CheckSum() int {
	return int(tsi.chksum)
}

func (tsi *StreamerInfo) ClassVersion() int {
	return int(tsi.clsver)
}

func (tsi *StreamerInfo) Elements() []rbytes.StreamerElement {
	return tsi.elems
}

func (tsi *StreamerInfo) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsi.Class(), tsi.RVersion())
	w.WriteObject(&tsi.named)
	w.WriteU32(tsi.chksum)
	w.WriteI32(tsi.clsver)

	if len(tsi.elems) > 0 {
		elems := make([]root.Object, len(tsi.elems))
		for i, v := range tsi.elems {
			elems[i] = v
		}
		tsi.objarr.SetElems(elems)
	}
	w.WriteObjectAny(tsi.objarr)
	tsi.objarr.SetElems(nil)

	return w.SetHeader(hdr)
}

func (tsi *StreamerInfo) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsi.Class())
	if hdr.Vers > rvers.StreamerInfo {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsi.Class(), hdr.Vers, tsi.RVersion(),
		))
	}

	r.ReadObject(&tsi.named)

	tsi.chksum = r.ReadU32()
	tsi.clsver = r.ReadI32()
	objs := r.ReadObjectAny()
	if r.Err() != nil {
		return r.Err()
	}

	tsi.objarr = objs.(*rcont.ObjArray)
	tsi.elems = nil
	if tsi.objarr.Len() > 0 {
		tsi.elems = make([]rbytes.StreamerElement, tsi.objarr.Len())
		for i := range tsi.elems {
			elem := tsi.objarr.At(i)
			tsi.elems[i] = elem.(rbytes.StreamerElement)
		}
	}
	tsi.objarr.SetElems(nil)

	r.CheckHeader(hdr)
	return r.Err()
}

func (si *StreamerInfo) String() string {
	o := new(strings.Builder)
	fmt.Fprintf(o, " StreamerInfo for %q version=%d title=%q\n", si.Name(), si.ClassVersion(), si.Title())
	w := tabwriter.NewWriter(o, 8, 4, 1, ' ', 0)
	for _, elm := range si.Elements() {
		fmt.Fprintf(w, "  %s\t%s\toffset=%3d\ttype=%3d\tsize=%3d\t %s\n", elm.TypeName(), elm.Name(), elm.Offset(), elm.Type(), elm.Size(), elm.Title())
	}
	w.Flush()
	return o.String()

}

// BuildStreamers builds the r/w streamers.
func (si *StreamerInfo) BuildStreamers() error {
	var err error
	si.init.Do(func() {
		err = si.build(StreamerInfos)
	})
	return err
}

func (si *StreamerInfo) build(sictx rbytes.StreamerInfoContext) error {
	si.descr = make([]elemDescr, 0, len(si.elems))
	si.roops = make([]rstreamer, 0, len(si.elems))
	si.woops = make([]wstreamer, 0, len(si.elems))
	si.rmops = make([]rstreamer, 0, len(si.elems))
	si.wmops = make([]wstreamer, 0, len(si.elems))

	for i, se := range si.elems {
		class := strings.TrimRight(se.TypeName(), "*")
		method := func() []int {
			var cname string
			switch se := se.(type) {
			case *StreamerBasicPointer:
				cname = se.CountName()
			case *StreamerLoop:
				cname = se.CountName()
				if se.cclass != si.Name() {
					// reaching into another class internals isn't supported (yet?) in groot
					panic(fmt.Errorf("rdict: unsupported StreamerLoop case: si=%q, se=%q, count=%q, class=%q",
						si.Name(), se.Name(), cname, se.cclass,
					))
				}
			default:
				return []int{0}
			}

			return si.findField(sictx, cname, se, nil)
		}()

		if method == nil {
			return fmt.Errorf("rdict: could not find count-offset for element %q in streamer %q (se=%T)", se.Name(), si.Name(), se)
		}

		descr := elemDescr{
			otype:  se.Type(),
			ntype:  se.Type(), // FIXME(sbinet): handle schema evolution
			offset: i,         // FIXME(sbinet): make sure this works (instead of se.Offset())
			length: se.ArrayLen(),
			elem:   se,
			method: method, // FIXME(sbinet): schema evolution (old/new class may not have the same "offsets")
			oclass: class,  // FIXME(sbinet): impl.
			nclass: class,  // FIXME(sbinet): impl. + schema evolution
			mbr:    nil,    // FIXME(sbinet): impl
		}

		si.descr = append(si.descr, descr)
	}

	for i, descr := range si.descr {
		si.roops = append(si.roops, si.makeROp(sictx, i, descr))
		si.woops = append(si.woops, si.makeWOp(sictx, i, descr))
		// FIXME(sbinet): handle member-wise r/w ops
		// si.rmops
		// si.wmops
	}

	return nil
}

func (si *StreamerInfo) NewDecoder(kind rbytes.StreamKind, r *rbytes.RBuffer) (rbytes.Decoder, error) {
	err := si.BuildStreamers()
	if err != nil {
		return nil, fmt.Errorf("rdict: could not build read streamers: %w", err)
	}

	switch kind {
	case rbytes.ObjectWise:
		return newDecoder(r, si, kind, si.roops)
	case rbytes.MemberWise:
		return newDecoder(r, si, kind, si.rmops)
	default:
		return nil, fmt.Errorf("rdict: invalid stream kind %v", kind)
	}
}

func (si *StreamerInfo) NewEncoder(kind rbytes.StreamKind, w *rbytes.WBuffer) (rbytes.Encoder, error) {
	err := si.BuildStreamers()
	if err != nil {
		return nil, fmt.Errorf("rdict: could not build write streamers: %w", err)
	}

	switch kind {
	case rbytes.ObjectWise:
		return newEncoder(w, si, kind, si.woops)
	case rbytes.MemberWise:
		return newEncoder(w, si, kind, si.wmops)
	default:
		return nil, fmt.Errorf("rdict: invalid stream kind %v", kind)
	}
}

func (si *StreamerInfo) NewRStreamer(kind rbytes.StreamKind) (rbytes.RStreamer, error) {
	err := si.BuildStreamers()
	if err != nil {
		return nil, fmt.Errorf("rdict: could not build read streamers: %w", err)
	}

	roops := make([]rstreamer, len(si.descr))
	switch kind {
	case rbytes.ObjectWise:
		copy(roops, si.roops)
	case rbytes.MemberWise:
		copy(roops, si.rmops)
	default:
		return nil, fmt.Errorf("rdict: invalid stream kind %v", kind)
	}
	return newRStreamerInfo(si, kind, roops)
}

func (si *StreamerInfo) NewWStreamer(kind rbytes.StreamKind) (rbytes.WStreamer, error) {
	err := si.BuildStreamers()
	if err != nil {
		return nil, fmt.Errorf("rdict: could not build write streamers: %w", err)
	}

	wops := make([]wstreamer, len(si.descr))
	switch kind {
	case rbytes.ObjectWise:
		copy(wops, si.woops)
	case rbytes.MemberWise:
		copy(wops, si.wmops)
	default:
		return nil, fmt.Errorf("rdict: invalid stream kind %v", kind)
	}
	return newWStreamerInfo(si, kind, wops)
}

func (si *StreamerInfo) findField(ctx rbytes.StreamerInfoContext, name string, se rbytes.StreamerElement, offset []int) []int {
	for j := range si.elems {
		if si.elems[j].Name() == name {
			offset = append(offset, j)
			return offset
		}
	}

	// look into base classes, if any.
	for j, bse := range si.elems {
		switch bse := bse.(type) {
		case *StreamerBase:
			base, err := ctx.StreamerInfo(bse.Name(), -1)
			if err != nil {
				panic(fmt.Errorf("rdict: could not find base class %q of %q: %w", se.Name(), si.Name(), err))
			}
			boffset := base.(*StreamerInfo).findField(ctx, name, se, nil)
			if boffset != nil {
				return append(append(offset, j), boffset...)
			}
		}
	}

	return nil
}

type Element struct {
	Name   rbase.Named
	Type   rmeta.Enum // element type
	Size   int32      // size of element
	ArrLen int32      // cumulative size of all array dims
	ArrDim int32      // number of array dimensions
	MaxIdx [5]int32   // maximum array index for array dimension "dim"
	Offset int32      // element offset in class
	EName  string     // data type name of data member
	XMin   float64    // minimum of data member if a range is specified [xmin.xmax.nbits]
	XMax   float64    // maximum of data member if a range is specified [xmin.xmax.nbits]
	Factor float64    // conversion factor if a range is specified. factor = (1<<nbits/(xmax-xmin))
}

func (e Element) New() StreamerElement {
	e.parse()
	return StreamerElement{
		named:  e.Name,
		etype:  e.Type,
		esize:  e.Size,
		arrlen: e.ArrLen,
		arrdim: e.ArrDim,
		maxidx: e.MaxIdx,
		offset: e.Offset,
		ename:  e.EName,
		xmin:   e.XMin,
		xmax:   e.XMax,
		factor: e.Factor,
	}
}

// parse parses the element's title for ROOT meta-data information (range, factor, ...)
func (e *Element) parse() {
	switch e.Type {
	case rmeta.Float16, rmeta.OffsetL + rmeta.Float16, rmeta.OffsetP + rmeta.Float16:
		e.XMin, e.XMax, e.Factor = e.getRange(e.Name.Title())
	case rmeta.Double32, rmeta.OffsetL + rmeta.Double32, rmeta.OffsetP + rmeta.Double32:
		e.XMin, e.XMax, e.Factor = e.getRange(e.Name.Title())
	}
}

func (Element) getRange(str string) (xmin, xmax, factor float64) {
	if str == "" {
		return xmin, xmax, factor
	}
	beg := strings.LastIndex(str, "[")
	if beg < 0 {
		return xmin, xmax, factor
	}
	if beg > 0 {
		// make sure there is a '/' in-between
		// make sure the slash is just one position before.
		slash := strings.LastIndex(str[:beg], "/")
		if slash < 0 || slash+2 != beg {
			return xmin, xmax, factor
		}
	}
	end := strings.LastIndex(str, "]")
	if end < 0 {
		return xmin, xmax, factor
	}
	str = str[beg+1 : end]
	if !strings.Contains(str, ",") {
		return xmin, xmax, factor
	}

	toks := strings.Split(str, ",")
	for i, tok := range toks {
		toks[i] = strings.ToLower(strings.TrimSpace(tok))
	}

	switch len(toks) {
	case 2, 3:
	default:
		panic(fmt.Errorf("rdict: invalid ROOT range specification (too many commas): %q", str))
	}

	var nbits uint32 = 32
	if len(toks) == 3 {
		n, err := strconv.ParseUint(toks[2], 10, 32)
		if err != nil {
			panic(fmt.Errorf("rdict: could not parse nbits specification %q: %w", str, err))
		}
		nbits = uint32(n)
		if nbits < 2 || nbits > 32 {
			panic(fmt.Errorf("rdict: illegal nbits specification (nbits=%d outside of range [2,32])", nbits))
		}
	}

	fct := func(s string) float64 {
		switch {
		case strings.Contains(s, "pi"):
			var f float64
			switch {
			case strings.Contains(s, "2pi"), strings.Contains(s, "2*pi"), strings.Contains(s, "twopi"):
				f = 2 * math.Pi
			case strings.Contains(s, "pi/2"):
				f = math.Pi / 2
			case strings.Contains(s, "pi/4"):
				f = math.Pi / 4
			case strings.Contains(s, "pi"):
				f = math.Pi
			}
			if strings.Contains(s, "-") {
				f = -f
			}
			return f
		default:
			f, err := strconv.ParseFloat(s, 64)
			if err != nil {
				panic(fmt.Errorf("rdict: could not parse range value %q: %w", s, err))
			}
			return f
		}
	}

	xmin = fct(toks[0])
	xmax = fct(toks[1])

	var bigint uint32
	switch {
	case nbits < 32:
		bigint = 1 << nbits
	default:
		bigint = 0xffffffff
	}
	if xmin < xmax {
		factor = float64(bigint) / (xmax - xmin)
	}
	if xmin >= xmax && nbits < 15 {
		xmin = float64(nbits) + 0.1
	}
	return xmin, xmax, factor
}

type StreamerElement struct {
	named  rbase.Named
	etype  rmeta.Enum // element type
	esize  int32      // size of element
	arrlen int32      // cumulative size of all array dims
	arrdim int32      // number of array dimensions
	maxidx [5]int32   // maximum array index for array dimension "dim"
	offset int32      // element offset in class
	ename  string     // data type name of data member
	xmin   float64    // minimum of data member if a range is specified [xmin.xmax.nbits]
	xmax   float64    // maximum of data member if a range is specified [xmin.xmax.nbits]
	factor float64    // conversion factor if a range is specified. factor = (1<<nbits/(xmax-xmin))
}

func (*StreamerElement) RVersion() int16 { return rvers.StreamerElement }

func (tse *StreamerElement) Class() string {
	return "TStreamerElement"
}

func (tse *StreamerElement) Name() string {
	return tse.named.Name()
}

func (tse *StreamerElement) Title() string {
	return tse.named.Title()
}

func (tse *StreamerElement) ArrayDim() int {
	return int(tse.arrdim)
}

func (tse *StreamerElement) ArrayDims() []int32 {
	return tse.maxidx[:tse.arrdim]
}

func (tse *StreamerElement) ArrayLen() int {
	return int(tse.arrlen)
}

func (tse *StreamerElement) Type() rmeta.Enum {
	return tse.etype
}

func (tse *StreamerElement) Offset() uintptr {
	return uintptr(tse.offset)
}

func (tse *StreamerElement) Size() uintptr {
	return uintptr(tse.esize)
}

func (tse *StreamerElement) TypeName() string {
	return tse.ename
}

func (tse *StreamerElement) XMin() float64 {
	return tse.xmin
}

func (tse *StreamerElement) XMax() float64 {
	return tse.xmax
}

func (tse *StreamerElement) Factor() float64 {
	return tse.factor
}

func (tse *StreamerElement) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tse.Class(), tse.RVersion())
	w.WriteObject(&tse.named)
	w.WriteI32(int32(tse.etype))
	w.WriteI32(tse.esize)
	w.WriteI32(tse.arrlen)
	w.WriteI32(tse.arrdim)
	w.WriteArrayI32(tse.maxidx[:])
	w.WriteString(tse.ename)

	switch {
	case tse.RVersion() == 3:
		w.WriteF64(tse.xmin)
		w.WriteF64(tse.xmax)
		w.WriteF64(tse.factor)
	case tse.RVersion() > 3:
		// FIXME(sbinet)
		// if (TestBit(kHasRange)) GetRange(GetTitle(),fXmin,fXmax,fFactor)
	}

	return w.SetHeader(hdr)
}

func (tse *StreamerElement) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tse.Class())
	if hdr.Vers > rvers.StreamerElement {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tse.Class(), hdr.Vers, tse.RVersion(),
		))
	}

	r.ReadObject(&tse.named)

	tse.etype = rmeta.Enum(r.ReadI32())
	tse.esize = r.ReadI32()
	tse.arrlen = r.ReadI32()
	tse.arrdim = r.ReadI32()
	if hdr.Vers == 1 {
		copy(tse.maxidx[:], r.ReadStaticArrayI32())
	} else {
		r.ReadArrayI32(tse.maxidx[:])
	}
	tse.ename = r.ReadString()

	if tse.etype == 11 && (tse.ename == "Bool_t" || tse.ename == "bool") {
		tse.etype = 18
	}

	// if vers <= 2 {
	// 	// FIXME(sbinet)
	// 	// tse.esize = tse.arrlen * gROOT->GetType(GetTypeName())->Size()
	// }
	switch {
	default:
		tse.xmin = 0
		tse.xmax = 0
		tse.factor = 0
	case hdr.Vers == 3:
		tse.xmin = r.ReadF64()
		tse.xmax = r.ReadF64()
		tse.factor = r.ReadF64()
	case hdr.Vers > 3:
		tse.xmin, tse.xmax, tse.factor = Element{}.getRange(tse.Title())
	}

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerBase struct {
	StreamerElement
	vbase int32 // version number of the base class
}

func NewStreamerBase(se StreamerElement, vbase int32) *StreamerBase {
	return &StreamerBase{StreamerElement: se, vbase: vbase}
}

func (*StreamerBase) RVersion() int16 { return rvers.StreamerBase }

func (tsb *StreamerBase) Class() string {
	return "TStreamerBase"
}

// Base returns the base class' version.
func (tsb *StreamerBase) Base() int {
	return int(tsb.vbase)
}

func (tsb *StreamerBase) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsb.Class(), tsb.RVersion())
	w.WriteObject(&tsb.StreamerElement)
	w.WriteI32(tsb.vbase)

	return w.SetHeader(hdr)
}

func (tsb *StreamerBase) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsb.Class())
	if hdr.Vers > rvers.StreamerBase {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsb.Class(), hdr.Vers, tsb.RVersion(),
		))
	}

	r.ReadObject(&tsb.StreamerElement)

	if hdr.Vers > 2 {
		tsb.vbase = r.ReadI32()
	}

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerBasicType struct {
	StreamerElement
}

func (*StreamerBasicType) RVersion() int16 { return rvers.StreamerBasicType }

func (tsb *StreamerBasicType) Class() string {
	return "TStreamerBasicType"
}

func (tsb *StreamerBasicType) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsb.Class(), tsb.RVersion())
	w.WriteObject(&tsb.StreamerElement)

	return w.SetHeader(hdr)
}

func (tsb *StreamerBasicType) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsb.Class())
	if hdr.Vers > rvers.StreamerBasicType {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsb.Class(), hdr.Vers, tsb.RVersion(),
		))
	}

	r.ReadObject(&tsb.StreamerElement)

	etype := tsb.StreamerElement.etype
	if rmeta.OffsetL < etype && etype < rmeta.OffsetP {
		etype -= rmeta.OffsetL
	}

	basic := true
	switch etype {
	case rmeta.Bool, rmeta.UChar, rmeta.Char:
		tsb.StreamerElement.esize = 1
	case rmeta.UShort, rmeta.Short:
		tsb.StreamerElement.esize = 2
	case rmeta.Bits, rmeta.UInt, rmeta.Int, rmeta.Counter:
		tsb.StreamerElement.esize = 4
	case rmeta.ULong, rmeta.ULong64, rmeta.Long, rmeta.Long64:
		tsb.StreamerElement.esize = 8
	case rmeta.Float, rmeta.Float16:
		tsb.StreamerElement.esize = 4
	case rmeta.Double, rmeta.Double32:
		tsb.StreamerElement.esize = 8
	case rmeta.CharStar:
		tsb.StreamerElement.esize = int32(ptrSize)
	default:
		basic = false
	}
	if basic && tsb.StreamerElement.arrlen > 0 {
		tsb.StreamerElement.esize *= tsb.StreamerElement.arrlen
	}

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerBasicPointer struct {
	StreamerElement
	cvers int32  // version number of the class with the counter
	cname string // name of data member holding the array count
	ccls  string // name of the class with the counter
}

func NewStreamerBasicPointer(se StreamerElement, cvers int32, cname, ccls string) *StreamerBasicPointer {
	return &StreamerBasicPointer{
		StreamerElement: se,
		cvers:           cvers,
		cname:           cname,
		ccls:            ccls,
	}
}

func (*StreamerBasicPointer) RVersion() int16 { return rvers.StreamerBasicPointer }

func (tsb *StreamerBasicPointer) Class() string {
	return "TStreamerBasicPointer"
}

func (tsb *StreamerBasicPointer) CountName() string {
	return tsb.cname
}

func (tsb *StreamerBasicPointer) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsb.Class(), tsb.RVersion())
	w.WriteObject(&tsb.StreamerElement)
	w.WriteI32(tsb.cvers)
	w.WriteString(tsb.cname)
	w.WriteString(tsb.ccls)

	return w.SetHeader(hdr)
}

func (tsb *StreamerBasicPointer) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsb.Class())
	if hdr.Vers > rvers.StreamerBasicPointer {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsb.Class(), hdr.Vers, tsb.RVersion(),
		))
	}

	r.ReadObject(&tsb.StreamerElement)

	tsb.cvers = r.ReadI32()
	tsb.cname = r.ReadString()
	tsb.ccls = r.ReadString()

	r.CheckHeader(hdr)
	return r.Err()
}

// StreamerLoop represents a streamer for a var-length array of a non-basic type.
type StreamerLoop struct {
	StreamerElement
	cvers  int32  // version number of the class with the counter
	cname  string // name of data member holding the array count
	cclass string // name of the class with the counter
}

func NewStreamerLoop(se StreamerElement, cvers int32, cname, cclass string) *StreamerLoop {
	se.etype = rmeta.StreamLoop
	return &StreamerLoop{
		StreamerElement: se,
		cvers:           cvers,
		cname:           cname,
		cclass:          cclass,
	}
}

func (*StreamerLoop) RVersion() int16 { return rvers.StreamerLoop }

func (*StreamerLoop) Class() string {
	return "TStreamerLoop"
}

func (tsl *StreamerLoop) CountName() string {
	return tsl.cname
}

func (tsl *StreamerLoop) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsl.Class(), tsl.RVersion())
	w.WriteObject(&tsl.StreamerElement)
	w.WriteI32(tsl.cvers)
	w.WriteString(tsl.cname)
	w.WriteString(tsl.cclass)

	return w.SetHeader(hdr)
}

func (tsl *StreamerLoop) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsl.Class())
	if hdr.Vers > rvers.StreamerLoop {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsl.Class(), hdr.Vers, tsl.RVersion(),
		))
	}

	r.ReadObject(&tsl.StreamerElement)
	tsl.cvers = r.ReadI32()
	tsl.cname = r.ReadString()
	tsl.cclass = r.ReadString()

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerObject struct {
	StreamerElement
}

func (*StreamerObject) RVersion() int16 { return rvers.StreamerObject }

func (tso *StreamerObject) Class() string {
	return "TStreamerObject"
}

func (tso *StreamerObject) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tso.Class(), tso.RVersion())
	w.WriteObject(&tso.StreamerElement)
	return w.SetHeader(hdr)
}

func (tso *StreamerObject) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tso.Class())
	if hdr.Vers > rvers.StreamerObject {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tso.Class(), hdr.Vers, tso.RVersion(),
		))
	}

	r.ReadObject(&tso.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerObjectPointer struct {
	StreamerElement
}

func (*StreamerObjectPointer) RVersion() int16 { return rvers.StreamerObjectPointer }

func (tso *StreamerObjectPointer) Class() string {
	return "TStreamerObjectPointer"
}

func (tso *StreamerObjectPointer) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tso.Class(), tso.RVersion())
	w.WriteObject(&tso.StreamerElement)
	return w.SetHeader(hdr)
}

func (tso *StreamerObjectPointer) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tso.Class())
	if hdr.Vers > rvers.StreamerObjectPointer {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tso.Class(), hdr.Vers, tso.RVersion(),
		))
	}

	r.ReadObject(&tso.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerObjectAny struct {
	StreamerElement
}

func (*StreamerObjectAny) RVersion() int16 { return rvers.StreamerObjectAny }

func (tso *StreamerObjectAny) Class() string {
	return "TStreamerObjectAny"
}

func (tso *StreamerObjectAny) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tso.Class(), tso.RVersion())
	w.WriteObject(&tso.StreamerElement)

	return w.SetHeader(hdr)
}

func (tso *StreamerObjectAny) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tso.Class())
	if hdr.Vers > rvers.StreamerObjectAny {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tso.Class(), hdr.Vers, tso.RVersion(),
		))
	}

	r.ReadObject(&tso.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerObjectAnyPointer struct {
	StreamerElement
}

func (*StreamerObjectAnyPointer) RVersion() int16 { return rvers.StreamerObjectAnyPointer }

func (tso *StreamerObjectAnyPointer) Class() string {
	return "TStreamerObjectAnyPointer"
}

func (tso *StreamerObjectAnyPointer) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tso.Class(), tso.RVersion())
	w.WriteObject(&tso.StreamerElement)

	return w.SetHeader(hdr)
}

func (tso *StreamerObjectAnyPointer) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tso.Class())
	if hdr.Vers > rvers.StreamerObjectAnyPointer {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tso.Class(), hdr.Vers, tso.RVersion(),
		))
	}

	r.ReadObject(&tso.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerString struct {
	StreamerElement
}

func (*StreamerString) RVersion() int16 { return rvers.StreamerString }

func (tss *StreamerString) Class() string {
	return "TStreamerString"
}

func (tss *StreamerString) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tss.Class(), tss.RVersion())
	w.WriteObject(&tss.StreamerElement)

	return w.SetHeader(hdr)
}

func (tss *StreamerString) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tss.Class())
	if hdr.Vers > rvers.StreamerString {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tss.Class(), hdr.Vers, tss.RVersion(),
		))
	}

	r.ReadObject(&tss.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerSTL struct {
	StreamerElement
	vtype rmeta.ESTLType // type of STL vector
	ctype rmeta.Enum     // STL contained type
}

func NewStreamerSTL(name string, vtype rmeta.ESTLType, ctype rmeta.Enum) *StreamerSTL {
	return &StreamerSTL{
		StreamerElement: StreamerElement{
			named: *rbase.NewNamed(name, ""),
			esize: int32(ptrSize + 2*intSize),
			ename: rmeta.STLNameFrom(name, vtype, ctype),
			etype: rmeta.Streamer,
		},
		vtype: vtype,
		ctype: ctype,
	}
}

// NewCxxStreamerSTL creates a new StreamerSTL from C++ informations.
func NewCxxStreamerSTL(se StreamerElement, vtype rmeta.ESTLType, ctype rmeta.Enum) *StreamerSTL {
	return &StreamerSTL{
		StreamerElement: se,
		vtype:           vtype,
		ctype:           ctype,
	}
}

func (*StreamerSTL) RVersion() int16 { return rvers.StreamerSTL }

func (tss *StreamerSTL) Class() string {
	return "TStreamerSTL"
}

func (tss *StreamerSTL) ElemTypeName() []string {
	return rmeta.CxxTemplateFrom(tss.ename).Args
}

func (tss *StreamerSTL) ContainedType() rmeta.Enum {
	return tss.ctype
}

func (tss *StreamerSTL) STLType() rmeta.ESTLType {
	return tss.vtype
}

func (tss *StreamerSTL) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tss.Class(), tss.RVersion())
	w.WriteObject(&tss.StreamerElement)
	w.WriteI32(int32(tss.vtype))
	w.WriteI32(int32(tss.ctype))

	return w.SetHeader(hdr)
}

func (tss *StreamerSTL) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tss.Class())
	if hdr.Vers > rvers.StreamerSTL {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tss.Class(), hdr.Vers, tss.RVersion(),
		))
	}

	r.ReadObject(&tss.StreamerElement)

	tss.vtype = rmeta.ESTLType(r.ReadI32())
	tss.ctype = rmeta.Enum(r.ReadI32())

	if tss.vtype == rmeta.STLmultimap || tss.vtype == rmeta.STLset {
		switch {
		case strings.HasPrefix(tss.StreamerElement.ename, "std::set") || strings.HasPrefix(tss.StreamerElement.ename, "set"):
			tss.vtype = rmeta.STLset
		case strings.HasPrefix(tss.StreamerElement.ename, "std::multimap") || strings.HasPrefix(tss.StreamerElement.ename, "multimap"):
			tss.vtype = rmeta.STLmultimap
		}
	}

	r.CheckHeader(hdr)
	return r.Err()
}

// func (tss *StreamerSTL) isaPointer() bool {
// 	tname := tss.StreamerElement.ename
// 	return strings.HasSuffix(tname, "*")
// }

type StreamerSTLstring struct {
	StreamerSTL
}

func (*StreamerSTLstring) RVersion() int16 { return rvers.StreamerSTLstring }

func (tss *StreamerSTLstring) Class() string {
	return "TStreamerSTLstring"
}

func (tss *StreamerSTLstring) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tss.Class(), tss.RVersion())
	w.WriteObject(&tss.StreamerSTL)

	return w.SetHeader(hdr)
}

func (tss *StreamerSTLstring) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tss.Class())
	if hdr.Vers > rvers.StreamerSTLstring {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tss.Class(), hdr.Vers, tss.RVersion(),
		))
	}

	r.ReadObject(&tss.StreamerSTL)

	r.CheckHeader(hdr)
	return r.Err()
}

type StreamerArtificial struct {
	StreamerElement
}

func (*StreamerArtificial) RVersion() int16 { return rvers.StreamerArtificial }

func (tss *StreamerArtificial) Class() string {
	return "TStreamerArtificial"
}

func (tsa *StreamerArtificial) MarshalROOT(w *rbytes.WBuffer) (int, error) {
	if w.Err() != nil {
		return 0, w.Err()
	}

	hdr := w.WriteHeader(tsa.Class(), tsa.RVersion())
	w.WriteObject(&tsa.StreamerElement)

	return w.SetHeader(hdr)
}

func (tsa *StreamerArtificial) UnmarshalROOT(r *rbytes.RBuffer) error {
	if r.Err() != nil {
		return r.Err()
	}

	hdr := r.ReadHeader(tsa.Class())
	if hdr.Vers > rvers.StreamerArtificial {
		panic(fmt.Errorf(
			"rdict: invalid %s version=%d > %d",
			tsa.Class(), hdr.Vers, tsa.RVersion(),
		))
	}

	r.ReadObject(&tsa.StreamerElement)

	r.CheckHeader(hdr)
	return r.Err()
}

func genChecksum(name string, elems []rbytes.StreamerElement) uint32 {
	var (
		id   uint32
		hash = func(s string) {
			for _, v := range []byte(s) {
				id = id*3 + uint32(v)
			}
		}
	)

	hash(name)

	// FIXME(sbinet): handle base-classes for std::pair<K,V>
	for _, se := range elems {
		//if se, ok := se.(*StreamerBase); ok {
		//	// FIXME(sbinet): get base checksum.
		//}

		// FIXME(sbinet): add enum handling.
		hash(se.Name())
		hash(se.TypeName())

		for _, v := range se.ArrayDims() {
			id = id*3 + uint32(v)
		}
		title := se.Title()
		beg := strings.Index(title, "[")
		if beg != 0 {
			continue
		}
		end := strings.Index(title, "]")
		hash(title[1:end])
	}

	return id
}

func init() {
	{
		f := func() reflect.Value {
			o := &StreamerInfo{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerInfo", f)
	}

	{
		f := func() reflect.Value {
			o := &StreamerElement{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerElement", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerBase{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerBase", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerBasicType{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerBasicType", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerBasicPointer{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerBasicPointer", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerLoop{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerLoop", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerObject{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerObject", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerObjectPointer{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerObjectPointer", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerObjectAny{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerObjectAny", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerObjectAnyPointer{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerObjectAnyPointer", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerString{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerString", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerSTL{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerSTL", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerSTLstring{
				StreamerSTL: StreamerSTL{
					vtype: rmeta.STLany,
					ctype: rmeta.STLstring,
				},
			}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerSTLstring", f)
	}
	{
		f := func() reflect.Value {
			o := &StreamerArtificial{}
			return reflect.ValueOf(o)
		}
		rtypes.Factory.Add("TStreamerArtificial", f)
	}
}

var (
	_ root.Object         = (*StreamerInfo)(nil)
	_ root.Named          = (*StreamerInfo)(nil)
	_ rbytes.StreamerInfo = (*StreamerInfo)(nil)
	_ rbytes.Marshaler    = (*StreamerInfo)(nil)
	_ rbytes.Unmarshaler  = (*StreamerInfo)(nil)

	_ root.Object            = (*StreamerElement)(nil)
	_ root.Named             = (*StreamerElement)(nil)
	_ rbytes.StreamerElement = (*StreamerElement)(nil)
	_ rbytes.Marshaler       = (*StreamerElement)(nil)
	_ rbytes.Unmarshaler     = (*StreamerElement)(nil)

	_ root.Object            = (*StreamerBase)(nil)
	_ root.Named             = (*StreamerBase)(nil)
	_ rbytes.StreamerElement = (*StreamerBase)(nil)
	_ rbytes.Marshaler       = (*StreamerBase)(nil)
	_ rbytes.Unmarshaler     = (*StreamerBase)(nil)

	_ root.Object            = (*StreamerBasicType)(nil)
	_ root.Named             = (*StreamerBasicType)(nil)
	_ rbytes.StreamerElement = (*StreamerBasicType)(nil)
	_ rbytes.Marshaler       = (*StreamerBasicType)(nil)
	_ rbytes.Unmarshaler     = (*StreamerBasicType)(nil)

	_ root.Object            = (*StreamerBasicPointer)(nil)
	_ root.Named             = (*StreamerBasicPointer)(nil)
	_ rbytes.StreamerElement = (*StreamerBasicPointer)(nil)
	_ rbytes.Marshaler       = (*StreamerBasicPointer)(nil)
	_ rbytes.Unmarshaler     = (*StreamerBasicPointer)(nil)

	_ root.Object            = (*StreamerLoop)(nil)
	_ root.Named             = (*StreamerLoop)(nil)
	_ rbytes.StreamerElement = (*StreamerLoop)(nil)
	_ rbytes.Marshaler       = (*StreamerLoop)(nil)
	_ rbytes.Unmarshaler     = (*StreamerLoop)(nil)

	_ root.Object            = (*StreamerObject)(nil)
	_ root.Named             = (*StreamerObject)(nil)
	_ rbytes.StreamerElement = (*StreamerObject)(nil)
	_ rbytes.Marshaler       = (*StreamerObject)(nil)
	_ rbytes.Unmarshaler     = (*StreamerObject)(nil)

	_ root.Object            = (*StreamerObjectPointer)(nil)
	_ root.Named             = (*StreamerObjectPointer)(nil)
	_ rbytes.StreamerElement = (*StreamerObjectPointer)(nil)
	_ rbytes.Marshaler       = (*StreamerObjectPointer)(nil)
	_ rbytes.Unmarshaler     = (*StreamerObjectPointer)(nil)

	_ root.Object            = (*StreamerObjectAny)(nil)
	_ root.Named             = (*StreamerObjectAny)(nil)
	_ rbytes.StreamerElement = (*StreamerObjectAny)(nil)
	_ rbytes.Marshaler       = (*StreamerObjectAny)(nil)
	_ rbytes.Unmarshaler     = (*StreamerObjectAny)(nil)

	_ root.Object            = (*StreamerString)(nil)
	_ root.Named             = (*StreamerString)(nil)
	_ rbytes.StreamerElement = (*StreamerString)(nil)
	_ rbytes.Marshaler       = (*StreamerString)(nil)
	_ rbytes.Unmarshaler     = (*StreamerString)(nil)

	_ root.Object            = (*StreamerSTL)(nil)
	_ root.Named             = (*StreamerSTL)(nil)
	_ rbytes.StreamerElement = (*StreamerSTL)(nil)
	_ rbytes.Marshaler       = (*StreamerSTL)(nil)
	_ rbytes.Unmarshaler     = (*StreamerSTL)(nil)

	_ root.Object            = (*StreamerSTLstring)(nil)
	_ root.Named             = (*StreamerSTLstring)(nil)
	_ rbytes.StreamerElement = (*StreamerSTLstring)(nil)
	_ rbytes.Marshaler       = (*StreamerSTLstring)(nil)
	_ rbytes.Unmarshaler     = (*StreamerSTLstring)(nil)

	_ root.Object            = (*StreamerArtificial)(nil)
	_ root.Named             = (*StreamerArtificial)(nil)
	_ rbytes.StreamerElement = (*StreamerArtificial)(nil)
	_ rbytes.Marshaler       = (*StreamerArtificial)(nil)
	_ rbytes.Unmarshaler     = (*StreamerArtificial)(nil)
)


text:
import React, { Component } from 'react';
import { connect } from 'nectarine';
import SearchHeader from '../../components/SearchForm/searchHeader.js';
/* eslint-disable */

//registration form
class Register extends Component {
  constructor(props) {
    super(props);
    var cDate = new Date();

    this.state = {
        //Account Information
        uname: '',
        cid: '',
        //Student Information
        fname: '',
        lname: '',
        NSHE:'',
        email: '',
        pnum:'',
        vColor:'',
        vYear: '',
        vLic:'',
        vMake:'',
        vModel:'',
        permitType: 'student',
        //Date
        curDate: (cDate.getMonth()+1).toString() + '-' + cDate.getDate().toString() + '-' + cDate.getFullYear().toString(),
        futDate: (cDate.getMonth()+1).toString() + '-' + cDate.getDate().toString() + '-' + (cDate.getFullYear()+1).toString()
    };
  }

  handleChange = (event) => {
    const target = event.target;
    const value = target.value
    const name = target.name;
    this.setState({
        [name]:value
    });
  }

  handleSubmit = (event) => {
      var confirmation = confirm('Is this information correct? \n\n' +
      'Username: ' + this.state.uname + '\n' +
      'Card ID: ' + parseInt(this.state.cid) + '\n' +
      'Name: '+ this.state.fname +' '+this.state.lname+'\n'+
      'NSHE: ' + parseInt(this.state.NSHE) + '\n'+
      'Email: '+ this.state.email + '\n'+
      'Phone Number: ' + parseInt(this.state.pnum) + '\n' +
      'Vehicle: ' + this.state.vColor + ' ' + this.state.vMake + ' ' + this.state.vModel + '\n'+
      'License: ' + this.state.vLic + '\n'+
      'Permit Type: ' + this.state.permitType + '\n' +
      'Current Date: ' + this.state.curDate + '\n' +
      'Expire Date: ' + this.state.futDate )

    if (confirmation) {
      if (this.checkUser(this.state.NSHE)) {
        this.registerUser();
        alert('User registered successfully!');
      }
      else {
        alert(this.state.NSHE + ' already exists!\n\nNo account created.');
      }
    }
    else {
      //Do nothing, allow user to fix input
    }
    event.preventDefault();
  }

  checkUser(userID){
    console.log('Requested to view a user');
    var data = {
      client: "Admin",
      flag: "viewUser",
      userID: parseInt(userID)
    }

  	this.props.sessionSocket.emit('client', data);
    this.props.sessionSocket.on('userInfo', (info)=>{
      console.log('Listening for info');
      console.log(info);
			if (info === null) {
				return true;
			}
			else {
				return false;
			}
    });
  }

  registerUser(){
    var vInt = 1;

    var data ={
      client: "Admin",
      username: this.state.uname,
      userID: parseInt(this.state.NSHE),
      cardID: parseInt(this.state.cid),
      firstName: this.state.fname,
      lastName: this.state.lname,
      email: this.state.email,
      phone: parseInt(this.state.pnum),
      gotPermit: true,
      permitType: this.state.permitType,
      purchaseDate: this.state.curDate,
      expDate: this.state.futDate,
      type: this.state.permitType,
      vehicleInt: vInt,
      v1_year: parseInt(this.state.vYear),
      v1_make: this.state.vMake,
      v1_model: this.state.vModel,
      v1_color: this.state.vColor,
      v1_plate: this.state.vLic,
      v2_year: 2012,
      v2_make: "Honda",
      v2_model: "Civic",
      v2_color: "Red",
      v2_plate: "licensePlate2",
      flag: "register"
    };

    if(vInt===1){
      data.v2_year = null;
      data.v2_make = null;
      data.v2_model = null;
      data.v2_color = null;
      data.v2_plate = null;
    }

    this.props.sessionSocket.emit('client', data);
    console.log('Sent data to server');
  }

    //EXECUTION TIME!
  render() {
    return (

        <SearchHeader activeName={this.props.pageName} description={this.props.pgDescription} />

New Patron Information

              <form role="form">

                    First Name
                      <input
                        className="form-control"
                        name="fname"
                        type="text"
                        placeholder="First Name"
                        value={this.state.fname}
                        onChange={this.handleChange} />

                    Last Name
                      <input
                        className="form-control"
                        name="lname"
                        type="text"
                        placeholder="Last Name"
                        value={this.state.lname}
                        onChange={this.handleChange} />

                    NSHE ID #
                      <input
                        className="form-control"
                        name="NSHE"
                        type="text"
                        placeholder="NSHE ID #"
                        value={this.state.NSHE}
                        onChange={this.handleChange} />

                    Email
                      <input
                        className="form-control"
                        name="email"
                        type="email"
                        placeholder="Email"
                        value={this.state.email}
                        onChange={this.handleChange} />

                    Phone Number
                      <input
                        className="form-control"
                        name="pnum"
                        type="text"
                        placeholder="Phone Number"
                        value={this.state.pnum}
                        onChange={this.handleChange} />

              </form>

              {/*Start Vehicle Information*/}

Vehicle Information

              <form role="form">

                    Year
                      <input
                        className="form-control"
                        name="vYear"
                        type="text"
                        placeholder="Year"
                        value={this.state.vYear}
                        onChange={this.handleChange} />

                    Color
                      <input
                        className="form-control"
                        name="vColor"
                        type="text"
                        placeholder="Color"
                        value={this.state.vColor}
                        onChange={this.handleChange} />

                    Car Make
                    <input
                      className="form-control"
                      name="vMake"
                      type="text"
                      placeholder="Make"
                      value={this.state.vMake}
                      onChange={this.handleChange} />

                    Model
                    <input
                      className="form-control"
                      name="vModel"
                      type="text"
                      placeholder="Model"
                      value={this.state.vModel}
                      onChange={this.handleChange} />

                    License Plate #
                      <input
                        className="form-control"
                        name="vLic"
                        type="text"
                        placeholder="License Plate Number"
                        value={this.state.vLic}
                        onChange={this.handleChange} />

              </form>

Permit Information

              <form role="form">

                    Card ID
                      <input
                        className="form-control"
                        name="cid"
                        type="text"
                        placeholder="Card ID"
                        value={this.state.cid}
                        onChange={this.handleChange} />

                  {/* Permit Information */}

                    Permit Type
                      <select className="form-control" name="permitType" value={this.state.permitType} onChange={this.handleChange}>
                        <option value="student">Student</option>
                        <option value="staff">Staff</option>
                        <option value="guest">Guest</option>
                      </select>

              </form>

              <button className="form-control" onClick={this.handleSubmit}>Submit</button>

  );
  }
}

Register.defaultProps = {
  //Page descriptors
  pageName: "Registration",
  pgDescription: "Students"
};

const mapProps = (store) => {
  return {
    sessionSocket: store.sessionSlice.socket.$get()
  }
}

export default connect({
  component: Register,
  mapProps
});


text:
package pl.radomiej.citizen.generator;

import com.badlogic.gdx.math.Vector2;

import pl.radomiej.citizen.world.GraphNode;
import pl.radomiej.citizen.world.GraphNodeConnection;
import pl.radomiej.citizen.world.GraphWorld;
import pl.radomiej.citizen.world.MovableGraphElement;

public class CitizenWorldGenerator {

	public GraphWorld generate() {
		GraphWorld world = new GraphWorld();
		generateStartRooms(world);
		return world;
	}

	private void generateStartRooms(GraphWorld world) {
		//Create rooms
		GraphNode city0Room = new GraphNode(new Vector2(250, 250));
		city0Room.setName("Roma");
		world.getNodes().add(city0Room);

		GraphNode city1Room = new GraphNode(new Vector2(500, 320));
		city1Room.setName("Mediolano");
		world.getNodes().add(city1Room);

		GraphNode city2Room = new GraphNode(new Vector2(200, 480));
		city2Room.setName("Kappua");
		world.getNodes().add(city2Room);

		GraphNode city3Room = new GraphNode(new Vector2(280, 780));
		city3Room.setName("Sapporo");
		world.getNodes().add(city3Room);

		//Create connections
		GraphNodeConnection roomConnection = new GraphNodeConnection(city0Room, city1Room);
		world.getRoomConnections().add(roomConnection);

		GraphNodeConnection roomConnection2 = new GraphNodeConnection(city0Room, city2Room);
		world.getRoomConnections().add(roomConnection2);

		GraphNodeConnection roomConnection3 = new GraphNodeConnection(city2Room, city3Room);
		world.getRoomConnections().add(roomConnection3);

		//Prepare AI
		world.generateAi();
	}

}


text:
var assert = require('assert'),
    math = require('../../../index'),
    error = math.error;

describe('abs', function () {
  it('should return the abs value of a boolean', function () {
    assert.equal(math.abs(true), 1);
    assert.equal(math.abs(false), 0);
  });

  it('should return the abs value of null', function () {
    assert.equal(math.abs(null), 0);
  });

  it('should return the abs value of a number', function () {
    assert.equal(math.abs(-4.2), 4.2);
    assert.equal(math.abs(-3.5), 3.5);
    assert.equal(math.abs(100), 100);
    assert.equal(math.abs(0), 0);
  });

  it('should return the absolute value of a big number', function () {
    assert.deepEqual(math.abs(math.bignumber(-2.3)), math.bignumber(2.3));
    assert.deepEqual(math.abs(math.bignumber('5e500')), math.bignumber('5e500'));
    assert.deepEqual(math.abs(math.bignumber('-5e500')), math.bignumber('5e500'));
  });

  it('should return the absolute value of a complex number', function () {
    assert.equal(math.abs(math.complex(3, -4)), 5);
    assert.equal(math.abs(math.complex(1e200, -4e200)), 4.12310562561766e+200);
    assert.equal(math.norm(math.complex(-4e200, 1e200)), 4.12310562561766e+200);
  });

  it('should return the absolute number of a complex number with zero', function () {
    assert.equal(math.abs(math.complex(1, 0)), 1);
    assert.equal(math.abs(math.complex(0, 1)), 1);
    assert.equal(math.abs(math.complex(0, 0)), 0);
    assert.equal(math.abs(math.complex(-1, 0)), 1);
    assert.equal(math.abs(math.complex(0, -1)), 1);
  });

  it('should return the absolute value of all elements in a matrix', function () {
    var a1 = math.abs(math.matrix([1,-2,3]));
    assert.ok(a1 instanceof math.type.Matrix);
    assert.deepEqual(a1.size(), [3]);
    assert.deepEqual(a1.valueOf(), [1,2,3]);
    a1 = math.abs(math.matrix([-2,-1,0,1,2]));
    assert.ok(a1 instanceof math.type.Matrix);
    assert.deepEqual(a1.size(), [5]);
    assert.deepEqual(a1.valueOf(), [2,1,0,1,2])
  });

  it('should throw an error with a measurment unit', function () {
    assert.throws(function () {
      math.abs(math.unit(5, 'km'));
    });
  });

  it('should throw an error in case of invalid number of arguments', function() {
    assert.throws(function () {math.abs()}, error.ArgumentsError);
    assert.throws(function () {math.abs(1, 2)}, error.ArgumentsError);
  });

  it('should throw an error with a string', function () {
    assert.throws(function () {
      math.abs('a string');
    });
  });

  it('should LaTeX abs', function () {
	  var expression = math.parse('abs(-1)');
	  assert.equal(expression.toTex(),'\\left|-1\\right|');
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.selendroid.translate"
    android:versionCode="1"
    android:versionName="0.1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.INJECT_EVENTS" />

    <application
        android:debuggable="true"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Light" >
        <activity android:name=".activities.TranslateActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Aerodynamic Module Documentation — AeroPy 0.0.3 documentation</title>
    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="3. Airfoil Module Documentation" href="airfoil_module.html" />
    <link rel="prev" title="1. Xfoil Module Documentation" href="xfoil_module.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

2. Aerodynamic Module Documentation¶

2.1. Lifting Line Theory¶

If \(\theta_0\) is an arbitrary span-wise location:

(1)¶\[\alpha (\theta_o)=\frac{2b}{\pi c(\theta_o)} \sum_1^N A_n sin(n \theta_o) + \alpha_{L=0}(\theta_o) + \sum_1^N n A_n \frac{sin(n\theta_o)}{sin(\theta_o)}\]

Each equation has \(N\) unknowns (\(A_n\)), so if there are N \(\theta_o\), we have NxN system, which in Einstein notation can be written as:

(2)¶\[C_{ij}A_{i}=D_{i}\]

where, \(i=0,...,N\), \(j=0,...,N\) and :

(3)¶\[C_{ij}= \left( \frac{2b}{\pi c(j)} + \frac{n}{sin \theta(i)} \right) sin(n \theta(i))\]

(4)¶\[A_i=A(i)\]

(5)¶\[D_i=\alpha(i)-\alpha_{L=0}(i)\]

where  \(n=1,3,5,...,N-1\). Since we are considering a symmetric wing, all of the even terms would cancel each other

2.2. The code¶

Current funcionatilities:
- Lifting line theory
- generate field pressures for Abaqus or other softwares
- air properties calculator
- Reynolds calculator
Created on Mon Jul 20 17:26:19 2015

@author: Pedro Leal

aeropy.aero_module.LLT_calculator(alpha_L_0_root, c_D_xfoil, N=10, b=10.0, taper=1.0, chord_root=1, alpha_root=0.0, V=1.0)[source]¶

Calculate the coefficients for a Wing.
TODO :  - Include elliptical wing

When alpha_L_0_root = zero, nan!

Include non rectangular wings

something else?

aeropy.aero_module.Reynolds(height, V, c)[source]¶

Simple function to calculate Reynolds for a given height.

@author: Pedro Leal
Created in Jul 17 2015

aeropy.aero_module.air_properties(height, unit='feet')[source]¶

Function to calculate air properties for a given height (m or ft).

Sources:

http://en.wikipedia.org/wiki/Density_of_air#Altitude

http://aerojet.engr.ucdavis.edu/fluenthelp/html/ug/node337.htm

Created on Thu May 15 14:59:43 2014
@author: Pedro Leal

aeropy.aero_module.calculate_moment_coefficient(x, y, Cp, alpha, c=1.0, x_ref=0.25, y_ref=0.0, flap=False)[source]¶

Calculate the moment coeffcient. Inputs are x and y coordinates, and
pressure coefficients (Cp). Inputs can be in a list in xfoil format
(counterclockwise starting from the trailing edge, in case necessary,
check create_input function from xfoil_module) or dictionaries with
'upper' and 'lower' keys.

<col class="field-name" />
<col class="field-body" />

Parameters:	flap – if true, also calculates the moment contribution from
the trailing edge and the panels in front of the flap
(that are not directly in contact with the air)

aeropy.aero_module.pressure_shell(Data, half_span, chord='MAX', air_density=0, Velocity=0, N=10, thickness=0, txt=False, llt_distribution=False, distribution='Uniform', amplifier=1)[source]¶

Converts pressure coefficient data, usually 2D, into a 3D presurre field
that Abaqus understands. Can be used for shells (considers thicknesses),
but also for any surface. Can do Lifting Line Theory (LLT), Elliptical,
and Uniform distributions.

If chord='MAX', the maximum value for vector 'x' is used as chord. If
data in non-dimensional, use a numerical value.

If txt==True, an output textfile is generated.

aeropy.aero_module.pressure_shell_2D(Data, chord, thickness, half_span, height, Velocity, N, txt=False)[source]¶

Calculate pressure field for a 2D Shell.

AeroPy

An easy to use aerodynamic tool

Navigation

1. Xfoil Module Documentation

2. Aerodynamic Module Documentation

3. Airfoil Module Documentation

4. Tutorial

Related Topics

Documentation overview

Previous: 1. Xfoil Module Documentation

Next: 3. Airfoil Module Documentation

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2015, Pedro Leal.

      |
      Powered by Sphinx 1.8.1
      & Alabaster 0.7.11

      |
      Page source


text:
build.js
11:31:29 AM
// Build task

var gulp = require('gulp'),
    runSequence = require('run-sequence');

// Clean build directory
gulp.task('build', function(callback) {
  runSequence(
    'clean',
    ['bower', 'js', 'images'],
    'cssmin',
    'html',
    'clean-partials',
    callback
  );
});


text:
import React                    from 'react';
import style from 'PVWStyle/ReactWidgets/PlotlySelectionWidgets.mcss';

const PlotlyHistogram2DWidget = (props) => {
  function handleChange(event) {
    const rootContainer = event.target.parentNode.parentNode.parentNode;
    const newXArray = rootContainer.querySelector('.jsX').value;
    const newYArray = rootContainer.querySelector('.jsY').value;
    // const forceNewPlot = props.arrays[props.chartState.x] !== props.arrays[newXArray] ||
    //   props.arrays[props.chartState.y] !== props.arrays[newYArray];
    props.onChange({
      chartType: 'Histogram2D',
      x: newXArray,
      y: newYArray,
      forceNewPlot: true,
    });
  }

  return (

            x

              <select className={['jsX', style.fullWidth].join(' ')} onChange={handleChange} value={props.chartState.x}>
                {Object.keys(props.arrays).map(arrayName => <option value={arrayName} key={arrayName}>{arrayName}</option>)}
              </select>

            y

              <select className={['jsY', style.fullWidth].join(' ')} onChange={handleChange} value={props.chartState.y}>
                {Object.keys(props.arrays).map(arrayName => <option value={arrayName} key={arrayName}>{arrayName}</option>)}
              </select>

  );
};

PlotlyHistogram2DWidget.propTypes = {
  chartState: React.PropTypes.object,
  arrays: React.PropTypes.object,
  onChange: React.PropTypes.func,
};

PlotlyHistogram2DWidget.defaultProps = {
  chartState: {},
  arrays: [],
  onChange: () => {},
};

export default PlotlyHistogram2DWidget;


text:
import 'babel-polyfill';
import express from 'express';
import dotenv from 'dotenv';
// import logger from 'morgan';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRouter from './routes/userRouter';
import groupRouter from './routes/groupRouter';
import membershipRouter from './routes/membershipRouter';
import messageRouter from './routes/messageRouter';
import Auth from './helpers/auth';
// import notificationRouter from './routes/notificationRouter';

// Configure environment settings
dotenv.config();

// Set up server express
const app = express();

// Log requests to the console
// app.use(logger('dev'));

// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// Unprotected routes
app.use('/api/v1/users', userRouter);

// Protected routes
// app.use('/api/v1/users/:userId/notifications',
// Auth.isAuthenticated, (req, res, next) => {
//   next();
// });
// app.use('/api/v1/users/:userId/notifications', notificationRouter);

app.use('/api/v1/groups',
 Auth.isAuthenticated, (req, res, next) => { next(); });
app.use('/api/v1/groups', groupRouter);
app.use('/api/v1/groups/:groupId/users', membershipRouter);
app.use('/api/v1/groups/:groupId/messages', messageRouter);

// Default API request
app.get('/api/v1/', (req, res) => {
  res.set('Content-Type', 'application/json');
  res.status(200).send({ message: 'PostIT API is running...' });
});

// Random or invalid request
app.get('*', (req, res) => {
  res.set('Content-Type', 'application/json');
  res.status(404).send({ message: 'Error! No resource matches your request!' });
});

// Retrieve port for this app environment
const port = process.env.PORT || 8000;

// Create server and initialize it with the express app
const server = app.listen(port, () => {
  console.log(`Listening at port ${port}`);
});

export default server;


text:
{% load staticfiles %}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Результаты fitnesse теста</title>
  <link rel="stylesheet" type="text/css" href="{% static 'fitnesse/project/css/fitnesse.css' %}" />
  <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
  <link rel="shortcut icon" href="{% static 'app/favicon.ico' %}" />

Home/

{{job.name}}/

{{test_name}}

 (build: {{build_id}})

          Fitnesse result

          ClientW8

            Браузер не поддерживает iframe. Обновитесь.

          {% autoescape off %}
          {{ fitnesse_result.before }}

{{ fitnesse_result.test }}

          {{ fitnesse_result.after }}
          {% endautoescape %}


text:
class RegistrationsController < Devise::RegistrationsController

  before_action :one_user_registered?, only: [:new, :create]

  protected

  def one_user_registered?
    if ((User.count == 1) & (user_signed_in?))
      redirect_to root_path
    elsif User.count == 1
      redirect_to new_user_session_path
    end
  end

end


text:
using System.Collections.Generic;
using System.Linq;
using Baseline;
using LamarCodeGeneration;
using Marten.Events.CodeGeneration;
using Marten.Exceptions;
using Marten.Schema;

namespace Marten.Events.Aggregation
{
    public abstract partial class GeneratedAggregateProjectionBase<T>
    {
        protected virtual void specialAssertValid() { }

        protected abstract IEnumerable<string> validateDocumentIdentity(StoreOptions options, DocumentMapping mapping);

        internal override IEnumerable<string> ValidateConfiguration(StoreOptions options)
        {
            var mapping = options.Storage.FindMapping(typeof(T)).Root.As<DocumentMapping>();
            foreach (var p in validateDocumentIdentity(options, mapping)) yield return p;

            if (options.Events.TenancyStyle != mapping.TenancyStyle)
            {
                yield return
                    $"Tenancy storage style mismatch between the events ({options.Events.TenancyStyle}) and the aggregate type {typeof(T).FullNameInCode()} ({mapping.TenancyStyle})";
            }

            if (mapping.DeleteStyle == DeleteStyle.SoftDelete)
            {
                yield return
                    $"AggregateProjection cannot support aggregates that are soft-deleted";
            }

        }

        internal override void AssembleAndAssertValidity()
        {
            if (_applyMethods.IsEmpty() && _createMethods.IsEmpty())
            {
                throw new InvalidProjectionException(
                    $"AggregateProjection for {typeof(T).FullNameInCode()} has no valid create or apply operations");
            }

            var invalidMethods =
                MethodCollection.FindInvalidMethods(GetType(), _applyMethods, _createMethods, _shouldDeleteMethods);

            if (invalidMethods.Any())
            {
                throw new InvalidProjectionException(this, invalidMethods);
            }

            specialAssertValid();

            var eventTypes = determineEventTypes();
            IncludedEventTypes.Fill(eventTypes);
        }
    }
}


text:
<!DOCTYPE html>

<?php
	 $this->load->view("common/meta_links");
?>
	 <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">

  <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.6/summernote.css" rel="stylesheet">

	<?php
		$this->load->view("common/header");
	?>

Add Service

Home/Add Service

Member Since:

December 26th, 2013

Total Sales:

820

Freelance Work:

Available

Website:

www.odindesign-themes.com

				<?php
					$this->load->view("common/clickers_sidebar");
				?>

Add Service

Service Specifications

					<form id="upload_form" name="myform" method="POST" action="<?php echo base_url();?>index.php/add_service/insert_service" enctype="multipart/form-data">

							Select Category

								<?php
									$categories_data = json_decode(json_encode($get_categories), True);
									//print_r($categories_data);
								?>
								<select name="category" id="category">
									<option selected disabled>Choose A Category...</option>
									<?php
									foreach($categories_data As $cat_val){
									?>
										<option value="<?php echo $cat_val['category_id'];?>"><?php echo $cat_val['category_name'];?></option>
									<?php
									}
									?>

								</select>

								<svg class="svg-arrow">
									<use xlink:href="#svg-arrow"></use>
								</svg>

							Title of the Service (Max 40 Characters)
							<input type="text" id="item_name" name="item_title" maxlength="40" placeholder="Enter them service title here.">

							Service Description
							<textarea id="item_description" name="item_description" placeholder="Enter them service description here."></textarea>

Hello Summernote

							Price (₹)
							<input type="text" id="item_tags" name="item_price" placeholder="Enter price for this service">

							Upload Service Banners

											<img src="<?php echo base_url();?>images/favicon.jpg" alt="profile-default-image" id="lolwa_pic">

Upload best work pictures

for the best results

									Upload Image
									<input type="file" id="pro_pic" name="picture[]" style="display:none"/>

										Add More

						<button class="button big dark" type="submit">Submit Service for Review</button>
					</form>

	<?php
		$this->load->view("common/footer");
	?>


text:
<?php

$multipleRoutes = [
    'product/(:num)'      => 'Catalog::productLookupById',
    'product/(:alphanum)' => 'Catalog::productLookupByName',
];

$routes->map($multipleRoutes);


text:
export default interface MDCTabAdapter {
    addClass(className: string): void;

    removeClass(className: string): void;

    registerInteractionHandler(type: string, handler: EventListener): void;

    deregisterInteractionHandler(type: string, handler: EventListener): void;

    getOffsetWidth(): number;

    getOffsetLeft(): number;

    notifySelected(): void;
}


text:
.monaco-workbench .timeline-tree-view {
	position: relative;
}

.monaco-workbench .timeline-view.pane-header .description {
	margin-left: 10px;
	opacity: 0.6;
	text-transform: none;
	font-weight: normal;
}

.monaco-workbench .timeline-view.pane-header:not(.expanded) .description {
	display: none;
}

.monaco-workbench .timeline-view.pane-header .description span.codicon {
	font-size: 9px;
	margin-left: 2px;
}

.monaco-workbench .timeline-tree-view .message.timeline-subtle {
	opacity: 0.5;
	padding: 10px 22px 0 22px;
	position: absolute;
	pointer-events: none;
	z-index: 1;
}

.timeline-tree-view .monaco-list .monaco-list-row .custom-view-tree-node-item .monaco-icon-label {
	flex: 1;
	text-overflow: ellipsis;
	overflow: hidden;
}

.timeline-tree-view .monaco-list .monaco-list-row .custom-view-tree-node-item .timeline-timestamp-container {
	margin-left: 2px;
	margin-right: 4px;
	opacity: 0.5;
	overflow: hidden;
	text-overflow: ellipsis;
}

.timeline-tree-view .monaco-list .monaco-list-row .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate::before {
	content: ' ';
	position: absolute;
	right: 10px;
	border-right: 1px solid currentColor;
	display: block;
	height: 100%;
	width: 1px;
	opacity: 0.25;
}

.timeline-tree-view  .monaco-list .monaco-list-row:hover .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate::before,
.timeline-tree-view .monaco-list .monaco-list-row.selected .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate::before,
.timeline-tree-view .monaco-list .monaco-list-row.focused .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate::before {
	display: none;
}

.timeline-tree-view .monaco-list .monaco-list-row .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate .timeline-timestamp {
	visibility: hidden;
}

.timeline-tree-view .monaco-list .monaco-list-row:hover .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate .timeline-timestamp,
.timeline-tree-view .monaco-list .monaco-list-row.selected .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate .timeline-timestamp,
.timeline-tree-view .monaco-list .monaco-list-row.focused .custom-view-tree-node-item .timeline-timestamp-container.timeline-timestamp--duplicate .timeline-timestamp {
	visibility: visible !important;
}


text:
@interface PDFDocumentBackForwardList ()
@property (nonatomic, assign) NSUInteger currentIndex;
@property (nonatomic, strong) NSArray *items;
@end

@implementation PDFDocumentBackForwardList

+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"currentPage"]) {
        return [NSSet setWithObjects:@"currentIndex", @"items", nil];
    } else if ([key isEqualToString:@"canGoBack"]) {
        return [NSSet setWithObjects:@"currentIndex", nil];
    } else if ([key isEqualToString:@"canGoForward"]) {
        return [NSSet setWithObjects:@"currentIndex", nil];
    }
    return NSSet.set;
}

- (instancetype)initWithCurrentPage:(NSUInteger)currentPage
{
    self = [super init];
    if (self) {
        _currentIndex = 0;
        _items = [NSArray arrayWithObject:@(currentPage)];
    }
    return self;
}

- (BOOL)canGoBack
{
    return self.currentIndex > 0;
}

- (BOOL)canGoForward
{
    return self.items.count - 1 > self.currentIndex;
}

- (NSUInteger)currentPage
{
    return [[self.items objectAtIndex:self.currentIndex] unsignedIntegerValue];
}

#pragma mark -

- (void)goBack
{
    if (self.canGoBack) {
        self.currentIndex--;
    }
}

- (void)goForward
{
    if (self.canGoForward) {
        self.currentIndex++;
    }
}

- (void)goTo:(NSUInteger)page
  addHistory:(BOOL)addHistory
{
    if (addHistory) {
        self.items = [[self.items subarrayWithRange:NSMakeRange(0, self.currentIndex + 1)] mutableCopy];
        [self.itemsProxy addObject:@(page)];
        self.currentIndex++;
    } else {
        [self.itemsProxy replaceObjectAtIndex:self.items.count - 1
                                   withObject:@(page)];
    }
}

#pragma mark -

- (NSMutableArray *)itemsProxy
{
    return [self mutableArrayValueForKey:@"items"];
}

@end


text:
layout: default
title: Homepage
title_label: hide
post_scripts:
- /js/registration.js
startup_functions:
---

Register Now!

            {% include registration-index.html %}


text:
import json
import os.path
import numpy as np
from common import time
from common.data import CachedDataLoader, makedirs
from common.pipeline import Pipeline
from seizure.transforms import FFT, Slice, Magnitude, Log10, FFTWithTimeFreqCorrelation, MFCC, Resample, Stats, \
    DaubWaveletStats, TimeCorrelation, FreqCorrelation, TimeFreqCorrelation
from seizure.tasks import TaskCore, CrossValidationScoreTask, MakePredictionsTask, TrainClassifierTask
from seizure.scores import get_score_summary, print_results

from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, ExtraTreesClassifier, \
    GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

def run_seizure_detection(build_target):
    """
    The main entry point for running seizure-detection cross-validation and predictions.
    Directories from settings file are configured, classifiers are chosen, pipelines are
    chosen, and the chosen build_target ('cv', 'predict', 'train_model') is run across
    all combinations of (targets, pipelines, classifiers)
    """

    with open('SETTINGS.json') as f:
        settings = json.load(f)

    data_dir = str(settings['competition-data-dir'])
    cache_dir = str(settings['data-cache-dir'])
    submission_dir = str(settings['submission-dir'])

    makedirs(submission_dir)

    cached_data_loader = CachedDataLoader(cache_dir)

    ts = time.get_millis()

    targets = [
        'Dog_1',
        'Dog_2',
        'Dog_3',
        'Dog_4',
        'Patient_1',
        'Patient_2',
        'Patient_3',
        'Patient_4',
        'Patient_5',
        'Patient_6',
        'Patient_7',
        'Patient_8'
    ]
    pipelines = [
        # NOTE(mike): you can enable multiple pipelines to run them all and compare results
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Slice(1, 48), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Slice(1, 64), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Slice(1, 96), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Slice(1, 128), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Slice(1, 160), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[FFT(), Magnitude(), Log10()]),
        # Pipeline(gen_ictal=False, pipeline=[Stats()]),
        # Pipeline(gen_ictal=False, pipeline=[DaubWaveletStats(4)]),
        # Pipeline(gen_ictal=False, pipeline=[Resample(400), DaubWaveletStats(4)]),
        # Pipeline(gen_ictal=False, pipeline=[Resample(400), MFCC()]),
        # Pipeline(gen_ictal=False, pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'us')]),
        # Pipeline(gen_ictal=True,  pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'us')]),
        Pipeline(gen_ictal=False, pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'usf')]), # winning submission
        # Pipeline(gen_ictal=True,  pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'usf')]), # higher score than winning submission
        # Pipeline(gen_ictal=False, pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'none')]),
        # Pipeline(gen_ictal=True,  pipeline=[FFTWithTimeFreqCorrelation(1, 48, 400, 'none')]),
        # Pipeline(gen_ictal=False, pipeline=[TimeCorrelation(400, 'usf', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[TimeCorrelation(400, 'us', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[TimeCorrelation(400, 'us', with_corr=True, with_eigen=False)]),
        # Pipeline(gen_ictal=False, pipeline=[TimeCorrelation(400, 'us', with_corr=False, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[TimeCorrelation(400, 'none', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[FreqCorrelation(1, 48, 'usf', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[FreqCorrelation(1, 48, 'us', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[FreqCorrelation(1, 48, 'us', with_corr=True, with_eigen=False)]),
        # Pipeline(gen_ictal=False, pipeline=[FreqCorrelation(1, 48, 'us', with_corr=False, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[FreqCorrelation(1, 48, 'none', with_corr=True, with_eigen=True)]),
        # Pipeline(gen_ictal=False, pipeline=[TimeFreqCorrelation(1, 48, 400, 'us')]),
        # Pipeline(gen_ictal=False, pipeline=[TimeFreqCorrelation(1, 48, 400, 'usf')]),
        # Pipeline(gen_ictal=False, pipeline=[TimeFreqCorrelation(1, 48, 400, 'none')]),
    ]
    classifiers = [
        # NOTE(mike): you can enable multiple classifiers to run them all and compare results
        # (RandomForestClassifier(n_estimators=50, min_samples_split=1, bootstrap=False, n_jobs=4, random_state=0), 'rf50mss1Bfrs0'),
        # (RandomForestClassifier(n_estimators=150, min_samples_split=1, bootstrap=False, n_jobs=4, random_state=0), 'rf150mss1Bfrs0'),
        # (RandomForestClassifier(n_estimators=300, min_samples_split=1, bootstrap=False, n_jobs=4, random_state=0), 'rf300mss1Bfrs0'),

        # NOTE(mike): The original submission classifier was min_samples_split=1, but I had to change it to 2 after upgrading scikit.
        # I'm not even sure min_samples_split=1 makes sense in hindsight, how can you split on 1 sample? Anyway to get the repo functional
        # again with newer libraries it's now 2.
        # (RandomForestClassifier(n_estimators=3000, min_samples_split=1, bootstrap=False, n_jobs=4, random_state=0), 'rf3000mss1Bfrs0'),
        (RandomForestClassifier(n_estimators=3000, min_samples_split=2, bootstrap=False, n_jobs=4, random_state=0), 'rf3000mss2Bfrs0'),
    ]
    cv_ratio = 0.5

    def should_normalize(classifier):
        clazzes = [LogisticRegression]
        return np.any(np.array([isinstance(classifier, clazz) for clazz in clazzes]) == True)

    def train_full_model(make_predictions):
        for pipeline in pipelines:
            for (classifier, classifier_name) in classifiers:
                print 'Using pipeline %s with classifier %s' % (pipeline.get_name(), classifier_name)
                guesses = ['clip,seizure,early']
                classifier_filenames = []
                for target in targets:
                    task_core = TaskCore(cached_data_loader=cached_data_loader, data_dir=data_dir,
                                         target=target, pipeline=pipeline,
                                         classifier_name=classifier_name, classifier=classifier,
                                         normalize=should_normalize(classifier), gen_ictal=pipeline.gen_ictal,
                                         cv_ratio=cv_ratio)

                    if make_predictions:
                        predictions = MakePredictionsTask(task_core).run()
                        guesses.append(predictions.data)
                    else:
                        task = TrainClassifierTask(task_core)
                        task.run()
                        classifier_filenames.append(task.filename())

                if make_predictions:
                    filename = 'submission%d-%s_%s.csv' % (ts, classifier_name, pipeline.get_name())
                    filename = os.path.join(submission_dir, filename)
                    with open(filename, 'w') as f:
                        print >> f, '\n'.join(guesses)
                    print 'wrote', filename
                else:
                    print 'Trained classifiers ready in %s' % cache_dir
                    for filename in classifier_filenames:
                        print os.path.join(cache_dir, filename + '.pickle')

    def do_cross_validation():
        summaries = []
        for pipeline in pipelines:
            for (classifier, classifier_name) in classifiers:
                print 'Using pipeline %s with classifier %s' % (pipeline.get_name(), classifier_name)
                scores = []
                S_scores = []
                E_scores = []
                for target in targets:
                    print 'Processing %s (classifier %s)' % (target, classifier_name)

                    task_core = TaskCore(cached_data_loader=cached_data_loader, data_dir=data_dir,
                                         target=target, pipeline=pipeline,
                                         classifier_name=classifier_name, classifier=classifier,
                                         normalize=should_normalize(classifier), gen_ictal=pipeline.gen_ictal,
                                         cv_ratio=cv_ratio)

                    data = CrossValidationScoreTask(task_core).run()
                    score = data.score

                    scores.append(score)

                    print '%.3f' % score, 'S=%.4f' % data.S_auc, 'E=%.4f' % data.E_auc
                    S_scores.append(data.S_auc)
                    E_scores.append(data.E_auc)

                if len(scores) > 0:
                    name = pipeline.get_name() + '_' + classifier_name
                    summary = get_score_summary(name, scores)
                    summaries.append((summary, np.mean(scores)))
                    print summary
                if len(S_scores) > 0:
                    name = pipeline.get_name() + '_' + classifier_name
                    summary = get_score_summary(name, S_scores)
                    print 'S', summary
                if len(E_scores) > 0:
                    name = pipeline.get_name() + '_' + classifier_name
                    summary = get_score_summary(name, E_scores)
                    print 'E', summary

            print_results(summaries)

    if build_target == 'cv':
        do_cross_validation()
    elif build_target == 'train_model':
        train_full_model(make_predictions=False)
    elif build_target == 'make_predictions':
        train_full_model(make_predictions=True)
    else:
        raise Exception("unknown build target %s" % build_target)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 1.1.1.2.3.0.0-2557 Reference Package org.apache.hadoop.hbase.exceptions</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.exceptions

Classes

            	ConnectionClosingException

            	DeserializationException

            	FailedSanityCheckException

            	HBaseException

            	LockTimeoutException

            	MergeRegionException

            	OperationConflictException

            	OutOfOrderScannerNextException

            	PreemptiveFastFailException

            	RegionInRecoveryException

            	RegionMovedException

            	RegionOpeningException

            	TimeoutIOException

            	UnknownProtocolException


text:
/**
 * @Title: FeedbackBean.java
 * @Package cn.changhong.chcare.core.webapi.bean
 * @Description: TODO
 * @author guoyang2011@gmail.com
 * @date 2014-10-20 下午6:15:09
 * @version V1.0
*/
package cn.changhong.chcare.core.webapi.bean;

import java.io.Serializable;
import java.util.Date;

/**
 * @ClassName: FeedbackBean
 * @Description: TODO
 * @author guoyang2011@gmail.com
 * @date 2014-10-20 下午6:15:09
 *
 */
public class FeedbackBean implements Serializable{
	/**
	 * @Fields serialVersionUID : TODO
	*/
	private static final long serialVersionUID = 1L;
	private int ID;//服务器端设置
	private int UserID;//上传用户ID
	private int APPID;//APP的ID号

	private int SugType;//意见类型
	private String UserSug;//意见内容
	private Date SugTime;//上传时间,服务器端设置
	private int DevVer;//开发者版本号
	private boolean isRead;//是否处理
	private int AppOS;//APP的平台类型

	private String OSVer;

	public String getOSVer() {
		return OSVer;
	}
	public void setOSVer(String oSVer) {
		OSVer = oSVer;
	}
	public int getID() {
		return ID;
	}
	public void setID(int iD) {
		ID = iD;
	}
	public int getAPPID() {
		return APPID;
	}
	public void setAPPID(int aPPID) {
		APPID = aPPID;
	}
	public int getUserID() {
		return UserID;
	}
	public void setUserID(int userID) {
		UserID = userID;
	}
	public int getSugType() {
		return SugType;
	}
	public void setSugType(int sugType) {
		SugType = sugType;
	}
	public String getUserSug() {
		return UserSug;
	}
	public void setUserSug(String userSug) {
		UserSug = userSug;
	}
	public Date getSugTime() {
		return SugTime;
	}
	public void setSugTime(Date sugTime) {
		SugTime = sugTime;
	}
	public int getDevVer() {
		return DevVer;
	}
	public void setDevVer(int devVer) {
		DevVer = devVer;
	}
	public boolean isRead() {
		return isRead;
	}
	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}
	public int getAppOS() {
		return AppOS;
	}
	public void setAppOS(int appOS) {
		AppOS = appOS;
	}

}


text:
.. _users-guide-separate_VCL:

Separate VCL files
==================

Having multiple different vhosts in the same Varnish is a very
typical use-case, and from Varnish 5.0 it is possible to have
a separate VCL files for separate vhosts or any other distinct
subset of requests.

Assume that we want to handle ``varnish.org`` with one VCL file
and ``varnish-cache.org`` with another VCL file.

First load the two VCL files::

    vcl.load vo_1 /somewhere/vo.vcl
    vcl.load vc_1 /somewhere/vc.vcl

These are 100% normal VCL files, as they would look if you ran
only that single domain on your varnish instance.

Next we need to point VCL labels to them::

    vcl.label l_vo vo_1
    vcl.label l_vc vc_1

Next we write the top-level VCL program, which branches out
to the other two, depending on the Host: header in the
request::

    import std;

    # We have to have a backend, even if we do not use it
    backend default { .host = "127.0.0.1"; }

    sub vcl_recv {
	# Normalize host header
	set req.http.host = std.tolower(req.http.host);

	if (req.http.host ~ "\.?varnish\.org$") {
	    return (vcl(l_vo));
	}
	if (req.http.host ~ "\.?varnish-cache\.org$") {
	    return (vcl(l_vc));
	}
	return (synth(302, "http://varnish-cache.org"));
    }

    sub vcl_synth {
	if (resp.status == 301 || resp.status == 302) {
	    set resp.http.location = resp.reason;
	    set resp.reason = "Moved";
	    return (deliver);
	}
    }

Finally, we load the top level VCL and make it the
active VCL::

    vcl.load top_1 /somewhere/top.vcl
    vcl.use top_1

If you want to update one of the separated VCLs, you load the new
one and change the label to point to it::

    vcl.load vo_2 /somewhere/vo.vcl
    vcl.label l_vo vo_2

If you want to change the top level VCL, do as you always did::

    vcl.load top_2 /somewhere/top.vcl
    vcl.use top_2

Details, details, details:
--------------------------

* All requests *always* start in the active VCL - the one from ``vcl.use``

* Only VCL labels can be used in ``return(vcl(name))``.  Without this
  restriction the top level VCL would have to be reloaded every time
  one of the separate VCLs were changed.

* You can only switch VCLs from the active VCL.  If you try it from one of
  the separate VCLs, you will get a 503

* You cannot remove VCL labels (with ``vcl.discard``) if any VCL
  contains ``return(vcl(name_of_that_label))``

* You cannot remove VCLs which have a label attached to them.

* This code is tested in testcase c00077

* This is a very new feature, it may change

* We would very much like feedback how this works for you