func (render *Render) Funcs(funcMap template.FuncMap) *Template {
	tmpl := &Template{render: render, usingDefaultLayout: true}
	return tmpl.Funcs(funcMap)
}

func ( render * Render ) Funcs ( funcMap template . FuncMap ) * Template { tmpl := & Template { render : render , usingDefaultLayout : true } return tmpl . Funcs ( funcMap ) }

// Funcs set helper functions for template with default "application" layout.

Funcs set helper functions for template with default application layout .


func (render *Render) Execute(name string, context interface{}, request *http.Request, writer http.ResponseWriter) error {
	tmpl := &Template{render: render, usingDefaultLayout: true}
	return tmpl.Execute(name, context, request, writer)
}

func ( render * Render ) Execute ( name string , context interface { } , request * http . Request , writer http . ResponseWriter ) error { tmpl := & Template { render : render , usingDefaultLayout : true } return tmpl . Execute ( name , context , request , writer ) }

// Execute render template with default "application" layout.

Execute render template with default application layout .


func (render *Render) RegisterFuncMap(name string, fc interface{}) {
	if render.funcMaps == nil {
		render.funcMaps = template.FuncMap{}
	}
	render.funcMaps[name] = fc
}

func ( render * Render ) RegisterFuncMap ( name string , fc interface { } ) { if render . funcMaps == nil { render . funcMaps = template . FuncMap { } } render . funcMaps [ name ] = fc }

// RegisterFuncMap register FuncMap for render.

RegisterFuncMap register FuncMap for render .


func (render *Render) Asset(name string) ([]byte, error) {
	return render.AssetFileSystem.Asset(name)
}

func ( render * Render ) Asset ( name string ) ( [ ] byte , error ) { return render . AssetFileSystem . Asset ( name ) }

// Asset get content from AssetFS by name


func NewPlainClient(identity, username, password string) Client {
	return &plainClient{identity, username, password}
}

func NewPlainClient ( identity , username , password string ) Client { return & plainClient { identity , username , password } }

// A client implementation of the PLAIN authentication mechanism, as described
// in RFC 4616. Authorization identity may be left blank to indicate that it is
// the same as the username.

A client implementation of the PLAIN authentication mechanism as described in RFC 4616 . Authorization identity may be left blank to indicate that it is the same as the username .


func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) {
	if c == nil {
		c = DefaultConfig
	}
	return newUploader(url, h, c)
}

func Create ( url string , h http . Header , c * Config ) ( io . WriteCloser , error ) { if c == nil { c = DefaultConfig } return newUploader ( url , h , c ) }

// Create creates an S3 object at url and sends multipart upload requests as
// data is written.
//
// If h is not nil, each of its entries is added to the HTTP request header.
// If c is nil, Create uses DefaultConfig.

Create creates an S3 object at url and sends multipart upload requests as data is written . If h is not nil each of its entries is added to the HTTP request header . If c is nil Create uses DefaultConfig .


func Open(url string, c *Config) (io.ReadCloser, error) {
	if c == nil {
		c = DefaultConfig
	}
	// TODO(kr): maybe parallel range fetching
	r, _ := http.NewRequest("GET", url, nil)
	r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
	c.Sign(r, *c.Keys)
	client := c.Client
	if client == nil {
		client = http.DefaultClient
	}
	resp, err := client.Do(r)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != 200 {
		return nil, newRespError(resp)
	}
	return resp.Body, nil
}

// Open requests the S3 object at url. An HTTP status other than 200 is
// considered an error.
//
// If c is nil, Open uses DefaultConfig.

Open requests the S3 object at url . An HTTP status other than 200 is considered an error . If c is nil Open uses DefaultConfig .


func Sign(r *http.Request, k Keys) {
	DefaultService.Sign(r, k)
}

func Sign ( r * http . Request , k Keys ) { DefaultService . Sign ( r , k ) }

// Sign signs an HTTP request with the given S3 keys.
//
// This function is a wrapper around DefaultService.Sign.

Sign signs an HTTP request with the given S3 keys . This function is a wrapper around DefaultService . Sign .


func (s *Service) Sign(r *http.Request, k Keys) {
	if k.SecurityToken != "" {
		r.Header.Set("X-Amz-Security-Token", k.SecurityToken)
	}
	h := hmac.New(sha1.New, []byte(k.SecretKey))
	s.writeSigData(h, r)
	sig := make([]byte, base64.StdEncoding.EncodedLen(h.Size()))
	base64.StdEncoding.Encode(sig, h.Sum(nil))
	r.Header.Set("Authorization", "AWS "+k.AccessKey+":"+string(sig))
}

func ( s * Service ) Sign ( r * http . Request , k Keys ) { if k . SecurityToken != " " { r . Header . Set ( " " , k . SecurityToken ) } h := hmac . New ( sha1 . New , [ ] byte ( k . SecretKey ) ) s . writeSigData ( h , r ) sig := make ( [ ] byte , base64 . StdEncoding . EncodedLen ( h . Size ( ) ) ) base64 . StdEncoding . Encode ( sig , h . Sum ( nil ) ) r . Header . Set ( " " , " " + k . AccessKey + " " + string ( sig ) ) }

// Sign signs an HTTP request with the given S3 keys for use on service s.

Sign signs an HTTP request with the given S3 keys for use on service s .


func (f *File) Readdir(n int) ([]os.FileInfo, error) {
	if f.result != nil && !f.result.IsTruncated {
		return make([]os.FileInfo, 0), io.EOF
	}

	reader, err := f.sendRequest(n)
	if err != nil {
		return nil, err
	}
	defer reader.Close()

	return f.parseResponse(reader)
}

func ( f * File ) Readdir ( n int ) ( [ ] os . FileInfo , error ) { if f . result != nil && ! f . result . IsTruncated { return make ( [ ] os . FileInfo , 0 ) , io . EOF } reader , err := f . sendRequest ( n ) if err != nil { return nil , err } defer reader . Close ( ) return f . parseResponse ( reader ) }

// Readdir requests a list of entries in the S3 directory
// represented by f and returns a slice of up to n FileInfo
// values, in alphabetical order. Subsequent calls
// on the same File will yield further FileInfos.
// Only direct children are returned, not deeper descendants.

Readdir requests a list of entries in the S3 directory represented by f and returns a slice of up to n FileInfo values in alphabetical order . Subsequent calls on the same File will yield further FileInfos . Only direct children are returned not deeper descendants .


func Find(x tree.Node, p pathexpr.PathExpr) []tree.Node {
	ret := []tree.Node{}

	if p.Axis == "" {
		findChild(x, &p, &ret)
		return ret
	}

	f := findMap[p.Axis]
	f(x, &p, &ret)

	return ret
}

func Find ( x tree . Node , p pathexpr . PathExpr ) [ ] tree . Node { ret := [ ] tree . Node { } if p . Axis == " " { findChild ( x , & p , & ret ) return ret } f := findMap [ p . Axis ] f ( x , & p , & ret ) return ret }

//Find finds nodes based on the pathexpr.PathExpr

Find finds nodes based on the pathexpr . PathExpr


func Lex(xpath string) chan XItem {
	l := &Lexer{
		input: xpath,
		items: make(chan XItem),
	}
	go l.run()
	return l.items
}

func Lex ( xpath string ) chan XItem { l := & Lexer { input : xpath , items : make ( chan XItem ) , } go l . run ( ) return l . items }

//Lex an XPath expresion on the io.Reader

Lex an XPath expresion on the io . Reader


func MustParseXML(r io.Reader, op ...ParseSettings) tree.Node {
	ret, err := ParseXML(r, op...)

	if err != nil {
		panic(err)
	}

	return ret
}

func MustParseXML ( r io . Reader , op ... ParseSettings ) tree . Node { ret , err := ParseXML ( r , op ... ) if err != nil { panic ( err ) } return ret }

//MustParseXML is like ParseXML, but panics instead of returning an error.

MustParseXML is like ParseXML but panics instead of returning an error .


func ParseXML(r io.Reader, op ...ParseSettings) (tree.Node, error) {
	ov := ParseOptions{
		Strict:  true,
		XMLRoot: xmlele.Root,
	}
	for _, i := range op {
		i(&ov)
	}

	dec := xml.NewDecoder(r)
	dec.CharsetReader = charset.NewReaderLabel
	dec.Strict = ov.Strict

	ordrPos := 1
	xmlTree := ov.XMLRoot()

	t, err := dec.Token()

	if err != nil {
		return nil, err
	}

	if head, ok := t.(xml.ProcInst); ok && head.Target == "xml" {
		t, err = dec.Token()
	}

	opts := xmlbuilder.BuilderOpts{
		Dec: dec,
	}

	for err == nil {
		switch xt := t.(type) {
		case xml.StartElement:
			setEle(&opts, xmlTree, xt, &ordrPos)
			xmlTree = xmlTree.CreateNode(&opts)
		case xml.CharData:
			setNode(&opts, xmlTree, xt, tree.NtChd, &ordrPos)
			xmlTree = xmlTree.CreateNode(&opts)
		case xml.Comment:
			setNode(&opts, xmlTree, xt, tree.NtComm, &ordrPos)
			xmlTree = xmlTree.CreateNode(&opts)
		case xml.ProcInst:
			setNode(&opts, xmlTree, xt, tree.NtPi, &ordrPos)
			xmlTree = xmlTree.CreateNode(&opts)
		case xml.EndElement:
			xmlTree = xmlTree.EndElem()
		case xml.Directive:
			if dp, ok := xmlTree.(DirectiveParser); ok {
				dp.Directive(xt.Copy(), dec)
			}
		}

		t, err = dec.Token()
	}

	if err == io.EOF {
		err = nil
	}

	return xmlTree, err
}

func ParseXML ( r io . Reader , op ... ParseSettings ) ( tree . Node , error ) { ov := ParseOptions { Strict : true , XMLRoot : xmlele . Root , } for _ , i := range op { i ( & ov ) } dec := xml . NewDecoder ( r ) dec . CharsetReader = charset . NewReaderLabel dec . Strict = ov . Strict ordrPos := 1 xmlTree := ov . XMLRoot ( ) t , err := dec . Token ( ) if err != nil { return nil , err } if head , ok := t . ( xml . ProcInst ) ; ok && head . Target == " " { t , err = dec . Token ( ) } opts := xmlbuilder . BuilderOpts { Dec : dec , } for err == nil { switch xt := t . ( type ) { case xml . StartElement : setEle ( & opts , xmlTree , xt , & ordrPos ) xmlTree = xmlTree . CreateNode ( & opts ) case xml . CharData : setNode ( & opts , xmlTree , xt , tree . NtChd , & ordrPos ) xmlTree = xmlTree . CreateNode ( & opts ) case xml . Comment : setNode ( & opts , xmlTree , xt , tree . NtComm , & ordrPos ) xmlTree = xmlTree . CreateNode ( & opts ) case xml . ProcInst : setNode ( & opts , xmlTree , xt , tree . NtPi , & ordrPos ) xmlTree = xmlTree . CreateNode ( & opts ) case xml . EndElement : xmlTree = xmlTree . EndElem ( ) case xml . Directive : if dp , ok := xmlTree . ( DirectiveParser ) ; ok { dp . Directive ( xt . Copy ( ) , dec ) } } t , err = dec . Token ( ) } if err == io . EOF { err = nil } return xmlTree , err }

//ParseXML creates an XMLTree structure from an io.Reader.

ParseXML creates an XMLTree structure from an io . Reader .


func (w Wrap) Call(c Ctx, args ...Result) (Result, error) {
	switch w.LastArgOpt {
	case Optional:
		if len(args) == w.NArgs || len(args) == w.NArgs-1 {
			return w.Fn(c, args...)
		}
	case Variadic:
		if len(args) >= w.NArgs-1 {
			return w.Fn(c, args...)
		}
	default:
		if len(args) == w.NArgs {
			return w.Fn(c, args...)
		}
	}
	return nil, fmt.Errorf("Invalid number of arguments")
}

func ( w Wrap ) Call ( c Ctx , args ... Result ) ( Result , error ) { switch w . LastArgOpt { case Optional : if len ( args ) == w . NArgs || len ( args ) == w . NArgs - 1 { return w . Fn ( c , args ... ) } case Variadic : if len ( args ) >= w . NArgs - 1 { return w . Fn ( c , args ... ) } default : if len ( args ) == w . NArgs { return w . Fn ( c , args ... ) } } return nil , fmt . Errorf ( " " ) }

//Call checks the arguments and calls Fn if they are valid


func Parse(xp string) (XPathExec, error) {
	n, err := parser.Parse(xp)
	return XPathExec{n: n}, err
}

func Parse ( xp string ) ( XPathExec , error ) { n , err := parser . Parse ( xp ) return XPathExec { n : n } , err }

//Parse parses the XPath expression, xp, returning an XPath executor.

Parse parses the XPath expression xp returning an XPath executor .


func MustParse(xp string) XPathExec {
	ret, err := Parse(xp)
	if err != nil {
		panic(err)
	}
	return ret
}

func MustParse ( xp string ) XPathExec { ret , err := Parse ( xp ) if err != nil { panic ( err ) } return ret }

//MustParse is like Parse, but panics instead of returning an error.

MustParse is like Parse but panics instead of returning an error .


func (xp XPathExec) Exec(t tree.Node, opts ...FuncOpts) (tree.Result, error) {
	o := &Opts{
		NS:    make(map[string]string),
		Funcs: make(map[xml.Name]tree.Wrap),
		Vars:  make(map[string]tree.Result),
	}
	for _, i := range opts {
		i(o)
	}
	return execxp.Exec(xp.n, t, o.NS, o.Funcs, o.Vars)
}

func ( xp XPathExec ) Exec ( t tree . Node , opts ... FuncOpts ) ( tree . Result , error ) { o := & Opts { NS : make ( map [ string ] string ) , Funcs : make ( map [ xml . Name ] tree . Wrap ) , Vars : make ( map [ string ] tree . Result ) , } for _ , i := range opts { i ( o ) } return execxp . Exec ( xp . n , t , o . NS , o . Funcs , o . Vars ) }

//Exec executes the XPath expression, xp, against the tree, t, with the
//namespace mappings, ns, and returns the result as a stringer.

Exec executes the XPath expression xp against the tree t with the namespace mappings ns and returns the result as a stringer .


func (xp XPathExec) ExecBool(t tree.Node, opts ...FuncOpts) (bool, error) {
	res, err := xp.Exec(t, opts...)
	if err != nil {
		return false, err
	}

	b, ok := res.(tree.IsBool)
	if !ok {
		return false, fmt.Errorf("Cannot convert result to a boolean")
	}

	return bool(b.Bool()), nil
}

func ( xp XPathExec ) ExecBool ( t tree . Node , opts ... FuncOpts ) ( bool , error ) { res , err := xp . Exec ( t , opts ... ) if err != nil { return false , err } b , ok := res . ( tree . IsBool ) if ! ok { return false , fmt . Errorf ( " " ) } return bool ( b . Bool ( ) ) , nil }

//ExecBool is like Exec, except it will attempt to convert the result to its boolean value.

ExecBool is like Exec except it will attempt to convert the result to its boolean value .


func (xp XPathExec) ExecNum(t tree.Node, opts ...FuncOpts) (float64, error) {
	res, err := xp.Exec(t, opts...)
	if err != nil {
		return 0, err
	}

	n, ok := res.(tree.IsNum)
	if !ok {
		return 0, fmt.Errorf("Cannot convert result to a number")
	}

	return float64(n.Num()), nil
}

func ( xp XPathExec ) ExecNum ( t tree . Node , opts ... FuncOpts ) ( float64 , error ) { res , err := xp . Exec ( t , opts ... ) if err != nil { return 0 , err } n , ok := res . ( tree . IsNum ) if ! ok { return 0 , fmt . Errorf ( " " ) } return float64 ( n . Num ( ) ) , nil }

//ExecNum is like Exec, except it will attempt to convert the result to its number value.

ExecNum is like Exec except it will attempt to convert the result to its number value .


func (xp XPathExec) ExecNode(t tree.Node, opts ...FuncOpts) (tree.NodeSet, error) {
	res, err := xp.Exec(t, opts...)
	if err != nil {
		return nil, err
	}

	n, ok := res.(tree.NodeSet)
	if !ok {
		return nil, fmt.Errorf("Cannot convert result to a node-set")
	}

	return n, nil
}

func ( xp XPathExec ) ExecNode ( t tree . Node , opts ... FuncOpts ) ( tree . NodeSet , error ) { res , err := xp . Exec ( t , opts ... ) if err != nil { return nil , err } n , ok := res . ( tree . NodeSet ) if ! ok { return nil , fmt . Errorf ( " " ) } return n , nil }

//ExecNode is like Exec, except it will attempt to return the result as a node-set.

ExecNode is like Exec except it will attempt to return the result as a node - set .


func (xp XPathExec) MustExec(t tree.Node, opts ...FuncOpts) tree.Result {
	res, err := xp.Exec(t, opts...)
	if err != nil {
		panic(err)
	}
	return res
}

func ( xp XPathExec ) MustExec ( t tree . Node , opts ... FuncOpts ) tree . Result { res , err := xp . Exec ( t , opts ... ) if err != nil { panic ( err ) } return res }

//MustExec is like Exec, but panics instead of returning an error.

MustExec is like Exec but panics instead of returning an error .


func ParseExec(xpstr string, t tree.Node, opts ...FuncOpts) (tree.Result, error) {
	xp, err := Parse(xpstr)
	if err != nil {
		return nil, err
	}
	return xp.Exec(t, opts...)
}

func ParseExec ( xpstr string , t tree . Node , opts ... FuncOpts ) ( tree . Result , error ) { xp , err := Parse ( xpstr ) if err != nil { return nil , err } return xp . Exec ( t , opts ... ) }

//ParseExec parses the XPath string, xpstr, and runs Exec.

ParseExec parses the XPath string xpstr and runs Exec .


func (x *XMLEle) CreateNode(opts *xmlbuilder.BuilderOpts) xmlbuilder.XMLBuilder {
	if opts.NodeType == tree.NtElem {
		ele := &XMLEle{
			StartElement: opts.Tok.(xml.StartElement),
			NSBuilder:    tree.NSBuilder{NS: opts.NS},
			Attrs:        make([]tree.Node, len(opts.Attrs)),
			Parent:       x,
			NodePos:      tree.NodePos(opts.NodePos),
			NodeType:     opts.NodeType,
		}
		for i := range opts.Attrs {
			ele.Attrs[i] = xmlnode.XMLNode{
				Token:    opts.Attrs[i],
				NodePos:  tree.NodePos(opts.AttrStartPos + i),
				NodeType: tree.NtAttr,
				Parent:   ele,
			}
		}
		x.Children = append(x.Children, ele)
		return ele
	}

	node := xmlnode.XMLNode{
		Token:    opts.Tok,
		NodePos:  tree.NodePos(opts.NodePos),
		NodeType: opts.NodeType,
		Parent:   x,
	}
	x.Children = append(x.Children, node)
	return x
}

func ( x * XMLEle ) CreateNode ( opts * xmlbuilder . BuilderOpts ) xmlbuilder . XMLBuilder { if opts . NodeType == tree . NtElem { ele := & XMLEle { StartElement : opts . Tok . ( xml . StartElement ) , NSBuilder : tree . NSBuilder { NS : opts . NS } , Attrs : make ( [ ] tree . Node , len ( opts . Attrs ) ) , Parent : x , NodePos : tree . NodePos ( opts . NodePos ) , NodeType : opts . NodeType , } for i := range opts . Attrs { ele . Attrs [ i ] = xmlnode . XMLNode { Token : opts . Attrs [ i ] , NodePos : tree . NodePos ( opts . AttrStartPos + i ) , NodeType : tree . NtAttr , Parent : ele , } } x . Children = append ( x . Children , ele ) return ele } node := xmlnode . XMLNode { Token : opts . Tok , NodePos : tree . NodePos ( opts . NodePos ) , NodeType : opts . NodeType , Parent : x , } x . Children = append ( x . Children , node ) return x }

//CreateNode is an implementation of xmlbuilder.XMLBuilder.  It appends the node
//specified in opts and returns the child if it is an element.  Otherwise, it returns x.

CreateNode is an implementation of xmlbuilder . XMLBuilder . It appends the node specified in opts and returns the child if it is an element . Otherwise it returns x .


func (x *XMLEle) GetChildren() []tree.Node {
	ret := make([]tree.Node, len(x.Children))

	for i := range x.Children {
		ret[i] = x.Children[i]
	}

	return ret
}

func ( x * XMLEle ) GetChildren ( ) [ ] tree . Node { ret := make ( [ ] tree . Node , len ( x . Children ) ) for i := range x . Children { ret [ i ] = x . Children [ i ] } return ret }

//GetChildren returns all child nodes of the element


func (x *XMLEle) GetAttrs() []tree.Node {
	ret := make([]tree.Node, len(x.Attrs))
	for i := range x.Attrs {
		ret[i] = x.Attrs[i]
	}
	return ret
}

func ( x * XMLEle ) GetAttrs ( ) [ ] tree . Node { ret := make ( [ ] tree . Node , len ( x . Attrs ) ) for i := range x . Attrs { ret [ i ] = x . Attrs [ i ] } return ret }

//GetAttrs returns all attributes of the element


func (x *XMLEle) ResValue() string {
	ret := ""
	for i := range x.Children {
		switch x.Children[i].GetNodeType() {
		case tree.NtChd, tree.NtElem, tree.NtRoot:
			ret += x.Children[i].ResValue()
		}
	}
	return ret
}

func ( x * XMLEle ) ResValue ( ) string { ret := " " for i := range x . Children { switch x . Children [ i ] . GetNodeType ( ) { case tree . NtChd , tree . NtElem , tree . NtRoot : ret += x . Children [ i ] . ResValue ( ) } } return ret }

//ResValue returns the string value of the element and children


func Parse(xp string) (*Node, error) {
	var err error
	c := lexer.Lex(xp)
	n := &Node{}
	p := &parseStack{cur: n}

	for next := range c {
		if next.Typ != lexer.XItemError {
			parseMap[next.Typ](p, next)
		} else if err == nil {
			err = fmt.Errorf(next.Val)
		}
	}

	return n, err
}

func Parse ( xp string ) ( * Node , error ) { var err error c := lexer . Lex ( xp ) n := & Node { } p := & parseStack { cur : n } for next := range c { if next . Typ != lexer . XItemError { parseMap [ next . Typ ] ( p , next ) } else if err == nil { err = fmt . Errorf ( next . Val ) } } return n , err }

//Parse creates an AST tree for XPath expressions.

Parse creates an AST tree for XPath expressions .


func (a XMLNode) GetToken() xml.Token {
	if a.NodeType == tree.NtAttr {
		ret := a.Token.(*xml.Attr)
		return *ret
	}
	return a.Token
}

func ( a XMLNode ) GetToken ( ) xml . Token { if a . NodeType == tree . NtAttr { ret := a . Token . ( * xml . Attr ) return * ret } return a . Token }

//GetToken returns the xml.Token representation of the node

GetToken returns the xml . Token representation of the node


func (a XMLNode) ResValue() string {
	switch a.NodeType {
	case tree.NtAttr:
		return a.Token.(*xml.Attr).Value
	case tree.NtChd:
		return string(a.Token.(xml.CharData))
	case tree.NtComm:
		return string(a.Token.(xml.Comment))
	}
	//case tree.NtPi:
	return string(a.Token.(xml.ProcInst).Inst)
}

func
(
a
XMLNode
)
ResValue
(
)
string
{
switch
a
.
NodeType
{
case
tree
.
NtAttr
:
return
a
.
Token
.
(
*
xml
.
Attr
)
.
Value
case
tree
.
NtChd
:
return
string
(
a
.
Token
.
(
xml
.
CharData
)
)
case
tree
.
NtComm
:
return
string
(
a
.
Token
.
(
xml
.
Comment
)
)
}
//case tree.NtPi:
return
string
(
a
.
Token
.
(
xml
.
ProcInst
)
.
Inst
)
}

//ResValue returns the string value of the attribute


func Exec(n *parser.Node, t tree.Node, ns map[string]string, fns map[xml.Name]tree.Wrap, v map[string]tree.Result) (tree.Result, error) {
	f := xpFilt{
		t:         t,
		ns:        ns,
		ctx:       tree.NodeSet{t},
		fns:       fns,
		variables: v,
	}

	return exec(&f, n)
}

func Exec ( n * parser . Node , t tree . Node , ns map [ string ] string , fns map [ xml . Name ] tree . Wrap , v map [ string ] tree . Result ) ( tree . Result , error ) { f := xpFilt { t : t , ns : ns , ctx : tree . NodeSet { t } , fns : fns , variables : v , } return exec ( & f , n ) }

//Exec executes the XPath expression, xp, against the tree, t, with the
//namespace mappings, ns.

Exec executes the XPath expression xp against the tree t with the namespace mappings ns .


func (n Num) String() string {
	if math.IsInf(float64(n), 0) {
		if math.IsInf(float64(n), 1) {
			return "Infinity"
		}
		return "-Infinity"
	}
	return fmt.Sprintf("%g", float64(n))
}

func ( n Num ) String ( ) string { if math . IsInf ( float64 ( n ) , 0 ) { if math . IsInf ( float64 ( n ) , 1 ) { return " " } return " " } return fmt . Sprintf ( " " , float64 ( n ) ) }

//ResValue satisfies the Res interface for Num


func (s String) Num() Num {
	num, err := strconv.ParseFloat(strings.TrimSpace(string(s)), 64)
	if err != nil {
		return Num(math.NaN())
	}
	return Num(num)
}

func ( s String ) Num ( ) Num { num , err := strconv . ParseFloat ( strings . TrimSpace ( string ( s ) ) , 64 ) if err != nil { return Num ( math . NaN ( ) ) } return Num ( num ) }

//Num satisfies the HasNum interface for String's

Num satisfies the HasNum interface for String s


func BuildNS(t Elem) (ret []NS) {
	vals := make(map[xml.Name]string)

	if nselem, ok := t.(NSElem); ok {
		buildNS(nselem, vals)

		ret = make([]NS, 0, len(vals))
		i := 1

		for k, v := range vals {
			if !(k.Local == "xmlns" && k.Space == "" && v == "") {
				ret = append(ret, NS{
					Attr:     xml.Attr{Name: k, Value: v},
					Parent:   t,
					NodeType: NtNs,
				})
				i++
			}
		}

		sort.Sort(nsValueSort(ret))
		for i := range ret {
			ret[i].NodePos = NodePos(t.Pos() + i + 1)
		}
	}

	return ret
}

func BuildNS ( t Elem ) ( ret [ ] NS ) { vals := make ( map [ xml . Name ] string ) if nselem , ok := t . ( NSElem ) ; ok { buildNS ( nselem , vals ) ret = make ( [ ] NS , 0 , len ( vals ) ) i := 1 for k , v := range vals { if ! ( k . Local == " " && k . Space == " " && v == " " ) { ret = append ( ret , NS { Attr : xml . Attr { Name : k , Value : v } , Parent : t , NodeType : NtNs , } ) i ++ } } sort . Sort ( nsValueSort ( ret ) ) for i := range ret { ret [ i ] . NodePos = NodePos ( t . Pos ( ) + i + 1 ) } } return ret }

//BuildNS resolves all the namespace nodes of the element and returns them


func GetAttribute(n Elem, local, space string) (xml.Attr, bool) {
	attrs := n.GetAttrs()
	for _, i := range attrs {
		attr := i.GetToken().(xml.Attr)
		if local == attr.Name.Local && space == attr.Name.Space {
			return attr, true
		}
	}
	return xml.Attr{}, false
}

func GetAttribute ( n Elem , local , space string ) ( xml . Attr , bool ) { attrs := n . GetAttrs ( ) for _ , i := range attrs { attr := i . GetToken ( ) . ( xml . Attr ) if local == attr . Name . Local && space == attr . Name . Space { return attr , true } } return xml . Attr { } , false }

//GetAttribute is a convenience function for getting the specified attribute from an element.
//false is returned if the attribute is not found.

GetAttribute is a convenience function for getting the specified attribute from an element . false is returned if the attribute is not found .


func GetAttributeVal(n Elem, local, space string) (string, bool) {
	attr, ok := GetAttribute(n, local, space)
	return attr.Value, ok
}

func GetAttributeVal ( n Elem , local , space string ) ( string , bool ) { attr , ok := GetAttribute ( n , local , space ) return attr . Value , ok }

//GetAttributeVal is like GetAttribute, except it returns the attribute's value.

GetAttributeVal is like GetAttribute except it returns the attribute s value .


func GetAttrValOrEmpty(n Elem, local, space string) string {
	val, ok := GetAttributeVal(n, local, space)
	if !ok {
		return ""
	}
	return val
}

func GetAttrValOrEmpty ( n Elem , local , space string ) string { val , ok := GetAttributeVal ( n , local , space ) if ! ok { return " " } return val }

//GetAttrValOrEmpty is like GetAttributeVal, except it returns an empty string if
//the attribute is not found instead of false.

GetAttrValOrEmpty is like GetAttributeVal except it returns an empty string if the attribute is not found instead of false .


func FindNodeByPos(n Node, pos int) Node {
	if n.Pos() == pos {
		return n
	}

	if elem, ok := n.(Elem); ok {
		chldrn := elem.GetChildren()
		for i := 1; i < len(chldrn); i++ {
			if chldrn[i-1].Pos() <= pos && chldrn[i].Pos() > pos {
				return FindNodeByPos(chldrn[i-1], pos)
			}
		}

		if len(chldrn) > 0 {
			if chldrn[len(chldrn)-1].Pos() <= pos {
				return FindNodeByPos(chldrn[len(chldrn)-1], pos)
			}
		}

		attrs := elem.GetAttrs()
		for _, i := range attrs {
			if i.Pos() == pos {
				return i
			}
		}

		ns := BuildNS(elem)
		for _, i := range ns {
			if i.Pos() == pos {
				return i
			}
		}
	}

	return nil
}

func FindNodeByPos ( n Node , pos int ) Node { if n . Pos ( ) == pos { return n } if elem , ok := n . ( Elem ) ; ok { chldrn := elem . GetChildren ( ) for i := 1 ; i < len ( chldrn ) ; i ++ { if chldrn [ i - 1 ] . Pos ( ) <= pos && chldrn [ i ] . Pos ( ) > pos { return FindNodeByPos ( chldrn [ i - 1 ] , pos ) } } if len ( chldrn ) > 0 { if chldrn [ len ( chldrn ) - 1 ] . Pos ( ) <= pos { return FindNodeByPos ( chldrn [ len ( chldrn ) - 1 ] , pos ) } } attrs := elem . GetAttrs ( ) for _ , i := range attrs { if i . Pos ( ) == pos { return i } } ns := BuildNS ( elem ) for _ , i := range ns { if i . Pos ( ) == pos { return i } } } return nil }

//FindNodeByPos finds a node from the given position.  Returns nil if the node
//is not found.

FindNodeByPos finds a node from the given position . Returns nil if the node is not found .


func Marshal(n tree.Node, w io.Writer) error {
	return marshal(n, w)
}

func Marshal ( n tree . Node , w io . Writer ) error { return marshal ( n , w ) }

//Marshal prints the result tree, r, in XML form to w.

Marshal prints the result tree r in XML form to w .


func MarshalStr(n tree.Node) (string, error) {
	ret := bytes.NewBufferString("")
	err := marshal(n, ret)

	return ret.String(), err
}

func MarshalStr ( n tree . Node ) ( string , error ) { ret := bytes . NewBufferString ( " " ) err := marshal ( n , ret ) return ret . String ( ) , err }

//MarshalStr is like Marhal, but returns a string.

MarshalStr is like Marhal but returns a string .


func NewLexer(r io.Reader, posix, whitespacesplit bool) *Lexer {
	return &Lexer{
		reader:          bufio.NewReader(r),
		tokenizer:       &DefaultTokenizer{},
		posix:           posix,
		whitespacesplit: whitespacesplit,
	}
}

func NewLexer ( r io . Reader , posix , whitespacesplit bool ) * Lexer { return & Lexer { reader : bufio . NewReader ( r ) , tokenizer : & DefaultTokenizer { } , posix : posix , whitespacesplit : whitespacesplit , } }

// NewLexer creates a new Lexer reading from io.Reader.  This Lexer
// has a DefaultTokenizer according to posix and whitespacesplit
// rules.

NewLexer creates a new Lexer reading from io . Reader . This Lexer has a DefaultTokenizer according to posix and whitespacesplit rules .


func NewLexerString(s string, posix, whitespacesplit bool) *Lexer {
	return NewLexer(strings.NewReader(s), posix, whitespacesplit)
}

func NewLexerString ( s string , posix , whitespacesplit bool ) * Lexer { return NewLexer ( strings . NewReader ( s ) , posix , whitespacesplit ) }

// NewLexerString creates a new Lexer reading from a string.  This
// Lexer has a DefaultTokenizer according to posix and whitespacesplit
// rules.

NewLexerString creates a new Lexer reading from a string . This Lexer has a DefaultTokenizer according to posix and whitespacesplit rules .


func Split(s string, posix bool) ([]string, error) {
	return NewLexerString(s, posix, true).Split()
}

func Split ( s string , posix bool ) ( [ ] string , error ) { return NewLexerString ( s , posix , true ) . Split ( ) }

// Split splits a string according to posix or non-posix rules.

Split splits a string according to posix or non - posix rules .


func (r *registry) Register(err *ErrDescriptor) {
	r.Lock()
	defer r.Unlock()

	if err.Code == NoCode {
		panic(fmt.Errorf("No code defined in error descriptor (message: `%s`)", err.MessageFormat))
	}

	if r.byCode[err.Code] != nil {
		panic(fmt.Errorf("errors: Duplicate error code %v registered", err.Code))
	}

	err.registered = true
	r.byCode[err.Code] = err
}

func ( r * registry ) Register ( err * ErrDescriptor ) { r . Lock ( ) defer r . Unlock ( ) if err . Code == NoCode { panic ( fmt . Errorf ( " " , err . MessageFormat ) ) } if r . byCode [ err . Code ] != nil { panic ( fmt . Errorf ( " " , err . Code ) ) } err . registered = true r . byCode [ err . Code ] = err }


func (r *registry) Get(code Code) *ErrDescriptor {
	r.RLock()
	defer r.RUnlock()
	return r.byCode[code]
}

func ( r * registry ) Get ( code Code ) * ErrDescriptor { r . RLock ( ) defer r . RUnlock ( ) return r . byCode [ code ] }

// Get returns the descriptor if it exists or nil otherwise


func (r *registry) GetAll() []*ErrDescriptor {
	r.RLock()
	defer r.RUnlock()

	res := make([]*ErrDescriptor, 0, len(r.byCode))
	for _, d := range r.byCode {
		res = append(res, d)
	}
	return res
}

func ( r * registry ) GetAll ( ) [ ] * ErrDescriptor { r . RLock ( ) defer r . RUnlock ( ) res := make ( [ ] * ErrDescriptor , 0 , len ( r . byCode ) ) for _ , d := range r . byCode { res = append ( res , d ) } return res }

// GetAll returns all registered error descriptors


func From(in error) Error {
	if err, ok := in.(Error); ok {
		return err
	}

	return FromGRPC(in)
}

func From ( in error ) Error { if err , ok := in . ( Error ) ; ok { return err } return FromGRPC ( in ) }


func Descriptor(in error) (desc *ErrDescriptor) {
	err := From(in)
	descriptor := Get(err.Code())
	if descriptor != nil {
		return descriptor
	}

	// return a new error descriptor with sane defaults
	return &ErrDescriptor{
		MessageFormat: err.Error(),
		Type:          err.Type(),
		Code:          err.Code(),
	}
}

// Descriptor returns the error descriptor from any error


func GetAttributes(err error) Attributes {
	e, ok := err.(Error)
	if ok {
		return e.Attributes()
	}

	return Attributes{}
}

func GetAttributes ( err error ) Attributes { e , ok := err . ( Error ) if ok { return e . Attributes ( ) } return Attributes { } }

// GetAttributes returns the error attributes or falls back
// to empty attributes

GetAttributes returns the error attributes or falls back to empty attributes


func (t Type) HTTPStatusCode() int {
	switch t {
	case Canceled:
		return http.StatusRequestTimeout
	case InvalidArgument:
		return http.StatusBadRequest
	case OutOfRange:
		return http.StatusBadRequest
	case NotFound:
		return http.StatusNotFound
	case Conflict:
		return http.StatusConflict
	case AlreadyExists:
		return http.StatusConflict
	case Unauthorized:
		return http.StatusUnauthorized
	case PermissionDenied:
		return http.StatusForbidden
	case Timeout:
		return http.StatusRequestTimeout
	case NotImplemented:
		return http.StatusNotImplemented
	case TemporarilyUnavailable:
		return http.StatusBadGateway
	case PermanentlyUnavailable:
		return http.StatusGone
	case ResourceExhausted:
		return http.StatusForbidden
	case Internal:
		return http.StatusInternalServerError
	case Unknown:
		return http.StatusInternalServerError
	}

	return http.StatusInternalServerError
}

func ( t Type ) HTTPStatusCode ( ) int { switch t { case Canceled : return http . StatusRequestTimeout case InvalidArgument : return http . StatusBadRequest case OutOfRange : return http . StatusBadRequest case NotFound : return http . StatusNotFound case Conflict : return http . StatusConflict case AlreadyExists : return http . StatusConflict case Unauthorized : return http . StatusUnauthorized case PermissionDenied : return http . StatusForbidden case Timeout : return http . StatusRequestTimeout case NotImplemented : return http . StatusNotImplemented case TemporarilyUnavailable : return http . StatusBadGateway case PermanentlyUnavailable : return http . StatusGone case ResourceExhausted : return http . StatusForbidden case Internal : return http . StatusInternalServerError case Unknown : return http . StatusInternalServerError } return http . StatusInternalServerError }

// HTTPStatusCode returns the corresponding http status code from an error type


func HTTPStatusCode(err error) int {
	e, ok := err.(Error)
	if ok {
		return e.Type().HTTPStatusCode()
	}

	return http.StatusInternalServerError
}

func HTTPStatusCode ( err error ) int { e , ok := err . ( Error ) if ok { return e . Type ( ) . HTTPStatusCode ( ) } return http . StatusInternalServerError }

// HTTPStatusCode returns the HTTP status code for the given error or 500 if it doesn't know

HTTPStatusCode returns the HTTP status code for the given error or 500 if it doesn t know


func HTTPStatusToType(status int) Type {
	switch status {
	case http.StatusBadRequest:
		return InvalidArgument
	case http.StatusNotFound:
		return NotFound
	case http.StatusConflict:
		return Conflict
	case http.StatusUnauthorized:
		return Unauthorized
	case http.StatusForbidden:
		return PermissionDenied
	case http.StatusRequestTimeout:
		return Timeout
	case http.StatusNotImplemented:
		return NotImplemented
	case http.StatusBadGateway:
	case http.StatusServiceUnavailable:
		return TemporarilyUnavailable
	case http.StatusGone:
		return PermanentlyUnavailable
	case http.StatusTooManyRequests:
		return ResourceExhausted
	case http.StatusInternalServerError:
		return Unknown
	}
	return Unknown
}

func HTTPStatusToType ( status int ) Type { switch status { case http . StatusBadRequest : return InvalidArgument case http . StatusNotFound : return NotFound case http . StatusConflict : return Conflict case http . StatusUnauthorized : return Unauthorized case http . StatusForbidden : return PermissionDenied case http . StatusRequestTimeout : return Timeout case http . StatusNotImplemented : return NotImplemented case http . StatusBadGateway : case http . StatusServiceUnavailable : return TemporarilyUnavailable case http . StatusGone : return PermanentlyUnavailable case http . StatusTooManyRequests : return ResourceExhausted case http . StatusInternalServerError : return Unknown } return Unknown }

// HTTPStatusToType infers the error Type from a HTTP Status code


func ToHTTP(in error, w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json")
	if err, ok := in.(Error); ok {
		w.Header().Set(CodeHeader, err.Code().String())
		w.WriteHeader(err.Type().HTTPStatusCode())
		return json.NewEncoder(w).Encode(toJSON(err))
	}

	w.WriteHeader(http.StatusInternalServerError)
	return json.NewEncoder(w).Encode(&jsonError{
		Message: in.Error(),
		Type:    Unknown,
	})
}

func ToHTTP ( in error , w http . ResponseWriter ) error { w . Header ( ) . Set ( " " , " " ) if err , ok := in . ( Error ) ; ok { w . Header ( ) . Set ( CodeHeader , err . Code ( ) . String ( ) ) w . WriteHeader ( err . Type ( ) . HTTPStatusCode ( ) ) return json . NewEncoder ( w ) . Encode ( toJSON ( err ) ) } w . WriteHeader ( http . StatusInternalServerError ) return json . NewEncoder ( w ) . Encode ( & jsonError { Message : in . Error ( ) , Type : Unknown , } ) }

// ToHTTP writes the error to the http response


func toImpl(err Error) *impl {
	if i, ok := err.(*impl); ok {
		return i
	}

	return &impl{
		message:    err.Error(),
		code:       err.Code(),
		typ:        err.Type(),
		attributes: err.Attributes(),
	}
}

func toImpl ( err Error ) * impl { if i , ok := err . ( * impl ) ; ok { return i } return & impl { message : err . Error ( ) , code : err . Code ( ) , typ : err . Type ( ) , attributes : err . Attributes ( ) , } }

// toImpl creates an equivalent impl for any Error


func MetadataFromIncomingContext(ctx context.Context) metadata.MD {
	md, _ := metadata.FromIncomingContext(ctx)
	return md
}

func MetadataFromIncomingContext ( ctx context . Context ) metadata . MD { md , _ := metadata . FromIncomingContext ( ctx ) return md }

// MetadataFromIncomingContext gets the metadata from the given context


func MetadataFromOutgoingContext(ctx context.Context) metadata.MD {
	md, _ := metadata.FromOutgoingContext(ctx)
	return md
}

func MetadataFromOutgoingContext ( ctx context . Context ) metadata . MD { md , _ := metadata . FromOutgoingContext ( ctx ) return md }

// MetadataFromOutgoingContext gets the metadata from the given context


func TokenFromMetadata(md metadata.MD) (string, error) {
	token, ok := md["token"]
	if !ok || len(token) == 0 {
		return "", ErrNoToken
	}
	return token[0], nil
}

func TokenFromMetadata ( md metadata . MD ) ( string , error ) { token , ok := md [ " " ] if ! ok || len ( token ) == 0 { return " " , ErrNoToken } return token [ 0 ] , nil }

// TokenFromMetadata gets the token from the metadata or returns ErrNoToken


func TokenFromIncomingContext(ctx context.Context) (string, error) {
	md := MetadataFromIncomingContext(ctx)
	return TokenFromMetadata(md)
}

func TokenFromIncomingContext ( ctx context . Context ) ( string , error ) { md := MetadataFromIncomingContext ( ctx ) return TokenFromMetadata ( md ) }

// TokenFromIncomingContext gets the token from the incoming context or returns ErrNoToken


func OutgoingContextWithToken(ctx context.Context, token string) context.Context {
	return outgoingContextWithMergedMetadata(ctx, "token", token)
}

func OutgoingContextWithToken ( ctx context . Context , token string ) context . Context { return outgoingContextWithMergedMetadata ( ctx , " " , token ) }

// OutgoingContextWithToken returns an outgoing context with the token


func KeyFromMetadata(md metadata.MD) (string, error) {
	key, ok := md["key"]
	if !ok || len(key) == 0 {
		return "", ErrNoKey
	}
	return key[0], nil
}

func KeyFromMetadata ( md metadata . MD ) ( string , error ) { key , ok := md [ " " ] if ! ok || len ( key ) == 0 { return " " , ErrNoKey } return key [ 0 ] , nil }

// KeyFromMetadata gets the key from the metadata or returns ErrNoKey


func KeyFromIncomingContext(ctx context.Context) (string, error) {
	md := MetadataFromIncomingContext(ctx)
	return KeyFromMetadata(md)
}

func KeyFromIncomingContext ( ctx context . Context ) ( string , error ) { md := MetadataFromIncomingContext ( ctx ) return KeyFromMetadata ( md ) }

// KeyFromIncomingContext gets the key from the incoming context or returns ErrNoKey


func OutgoingContextWithKey(ctx context.Context, key string) context.Context {
	return outgoingContextWithMergedMetadata(ctx, "key", key)
}

func OutgoingContextWithKey ( ctx context . Context , key string ) context . Context { return outgoingContextWithMergedMetadata ( ctx , " " , key ) }

// OutgoingContextWithKey returns an outgoing context with the key


func IDFromMetadata(md metadata.MD) (string, error) {
	id, ok := md["id"]
	if !ok || len(id) == 0 {
		return "", ErrNoID
	}
	return id[0], nil
}

func IDFromMetadata ( md metadata . MD ) ( string , error ) { id , ok := md [ " " ] if ! ok || len ( id ) == 0 { return " " , ErrNoID } return id [ 0 ] , nil }

// IDFromMetadata gets the key from the metadata or returns ErrNoID


func IDFromIncomingContext(ctx context.Context) (string, error) {
	md := MetadataFromIncomingContext(ctx)
	return IDFromMetadata(md)
}

func IDFromIncomingContext ( ctx context . Context ) ( string , error ) { md := MetadataFromIncomingContext ( ctx ) return IDFromMetadata ( md ) }

// IDFromIncomingContext gets the key from the incoming context or returns ErrNoID


func OutgoingContextWithID(ctx context.Context, id string) context.Context {
	return outgoingContextWithMergedMetadata(ctx, "id", id)
}

func OutgoingContextWithID ( ctx context . Context , id string ) context . Context { return outgoingContextWithMergedMetadata ( ctx , " " , id ) }

// OutgoingContextWithID returns an outgoing context with the id


func ServiceInfoFromMetadata(md metadata.MD) (serviceName, serviceVersion, netAddress string, err error) {
	serviceNameL, ok := md["service-name"]
	if ok && len(serviceNameL) > 0 {
		serviceName = serviceNameL[0]
	}
	serviceVersionL, ok := md["service-version"]
	if ok && len(serviceVersionL) > 0 {
		serviceVersion = serviceVersionL[0]
	}
	netAddressL, ok := md["net-address"]
	if ok && len(netAddressL) > 0 {
		netAddress = netAddressL[0]
	}
	return
}

func ServiceInfoFromMetadata ( md metadata . MD ) ( serviceName , serviceVersion , netAddress string , err error ) { serviceNameL , ok := md [ " " ] if ok && len ( serviceNameL ) > 0 { serviceName = serviceNameL [ 0 ] } serviceVersionL , ok := md [ " " ] if ok && len ( serviceVersionL ) > 0 { serviceVersion = serviceVersionL [ 0 ] } netAddressL , ok := md [ " " ] if ok && len ( netAddressL ) > 0 { netAddress = netAddressL [ 0 ] } return }

// ServiceInfoFromMetadata gets the service information from the metadata or returns empty strings


func ServiceInfoFromIncomingContext(ctx context.Context) (serviceName, serviceVersion, netAddress string, err error) {
	md := MetadataFromIncomingContext(ctx)
	return ServiceInfoFromMetadata(md)
}

func ServiceInfoFromIncomingContext ( ctx context . Context ) ( serviceName , serviceVersion , netAddress string , err error ) { md := MetadataFromIncomingContext ( ctx ) return ServiceInfoFromMetadata ( md ) }

// ServiceInfoFromIncomingContext gets the service information from the incoming context or returns empty strings


func OutgoingContextWithServiceInfo(ctx context.Context, serviceName, serviceVersion, netAddress string) context.Context {
	return outgoingContextWithMergedMetadata(ctx, "service-name", serviceName, "service-version", serviceVersion, "net-address", netAddress)
}

func OutgoingContextWithServiceInfo ( ctx context . Context , serviceName , serviceVersion , netAddress string ) context . Context { return outgoingContextWithMergedMetadata ( ctx , " " , serviceName , " " , serviceVersion , " " , netAddress ) }

// OutgoingContextWithServiceInfo returns an outgoing context with the id


func LimitFromMetadata(md metadata.MD) (uint64, error) {
	limit, ok := md["limit"]
	if !ok || len(limit) == 0 {
		return 0, nil
	}
	return strconv.ParseUint(limit[0], 10, 64)
}

func LimitFromMetadata ( md metadata . MD ) ( uint64 , error ) { limit , ok := md [ " " ] if ! ok || len ( limit ) == 0 { return 0 , nil } return strconv . ParseUint ( limit [ 0 ] , 10 , 64 ) }

// LimitFromMetadata gets the limit from the metadata


func OffsetFromMetadata(md metadata.MD) (uint64, error) {
	offset, ok := md["offset"]
	if !ok || len(offset) == 0 {
		return 0, nil
	}
	return strconv.ParseUint(offset[0], 10, 64)
}

func OffsetFromMetadata ( md metadata . MD ) ( uint64 , error ) { offset , ok := md [ " " ] if ! ok || len ( offset ) == 0 { return 0 , nil } return strconv . ParseUint ( offset [ 0 ] , 10 , 64 ) }

// OffsetFromMetadata gets the offset from the metadata


func LimitAndOffsetFromIncomingContext(ctx context.Context) (limit, offset uint64, err error) {
	md := MetadataFromIncomingContext(ctx)
	limit, err = LimitFromMetadata(md)
	if err != nil {
		return 0, 0, err
	}
	offset, err = OffsetFromMetadata(md)
	if err != nil {
		return 0, 0, err
	}
	return limit, offset, nil
}

func LimitAndOffsetFromIncomingContext ( ctx context . Context ) ( limit , offset uint64 , err error ) { md := MetadataFromIncomingContext ( ctx ) limit , err = LimitFromMetadata ( md ) if err != nil { return 0 , 0 , err } offset , err = OffsetFromMetadata ( md ) if err != nil { return 0 , 0 , err } return limit , offset , nil }

// LimitAndOffsetFromIncomingContext gets the limit and offset from the incoming context


func OutgoingContextWithLimitAndOffset(ctx context.Context, limit, offset uint64) context.Context {
	var pairs []string
	if limit != 0 {
		pairs = append(pairs, "limit", strconv.FormatUint(limit, 10))
	}
	if offset != 0 {
		pairs = append(pairs, "offset", strconv.FormatUint(offset, 10))
	}
	if len(pairs) == 0 {
		return ctx
	}
	return outgoingContextWithMergedMetadata(ctx, pairs...)
}

func OutgoingContextWithLimitAndOffset ( ctx context . Context , limit , offset uint64 ) context . Context { var pairs [ ] string if limit != 0 { pairs = append ( pairs , " " , strconv . FormatUint ( limit , 10 ) ) } if offset != 0 { pairs = append ( pairs , " " , strconv . FormatUint ( offset , 10 ) ) } if len ( pairs ) == 0 { return ctx } return outgoingContextWithMergedMetadata ( ctx , pairs ... ) }

// OutgoingContextWithLimitAndOffset returns an outgoing context with the limit and offset


func before(i, j ScheduleItem) bool {
	iEnd := i.Time().UnixNano() + i.Duration().Nanoseconds()
	jStart := j.Time().UnixNano()
	if i, ok := i.(ScheduleItemWithTimestamp); ok {
		if j, ok := j.(ScheduleItemWithTimestamp); ok {
			iEnd = i.Timestamp() + i.Duration().Nanoseconds()
			jStart = j.Timestamp()
		}
	}
	return iEnd < jStart
}

func before ( i , j ScheduleItem ) bool { iEnd := i . Time ( ) . UnixNano ( ) + i . Duration ( ) . Nanoseconds ( ) jStart := j . Time ( ) . UnixNano ( ) if i , ok := i . ( ScheduleItemWithTimestamp ) ; ok { if j , ok := j . ( ScheduleItemWithTimestamp ) ; ok { iEnd = i . Timestamp ( ) + i . Duration ( ) . Nanoseconds ( ) jStart = j . Timestamp ( ) } } return iEnd < jStart }


func (err *ErrDescriptor) New(attributes Attributes) Error {
	if err.Code != NoCode && !err.registered {
		panic(fmt.Errorf("Error descriptor with code %v was not registered", err.Code))
	}

	return &impl{
		message:    Format(err.MessageFormat, attributes),
		code:       err.Code,
		typ:        err.Type,
		attributes: attributes,
	}
}

func ( err * ErrDescriptor ) New ( attributes Attributes ) Error { if err . Code != NoCode && ! err . registered { panic ( fmt . Errorf ( " " , err . Code ) ) } return & impl { message : Format ( err . MessageFormat , attributes ) , code : err . Code , typ : err . Type , attributes : attributes , } }

// New creates a new error based on the error descriptor


func WithNamespace(namespace string, ctx log.Interface) log.Interface {
	return ctx.WithField(NamespaceKey, namespace)
}

func WithNamespace ( namespace string , ctx log . Interface ) log . Interface { return ctx . WithField ( NamespaceKey , namespace ) }

// WithNamespace adds a namespace to the logging context


func Wrap(ctx log.Interface, namespaces ...string) *Namespaced {
	return &Namespaced{
		Interface: ctx,
		namespaces: &ns{
			namespaces: namespaces,
		},
	}
}

func Wrap ( ctx log . Interface , namespaces ... string ) * Namespaced { return & Namespaced { Interface : ctx , namespaces : & ns { namespaces : namespaces , } , } }

// Wrap wraps the logger in a Namespaced logger and enables the specified
// namespaces. See SetNamespaces for information on how to set the namspaces

Wrap wraps the logger in a Namespaced logger and enables the specified namespaces . See SetNamespaces for information on how to set the namspaces


func (n *Namespaced) WithField(k string, v interface{}) log.Interface {
	if k == NamespaceKey {
		if str, ok := v.(string); ok {
			return &Namespaced{
				Interface:  n.Interface,
				namespaces: n.namespaces,
				namespace:  str,
			}
		}
	}

	return &Namespaced{
		Interface:  n.Interface.WithField(k, v),
		namespaces: n.namespaces,
		namespace:  n.namespace,
	}
}

func ( n * Namespaced ) WithField ( k string , v interface { } ) log . Interface { if k == NamespaceKey { if str , ok := v . ( string ) ; ok { return & Namespaced { Interface : n . Interface , namespaces : n . namespaces , namespace : str , } } } return & Namespaced { Interface : n . Interface . WithField ( k , v ) , namespaces : n . namespaces , namespace : n . namespace , } }


func (n *Namespaced) WithFields(fields log.Fields) log.Interface {
	return &Namespaced{
		Interface:  n.Interface.WithFields(fields),
		namespaces: n.namespaces,
		namespace:  n.namespace,
	}
}

func ( n * Namespaced ) WithFields ( fields log . Fields ) log . Interface { return & Namespaced { Interface : n . Interface . WithFields ( fields ) , namespaces : n . namespaces , namespace : n . namespace , } }

// WithFields adds multiple fields to the logger


func Format(format string, values Attributes) string {
	formatter, err := messageformat.New()
	if err != nil {
		return format
	}

	fm, err := formatter.Parse(format)
	if err != nil {
		return format
	}

	fixed := make(map[string]interface{}, len(values))
	for k, v := range values {
		fixed[k] = fix(v)
	}

	// todo format unsupported types
	res, err := fm.FormatMap(fixed)
	if err != nil {
		fmt.Println("err", err)
		return format
	}

	return res
}

func
Format
(
format
string
,
values
Attributes
)
string
{
formatter
,
err
:=
messageformat
.
New
(
)
if
err
!=
{
return
format
}
fm
,
err
:=
formatter
.
Parse
(
format
)
if
err
!=
{
return
format
}
fixed
:=
make
(
map
[
string
]
interface
{
}
,
len
(
values
)
)
for
k
,
v
:=
range
values
{
fixed
[
k
]
=
fix
(
v
)
}
// todo format unsupported types
res
,
err
:=
fm
.
FormatMap
(
fixed
)
if
err
!=
{
fmt
.
Println
(
"
"
,
err
)
return
format
}
return
res
}

// Format formats the values into the provided string


func fix(v interface{}) interface{} {
	if v == nil {
		return "<nil>"
	}

	switch reflect.TypeOf(v).Kind() {
	case reflect.Bool:
	case reflect.Int:
	case reflect.Int8:
	case reflect.Int16:
	case reflect.Int32:
	case reflect.Int64:
	case reflect.Uint:
	case reflect.Uint8:
	case reflect.Uint16:
	case reflect.Uint32:
	case reflect.Uint64:
	case reflect.Uintptr:
	case reflect.Float32:
	case reflect.Float64:
		return v
	case reflect.Ptr:
		// dereference and fix
		return fix(reflect.ValueOf(v).Elem())
	}
	return fmt.Sprintf("%v", v)
}

func
fix
(
v
interface
{
}
)
interface
{
}
{
if
v
==
{
return
"
"
}
switch
reflect
.
TypeOf
(
v
)
.
Kind
(
)
{
case
reflect
.
Bool
:
case
reflect
.
Int
:
case
reflect
.
Int8
:
case
reflect
.
Int16
:
case
reflect
.
Int32
:
case
reflect
.
Int64
:
case
reflect
.
Uint
:
case
reflect
.
Uint8
:
case
reflect
.
Uint16
:
case
reflect
.
Uint32
:
case
reflect
.
Uint64
:
case
reflect
.
Uintptr
:
case
reflect
.
Float32
:
case
reflect
.
Float64
:
return
v
case
reflect
.
Ptr
:
// dereference and fix
return
fix
(
reflect
.
ValueOf
(
v
)
.
Elem
(
)
)
}
return
fmt
.
Sprintf
(
"
"
,
v
)
}

// Fix coerces types that cannot be formatted by messageformat to string


func (t Type) GRPCCode() codes.Code {
	switch t {
	case InvalidArgument:
		return codes.InvalidArgument
	case OutOfRange:
		return codes.OutOfRange
	case NotFound:
		return codes.NotFound
	case Conflict:
	case AlreadyExists:
		return codes.AlreadyExists
	case Unauthorized:
		return codes.Unauthenticated
	case PermissionDenied:
		return codes.PermissionDenied
	case Timeout:
		return codes.DeadlineExceeded
	case NotImplemented:
		return codes.Unimplemented
	case TemporarilyUnavailable:
		return codes.Unavailable
	case PermanentlyUnavailable:
		return codes.FailedPrecondition
	case Canceled:
		return codes.Canceled
	case ResourceExhausted:
		return codes.ResourceExhausted
	case Internal:
	case Unknown:
		return codes.Unknown
	}

	return codes.Unknown
}

func ( t Type ) GRPCCode ( ) codes . Code { switch t { case InvalidArgument : return codes . InvalidArgument case OutOfRange : return codes . OutOfRange case NotFound : return codes . NotFound case Conflict : case AlreadyExists : return codes . AlreadyExists case Unauthorized : return codes . Unauthenticated case PermissionDenied : return codes . PermissionDenied case Timeout : return codes . DeadlineExceeded case NotImplemented : return codes . Unimplemented case TemporarilyUnavailable : return codes . Unavailable case PermanentlyUnavailable : return codes . FailedPrecondition case Canceled : return codes . Canceled case ResourceExhausted : return codes . ResourceExhausted case Internal : case Unknown : return codes . Unknown } return codes . Unknown }

// GRPCCode returns the corresponding http status code from an error type


func GRPCCodeToType(code codes.Code) Type {
	switch code {
	case codes.InvalidArgument:
		return InvalidArgument
	case codes.OutOfRange:
		return OutOfRange
	case codes.NotFound:
		return NotFound
	case codes.AlreadyExists:
		return AlreadyExists
	case codes.Unauthenticated:
		return Unauthorized
	case codes.PermissionDenied:
		return PermissionDenied
	case codes.DeadlineExceeded:
		return Timeout
	case codes.Unimplemented:
		return NotImplemented
	case codes.Unavailable:
		return TemporarilyUnavailable
	case codes.FailedPrecondition:
		return PermanentlyUnavailable
	case codes.Canceled:
		return Canceled
	case codes.ResourceExhausted:
		return ResourceExhausted
	case codes.Unknown:
		return Unknown
	}
	return Unknown
}

func GRPCCodeToType ( code codes . Code ) Type { switch code { case codes . InvalidArgument : return InvalidArgument case codes . OutOfRange : return OutOfRange case codes . NotFound : return NotFound case codes . AlreadyExists : return AlreadyExists case codes . Unauthenticated : return Unauthorized case codes . PermissionDenied : return PermissionDenied case codes . DeadlineExceeded : return Timeout case codes . Unimplemented : return NotImplemented case codes . Unavailable : return TemporarilyUnavailable case codes . FailedPrecondition : return PermanentlyUnavailable case codes . Canceled : return Canceled case codes . ResourceExhausted : return ResourceExhausted case codes . Unknown : return Unknown } return Unknown }

// GRPCCodeToType converts the gRPC error code to an error type or returns the
// Unknown type if not possible.

GRPCCodeToType converts the gRPC error code to an error type or returns the Unknown type if not possible .


func GRPCCode(err error) codes.Code {
	e, ok := err.(Error)
	if ok {
		return e.Type().GRPCCode()
	}

	return grpc.Code(err)
}

func GRPCCode ( err error ) codes . Code { e , ok := err . ( Error ) if ok { return e . Type ( ) . GRPCCode ( ) } return grpc . Code ( err ) }

// GRPCCode returns the corresponding http status code from an error


func FromGRPC(in error) Error {
	out := &impl{
		message: grpc.ErrorDesc(in),
		typ:     GRPCCodeToType(grpc.Code(in)),
		code:    NoCode,
	}

	matches := grpcMessageFormat.FindStringSubmatch(in.Error())

	if len(matches) < 4 {
		return out
	}

	out.message = matches[1]
	out.code = parseCode(matches[2])
	_ = json.Unmarshal([]byte(matches[3]), &out.attributes)

	got := Get(Code(out.code))
	if got == nil {
		return out
	}

	return got.New(out.attributes)
}

func FromGRPC ( in error ) Error { out := & impl { message : grpc . ErrorDesc ( in ) , typ : GRPCCodeToType ( grpc . Code ( in ) ) , code : NoCode , } matches := grpcMessageFormat . FindStringSubmatch ( in . Error ( ) ) if len ( matches ) < 4 { return out } out . message = matches [ 1 ] out . code = parseCode ( matches [ 2 ] ) _ = json . Unmarshal ( [ ] byte ( matches [ 3 ] ) , & out . attributes ) got := Get ( Code ( out . code ) ) if got == nil { return out } return got . New ( out . attributes ) }

// FromGRPC parses a gRPC error and returns an Error


func ToGRPC(in error) error {
	if err, ok := in.(Error); ok {
		attrs, _ := json.Marshal(err.Attributes())
		return grpc.Errorf(err.Type().GRPCCode(), format, err.Error(), err.Code(), attrs)
	}

	return grpc.Errorf(codes.Unknown, in.Error())
}

func ToGRPC ( in error ) error { if err , ok := in . ( Error ) ; ok { attrs , _ := json . Marshal ( err . Attributes ( ) ) return grpc . Errorf ( err . Type ( ) . GRPCCode ( ) , format , err . Error ( ) , err . Code ( ) , attrs ) } return grpc . Errorf ( codes . Unknown , in . Error ( ) ) }

// ToGRPC turns an error into a gRPC error


func (n *ns) IsEnabled(namespace string) bool {
	n.RLock()
	defer n.RUnlock()

	if namespace == "" {
		return true
	}

	hasStar := false
	included := false

	for _, ns := range n.namespaces {
		// if the namspace is negated, it can never be enabled
		if ns == negate(namespace) {
			return false
		}

		// if the namespace is explicitly enabled, mark it as included
		if ns == namespace {
			included = true
		}

		// mark that we have a *
		if ns == "*" {
			hasStar = true
		}
	}

	// non-mentioned namespaces are only enabled if we got the catch-all *
	return hasStar || included
}

// isEnabled checks wether or not the namespace is enabled


func (n *ns) Set(namespaces []string) {
	n.Lock()
	defer n.Unlock()
	n.namespaces = namespaces
}

func ( n * ns ) Set ( namespaces [ ] string ) { n . Lock ( ) defer n . Unlock ( ) n . namespaces = namespaces }


func Cause(err Error) error {
	attributes := err.Attributes()
	if attributes == nil {
		return nil
	}

	cause, ok := attributes[causeKey]
	if !ok {
		return nil
	}

	switch v := cause.(type) {
	case error:
		return v
	case string:
		return errors.New(v)
	default:
		return nil
	}
}

func Cause ( err Error ) error { attributes := err . Attributes ( ) if attributes == nil { return nil } cause , ok := attributes [ causeKey ] if ! ok { return nil } switch v := cause . ( type ) { case error : return v case string : return errors . New ( v ) default : return nil } }


func parseCode(str string) Code {
	code, err := strconv.Atoi(str)
	if err != nil {
		return Code(0)
	}
	return Code(code)
}

func parseCode ( str string ) Code { code , err := strconv . Atoi ( str ) if err != nil { return Code ( 0 ) } return Code ( code ) }

// pareCode parses a string into a Code or returns 0 if the parse failed


func UnaryServerInterceptor(fn ConvertFunc) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		resp, err = handler(ctx, req)
		return resp, fn(err)
	}
}

func UnaryServerInterceptor ( fn ConvertFunc ) grpc . UnaryServerInterceptor { return func ( ctx context . Context , req interface { } , info * grpc . UnaryServerInfo , handler grpc . UnaryHandler ) ( resp interface { } , err error ) { resp , err = handler ( ctx , req ) return resp , fn ( err ) } }

// UnaryServerInterceptor applies fn to errors returned by server.

UnaryServerInterceptor applies fn to errors returned by server .


func StreamServerInterceptor(fn ConvertFunc) grpc.StreamServerInterceptor {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
		return fn(handler(srv, ss))
	}
}

func StreamServerInterceptor ( fn ConvertFunc ) grpc . StreamServerInterceptor { return func ( srv interface { } , ss grpc . ServerStream , info * grpc . StreamServerInfo , handler grpc . StreamHandler ) ( err error ) { return fn ( handler ( srv , ss ) ) } }

// StreamServerInterceptor applies fn to errors returned by server.

StreamServerInterceptor applies fn to errors returned by server .


func UnaryClientInterceptor(fn ConvertFunc) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
		return fn(invoker(ctx, method, req, reply, cc, opts...))
	}
}

func UnaryClientInterceptor ( fn ConvertFunc ) grpc . UnaryClientInterceptor { return func ( ctx context . Context , method string , req , reply interface { } , cc * grpc . ClientConn , invoker grpc . UnaryInvoker , opts ... grpc . CallOption ) ( err error ) { return fn ( invoker ( ctx , method , req , reply , cc , opts ... ) ) } }

// UnaryClientInterceptor applies fn to errors recieved by client.

UnaryClientInterceptor applies fn to errors recieved by client .


func StreamClientInterceptor(fn ConvertFunc) grpc.StreamClientInterceptor {
	return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) {
		stream, err = streamer(ctx, desc, cc, method, opts...)
		return stream, fn(err)
	}
}

func StreamClientInterceptor ( fn ConvertFunc ) grpc . StreamClientInterceptor { return func ( ctx context . Context , desc * grpc . StreamDesc , cc * grpc . ClientConn , method string , streamer grpc . Streamer , opts ... grpc . CallOption ) ( stream grpc . ClientStream , err error ) { stream , err = streamer ( ctx , desc , cc , method , opts ... ) return stream , fn ( err ) } }

// StreamClientInterceptor applies fn to errors recieved by client.

StreamClientInterceptor applies fn to errors recieved by client .


func Interceptor(settings Settings) grpc.StreamClientInterceptor {
	return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) {
		s := &restartingStream{
			log: log.Get().WithField("method", method),

			ctx:      ctx,
			desc:     desc,
			cc:       cc,
			method:   method,
			streamer: streamer,
			opts:     opts,

			retryableCodes: settings.RetryableCodes,
			backoff:        settings.Backoff,
			retries:        -1,
		}

		err = s.start()

		stream = s
		return
	}
}

func Interceptor ( settings Settings ) grpc . StreamClientInterceptor { return func ( ctx context . Context , desc * grpc . StreamDesc , cc * grpc . ClientConn , method string , streamer grpc . Streamer , opts ... grpc . CallOption ) ( stream grpc . ClientStream , err error ) { s := & restartingStream { log : log . Get ( ) . WithField ( " " , method ) , ctx : ctx , desc : desc , cc : cc , method : method , streamer : streamer , opts : opts , retryableCodes : settings . RetryableCodes , backoff : settings . Backoff , retries : - 1 , } err = s . start ( ) stream = s return } }

// Interceptor automatically restarts streams on non-expected errors
// To do so, the application should create a for-loop around RecvMsg, which
// returns the same errors that are received from the server.
//
// An io.EOF indicates the end of the stream
//
// To stop the reconnect behaviour, you have to cancel the context

Interceptor automatically restarts streams on non - expected errors To do so the application should create a for - loop around RecvMsg which returns the same errors that are received from the server . An io . EOF indicates the end of the stream To stop the reconnect behaviour you have to cancel the context


func Wrap(logger *logrus.Logger) log.Interface {
	return &logrusEntryWrapper{logrus.NewEntry(logger)}
}

func Wrap ( logger * logrus . Logger ) log . Interface { return & logrusEntryWrapper { logrus . NewEntry ( logger ) } }


func NewCounter(bucketSize, retention time.Duration) Counter {
	return &counter{
		bucketSize: bucketSize,
		retention:  retention,
		buckets:    make([]uint64, 2*retention/bucketSize),
	}
}

func NewCounter ( bucketSize , retention time . Duration ) Counter { return & counter { bucketSize : bucketSize , retention : retention , buckets : make ( [ ] uint64 , 2 * retention / bucketSize ) , } }

// NewCounter returns a new rate counter with the given bucket size and retention


func NewRedisCounter(client *redis.Client, key string, bucketSize, retention time.Duration) Counter {
	return &redisCounter{
		client:     client,
		key:        key,
		bucketSize: bucketSize,
		retention:  retention,
	}
}

func NewRedisCounter ( client * redis . Client , key string , bucketSize , retention time . Duration ) Counter { return & redisCounter { client : client , key : key , bucketSize : bucketSize , retention : retention , } }

// NewRedisCounter returns a new redis-based counter

NewRedisCounter returns a new redis - based counter


func NewLimiter(counter Counter, duration time.Duration, limit uint64) Limiter {
	return &limiter{
		Counter:  counter,
		duration: duration,
		limit:    limit,
	}
}

func NewLimiter ( counter Counter , duration time . Duration , limit uint64 ) Limiter { return & limiter { Counter : counter , duration : duration , limit : limit , } }


func (c *TokenCredentials) WithInsecure() *TokenCredentials {
	return &TokenCredentials{token: c.token, tokenFunc: c.tokenFunc, allowInsecure: true}
}

func ( c * TokenCredentials ) WithInsecure ( ) * TokenCredentials { return & TokenCredentials { token : c . token , tokenFunc : c . tokenFunc , allowInsecure : true } }

// WithInsecure returns a copy of the TokenCredentials, allowing insecure transport

WithInsecure returns a copy of the TokenCredentials allowing insecure transport


func WithTokenFunc(k string, tokenFunc func(v string) string) *TokenCredentials {
	return &TokenCredentials{
		tokenFunc:    tokenFunc,
		tokenFuncKey: k,
	}
}

func WithTokenFunc ( k string , tokenFunc func ( v string ) string ) * TokenCredentials { return & TokenCredentials { tokenFunc : tokenFunc , tokenFuncKey : k , } }

// WithTokenFunc returns TokenCredentials that execute the tokenFunc on each request
// The value of v sent to the tokenFunk is the MD value of the supplied k

WithTokenFunc returns TokenCredentials that execute the tokenFunc on each request The value of v sent to the tokenFunk is the MD value of the supplied k


func (c *TokenCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	md := ttnctx.MetadataFromOutgoingContext(ctx)
	token, _ := ttnctx.TokenFromMetadata(md)
	if token != "" {
		return map[string]string{tokenKey: token}, nil
	}
	if c.tokenFunc != nil {
		var k string
		if v, ok := md[c.tokenFuncKey]; ok && len(v) > 0 {
			k = v[0]
		}
		return map[string]string{tokenKey: c.tokenFunc(k)}, nil
	}
	if c.token != "" {
		return map[string]string{tokenKey: c.token}, nil
	}
	return map[string]string{tokenKey: ""}, nil
}

func ( c * TokenCredentials ) GetRequestMetadata ( ctx context . Context , uri ... string ) ( map [ string ] string , error ) { md := ttnctx . MetadataFromOutgoingContext ( ctx ) token , _ := ttnctx . TokenFromMetadata ( md ) if token != " " { return map [ string ] string { tokenKey : token } , nil } if c . tokenFunc != nil { var k string if v , ok := md [ c . tokenFuncKey ] ; ok && len ( v ) > 0 { k = v [ 0 ] } return map [ string ] string { tokenKey : c . tokenFunc ( k ) } , nil } if c . token != " " { return map [ string ] string { tokenKey : c . token } , nil } return map [ string ] string { tokenKey : " " } , nil }

// GetRequestMetadata implements credentials.PerRPCCredentials

GetRequestMetadata implements credentials . PerRPCCredentials


func FieldsFromIncomingContext(ctx context.Context) ttnlog.Fields {
	fields := make(fieldMap)
	if peer, ok := peer.FromContext(ctx); ok {
		fields.addFromPeer(peer)
	}
	if md, ok := metadata.FromIncomingContext(ctx); ok {
		fields.addFromMD(md)
	}
	return fields.LogFields()
}

func FieldsFromIncomingContext ( ctx context . Context ) ttnlog . Fields { fields := make ( fieldMap ) if peer , ok := peer . FromContext ( ctx ) ; ok { fields . addFromPeer ( peer ) } if md , ok := metadata . FromIncomingContext ( ctx ) ; ok { fields . addFromMD ( md ) } return fields . LogFields ( ) }

// FieldsFromIncomingContext returns peer information and MDLogFields from the given context


func (t Type) String() string {
	switch t {
	case Unknown:
		return "Unknown"
	case Internal:
		return "Internal"
	case InvalidArgument:
		return "Invalid argument"
	case OutOfRange:
		return "Out of range"
	case NotFound:
		return "Not found"
	case Conflict:
		return "Conflict"
	case AlreadyExists:
		return "Already exists"
	case Unauthorized:
		return "Unauthorized"
	case PermissionDenied:
		return "Permission denied"
	case Timeout:
		return "Timeout"
	case NotImplemented:
		return "Not implemented"
	case TemporarilyUnavailable:
		return "Temporarily unavailable"
	case PermanentlyUnavailable:
		return "Permanently unavailable"
	case Canceled:
		return "Canceled"
	case ResourceExhausted:
		return "Resource exhausted"
	default:
		return "Unknown"
	}
}

func ( t Type ) String ( ) string { switch t { case Unknown : return " " case Internal : return " " case InvalidArgument : return " " case OutOfRange : return " " case NotFound : return " " case Conflict : return " " case AlreadyExists : return " " case Unauthorized : return " " case PermissionDenied : return " " case Timeout : return " " case NotImplemented : return " " case TemporarilyUnavailable : return " " case PermanentlyUnavailable : return " " case Canceled : return " " case ResourceExhausted : return " " default : return " " } }


func (t *Type) UnmarshalText(text []byte) error {
	e, err := fromString(string(text))
	if err != nil {
		return err
	}

	*t = e

	return nil
}

func ( t * Type ) UnmarshalText ( text [ ] byte ) error { e , err := fromString ( string ( text ) ) if err != nil { return err } * t = e return nil }

// UnmarshalText implements TextUnmarsheler


func fromString(str string) (Type, error) {
	enum := strings.ToLower(str)
	switch enum {
	case "unknown":
		return Unknown, nil
	case "internal":
		return Internal, nil
	case "invalid argument":
		return InvalidArgument, nil
	case "out of range":
		return OutOfRange, nil
	case "not found":
		return NotFound, nil
	case "conflict":
		return Conflict, nil
	case "already exists":
		return AlreadyExists, nil
	case "unauthorized":
		return Unauthorized, nil
	case "permission denied":
		return PermissionDenied, nil
	case "timeout":
		return Timeout, nil
	case "not implemented":
		return NotImplemented, nil
	case "temporarily unavailable":
		return TemporarilyUnavailable, nil
	case "permanently unavailable":
		return PermanentlyUnavailable, nil
	case "canceled":
		return Canceled, nil
	case "resource exhausted":
		return ResourceExhausted, nil
	default:
		return Unknown, fmt.Errorf("Invalid error type")
	}
}

func fromString ( str string ) ( Type , error ) { enum := strings . ToLower ( str ) switch enum { case " " : return Unknown , nil case " " : return Internal , nil case " " : return InvalidArgument , nil case " " : return OutOfRange , nil case " " : return NotFound , nil case " " : return Conflict , nil case " " : return AlreadyExists , nil case " " : return Unauthorized , nil case " " : return PermissionDenied , nil case " " : return Timeout , nil case " " : return NotImplemented , nil case " " : return TemporarilyUnavailable , nil case " " : return PermanentlyUnavailable , nil case " " : return Canceled , nil case " " : return ResourceExhausted , nil default : return Unknown , fmt . Errorf ( " " ) } }

// fromString parses a string into an error type. If the type is invalid, the
// Unknown type will be returned as well as an error.

fromString parses a string into an error type . If the type is invalid the Unknown type will be returned as well as an error .


func Start(ctx log.Interface, interval time.Duration) {
	ctx.WithField("interval", interval).Debug("starting stats loop")
	go func() {
		memstats := new(runtime.MemStats)
		for range time.Tick(interval) {
			runtime.ReadMemStats(memstats)
			ctx.WithFields(log.Fields{
				"goroutines": runtime.NumGoroutine(),
				"memory":     float64(memstats.Alloc) / megaByte, // MegaBytes allocated and not yet freed
			}).Debugf("memory stats")
		}
	}()
}

// Start starts the stat process that will log relevant memory-related stats
// to ctx, at an interval determined by interval.

Start starts the stat process that will log relevant memory - related stats to ctx at an interval determined by interval .


func NewSimple() Simple {
	q := &simpleQueue{
		queue: make([]interface{}, 0),
	}
	q.available = sync.NewCond(&q.mu)
	return q
}

func NewSimple ( ) Simple { q := & simpleQueue { queue : make ( [ ] interface { } , 0 ) , } q . available = sync . NewCond ( & q . mu ) return q }


func Wrap(logger log.Interface, filters ...Filter) *Filtered {
	return &Filtered{
		Interface: logger,
		filters:   filters,
	}
}

func Wrap ( logger log . Interface , filters ... Filter ) * Filtered { return & Filtered { Interface : logger , filters : filters , } }

// Wrap wraps an existing logger, filtering the fields as it goes along
// using the provided filters

Wrap wraps an existing logger filtering the fields as it goes along using the provided filters


func (f *Filtered) WithFilters(filters ...Filter) *Filtered {
	return &Filtered{
		Interface: f.Interface,
		filters:   append(f.filters, filters...),
	}
}

func ( f * Filtered ) WithFilters ( filters ... Filter ) * Filtered { return & Filtered { Interface : f . Interface , filters : append ( f . filters , filters ... ) , } }

// WithFilter creates a new Filtered that will use the extra filters


func (f *Filtered) WithField(k string, v interface{}) log.Interface {
	val := v

	// apply the filters
	for _, filter := range f.filters {
		val = filter.Filter(k, val)
	}

	return &Filtered{
		Interface: f.Interface.WithField(k, val),
		filters:   f.filters,
	}
}

func
(
f
*
Filtered
)
WithField
(
k
string
,
v
interface
{
}
)
log
.
Interface
{
val
:=
v
// apply the filters
for
_
,
filter
:=
range
f
.
filters
{
val
=
filter
.
Filter
(
k
,
val
)
}
return
&
Filtered
{
Interface
:
f
.
Interface
.
WithField
(
k
,
val
)
,
filters
:
f
.
filters
,
}
}

// WithField filters the field and passes it on to the wrapped loggers WithField


func (f *Filtered) WithFields(fields log.Fields) log.Interface {
	res := make(map[string]interface{}, len(fields))

	for k, v := range fields {
		val := v

		// apply the filters
		for _, filter := range f.filters {
			val = filter.Filter(k, val)
		}

		res[k] = val
	}

	return &Filtered{
		Interface: f.Interface.WithFields(res),
		filters:   f.filters,
	}
}

func
(
f
*
Filtered
)
WithFields
(
fields
log
.
Fields
)
log
.
Interface
{
res
:=
make
(
map
[
string
]
interface
{
}
,
len
(
fields
)
)
for
k
,
v
:=
range
fields
{
val
:=
v
// apply the filters
for
_
,
filter
:=
range
f
.
filters
{
val
=
filter
.
Filter
(
k
,
val
)
}
res
[
k
]
=
val
}
return
&
Filtered
{
Interface
:
f
.
Interface
.
WithFields
(
res
)
,
filters
:
f
.
filters
,
}
}

// WithFields filters the fields and passes them on to the wrapped loggers WithFields


func FilterSensitive(sensitive []string, elided interface{}) Filter {
	return FilterFunc(func(key string, v interface{}) interface{} {
		lower := strings.ToLower(key)
		for _, s := range sensitive {
			if lower == s {
				return elided
			}
		}

		return v
	})
}

func FilterSensitive ( sensitive [ ] string , elided interface { } ) Filter { return FilterFunc ( func ( key string , v interface { } ) interface { } { lower := strings . ToLower ( key ) for _ , s := range sensitive { if lower == s { return elided } } return v } ) }

// FilterSensitive creates a Filter that filters most sensitive data like passwords,
// keys, access_tokens, etc. and replaces them with the elided value

FilterSensitive creates a Filter that filters most sensitive data like passwords keys access_tokens etc . and replaces them with the elided value


func SliceFilter(filter Filter) Filter {
	return FilterFunc(func(k string, v interface{}) interface{} {
		r := reflect.ValueOf(v)
		if r.Kind() == reflect.Slice {
			res := make([]interface{}, 0, r.Len())
			for i := 0; i < r.Len(); i++ {
				el := r.Index(i).Interface()
				res = append(res, filter.Filter(k, el))
			}

			return res
		}

		return filter.Filter(k, v)
	})
}

func SliceFilter ( filter Filter ) Filter { return FilterFunc ( func ( k string , v interface { } ) interface { } { r := reflect . ValueOf ( v ) if r . Kind ( ) == reflect . Slice { res := make ( [ ] interface { } , 0 , r . Len ( ) ) for i := 0 ; i < r . Len ( ) ; i ++ { el := r . Index ( i ) . Interface ( ) res = append ( res , filter . Filter ( k , el ) ) } return res } return filter . Filter ( k , v ) } ) }

// SliceFilter lifts the filter to also work on slices. It loses the
// type information of the slice elements

SliceFilter lifts the filter to also work on slices . It loses the type information of the slice elements


func MapFilter(filter Filter) Filter {
	return FilterFunc(func(k string, v interface{}) interface{} {
		r := reflect.ValueOf(v)
		if r.Kind() == reflect.Map {
			// res will be the filtered map
			res := make(map[string]interface{}, r.Len())
			for _, key := range r.MapKeys() {
				str := key.String()
				val := r.MapIndex(key).Interface()
				res[str] = filter.Filter(str, val)
			}

			return res
		}

		return v
	})
}

func
MapFilter
(
filter
Filter
)
Filter
{
return
FilterFunc
(
func
(
k
string
,
v
interface
{
}
)
interface
{
}
{
r
:=
reflect
.
ValueOf
(
v
)
if
r
.
Kind
(
)
==
reflect
.
Map
{
// res will be the filtered map
res
:=
make
(
map
[
string
]
interface
{
}
,
r
.
Len
(
)
)
for
_
,
key
:=
range
r
.
MapKeys
(
)
{
str
:=
key
.
String
(
)
val
:=
r
.
MapIndex
(
key
)
.
Interface
(
)
res
[
str
]
=
filter
.
Filter
(
str
,
val
)
}
return
res
}
return
v
}
)
}

// MapFilter lifts the filter to also work on maps. It loses the type
// information of the map fields

MapFilter lifts the filter to also work on maps . It loses the type information of the map fields


func RestrictFilter(fieldName string, filter Filter) Filter {
	return FilterFunc(func(k string, v interface{}) interface{} {
		if fieldName == k {
			return filter.Filter(k, v)
		}

		return v
	})
}

func RestrictFilter ( fieldName string , filter Filter ) Filter { return FilterFunc ( func ( k string , v interface { } ) interface { } { if fieldName == k { return filter . Filter ( k , v ) } return v } ) }

// RestrictFilter restricts the filter to only work on a certain field


func LowerCaseFilter(filter Filter) Filter {
	return FilterFunc(func(k string, v interface{}) interface{} {
		return filter.Filter(strings.ToLower(k), v)
	})
}

func LowerCaseFilter ( filter Filter ) Filter { return FilterFunc ( func ( k string , v interface { } ) interface { } { return filter . Filter ( strings . ToLower ( k ) , v ) } ) }

// LowerCaseFilter creates a filter that only get passed lowercase field names


func newBatchPoints(bpConf influxdb.BatchPointsConfig) influxdb.BatchPoints {
	bp, err := influxdb.NewBatchPoints(bpConf)
	if err != nil {
		// Can only happen if there's an error in the code
		panic(fmt.Errorf("Invalid batch point configuration: %s", err))
	}
	return bp
}

// newBatchPoints creates new influxdb.BatchPoints with specified bpConf.
// Panics on errors.

newBatchPoints creates new influxdb . BatchPoints with specified bpConf . Panics on errors .


func NewSinglePointWriter(log ttnlog.Interface, w BatchPointsWriter) *SinglePointWriter {
	return &SinglePointWriter{
		log:    log,
		writer: w,
	}
}

func NewSinglePointWriter ( log ttnlog . Interface , w BatchPointsWriter ) * SinglePointWriter { return & SinglePointWriter { log : log , writer : w , } }

// NewSinglePointWriter creates new SinglePointWriter


func (w *SinglePointWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error {
	bp := newBatchPoints(bpConf)
	bp.AddPoint(p)
	return w.writer.Write(bp)
}

func ( w * SinglePointWriter ) Write ( bpConf influxdb . BatchPointsConfig , p * influxdb . Point ) error { bp := newBatchPoints ( bpConf ) bp . AddPoint ( p ) return w . writer . Write ( bp ) }

// Write creates new influxdb.BatchPoints containing p and delegates that to the writer

Write creates new influxdb . BatchPoints containing p and delegates that to the writer


func WithScalingInterval(v time.Duration) BatchingWriterOption {
	return func(w *BatchingWriter) {
		w.scalingInterval = v
	}
}

func WithScalingInterval ( v time . Duration ) BatchingWriterOption { return func ( w * BatchingWriter ) { w . scalingInterval = v } }

// WithInstanceLimit sets a limit on amount of additional instances spawned by BatchingWriter


func NewBatchingWriter(log ttnlog.Interface, w BatchPointsWriter, opts ...BatchingWriterOption) *BatchingWriter {
	bw := &BatchingWriter{
		log:             log,
		writer:          w,
		scalingInterval: DefaultScalingInterval,
		limit:           DefaultInstanceLimit,
		pointChans:      make(map[influxdb.BatchPointsConfig]chan *batchPoint),
	}
	for _, opt := range opts {
		opt(bw)
	}
	bw.log = bw.log.WithFields(ttnlog.Fields{
		"limit":           bw.limit,
		"scalingInterval": bw.scalingInterval,
	})
	return bw
}

func NewBatchingWriter ( log ttnlog . Interface , w BatchPointsWriter , opts ... BatchingWriterOption ) * BatchingWriter { bw := & BatchingWriter { log : log , writer : w , scalingInterval : DefaultScalingInterval , limit : DefaultInstanceLimit , pointChans : make ( map [ influxdb . BatchPointsConfig ] chan * batchPoint ) , } for _ , opt := range opts { opt ( bw ) } bw . log = bw . log . WithFields ( ttnlog . Fields { " " : bw . limit , " " : bw . scalingInterval , } ) return bw }

// NewBatchingWriter creates new BatchingWriter. If WithScalingInterval is not specified, DefaultScalingInterval value is used. If WithInstanceLimit is not specified, DefaultInstanceLimit is used.

NewBatchingWriter creates new BatchingWriter . If WithScalingInterval is not specified DefaultScalingInterval value is used . If WithInstanceLimit is not specified DefaultInstanceLimit is used .


func (w *BatchingWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error {
	log := w.log.WithField("config", bpConf)

	w.pointChanMutex.RLock()
	ch, ok := w.pointChans[bpConf]
	w.pointChanMutex.RUnlock()
	if !ok {
		w.pointChanMutex.Lock()
		ch, ok = w.pointChans[bpConf]
		if !ok {
			w.mutex.Lock()
			w.active++
			w.limit++
			w.mutex.Unlock()

			ch = make(chan *batchPoint)
			w.pointChans[bpConf] = ch
			go writeInBatches(log, w.writer, bpConf, w.scalingInterval, ch, true)
		}
		w.pointChanMutex.Unlock()
	}

	point := &batchPoint{
		Point: p,
		errch: make(chan error, 1),
	}
	select {
	case ch <- point:
	case <-time.After(w.scalingInterval):
		w.mutex.Lock()
		if w.active < w.limit {
			w.active++
			go writeInBatches(w.log, w.writer, bpConf, w.scalingInterval, ch, false)
		}
		w.mutex.Unlock()
		ch <- point
	}
	return <-point.errch
}

func ( w * BatchingWriter ) Write ( bpConf influxdb . BatchPointsConfig , p * influxdb . Point ) error { log := w . log . WithField ( " " , bpConf ) w . pointChanMutex . RLock ( ) ch , ok := w . pointChans [ bpConf ] w . pointChanMutex . RUnlock ( ) if ! ok { w . pointChanMutex . Lock ( ) ch , ok = w . pointChans [ bpConf ] if ! ok { w . mutex . Lock ( ) w . active ++ w . limit ++ w . mutex . Unlock ( ) ch = make ( chan * batchPoint ) w . pointChans [ bpConf ] = ch go writeInBatches ( log , w . writer , bpConf , w . scalingInterval , ch , true ) } w . pointChanMutex . Unlock ( ) } point := & batchPoint { Point : p , errch : make ( chan error , 1 ) , } select { case ch <- point : case <- time . After ( w . scalingInterval ) : w . mutex . Lock ( ) if w . active < w . limit { w . active ++ go writeInBatches ( w . log , w . writer , bpConf , w . scalingInterval , ch , false ) } w . mutex . Unlock ( ) ch <- point } return <- point . errch }

// Write delegates p to a running instance of BatchingWriter and spawns new instances as required.

Write delegates p to a running instance of BatchingWriter and spawns new instances as required .


func (w *apexInterfaceWrapper) MustParseLevel(s string) {
	level, err := ParseLevel(s)
	if err != nil {
		w.WithError(err).WithField("level", s).Fatal("Could not parse log level")
	}
	w.Level = level
}

func ( w * apexInterfaceWrapper ) MustParseLevel ( s string ) { level , err := ParseLevel ( s ) if err != nil { w . WithError ( err ) . WithField ( " " , s ) . Fatal ( " " ) } w . Level = level }

// MustParseLevel is a convience function that parses the passed in string
// as a log level and sets the log level of the apexInterfaceWrapper to the
// parsed level. If an error occurs it will handle it with w.Fatal

MustParseLevel is a convience function that parses the passed in string as a log level and sets the log level of the apexInterfaceWrapper to the parsed level . If an error occurs it will handle it with w . Fatal


func New(bufferSize int, setup func() (grpc.ClientStream, error)) *Stream {
	return &Stream{
		setupFunc:  setup,
		sendBuffer: make(chan interface{}, bufferSize),
		log:        ttnlog.Get(),
	}
}

func New ( bufferSize int , setup func ( ) ( grpc . ClientStream , error ) ) * Stream { return & Stream { setupFunc : setup , sendBuffer : make ( chan interface { } , bufferSize ) , log : ttnlog . Get ( ) , } }

// New returns a new Stream with the given buffer size and setup function.

New returns a new Stream with the given buffer size and setup function .


func (s *Stream) SetLogger(log ttnlog.Interface) {
	s.mu.Lock()
	s.log = log
	s.mu.Unlock()
}

func ( s * Stream ) SetLogger ( log ttnlog . Interface ) { s . mu . Lock ( ) s . log = log s . mu . Unlock ( ) }

// SetLogger sets the logger for this streambuffer


func (s *Stream) CloseRecv() {
	s.mu.Lock()
	if s.recvBuffer != nil {
		close(s.recvBuffer)
		s.recvBuffer = nil
	}
	s.mu.Unlock()
}

func ( s * Stream ) CloseRecv ( ) { s . mu . Lock ( ) if s . recvBuffer != nil { close ( s . recvBuffer ) s . recvBuffer = nil } s . mu . Unlock ( ) }


func (s *Stream) Stats() (sent, dropped uint64) {
	return atomic.LoadUint64(&s.sent), atomic.LoadUint64(&s.dropped)
}

func ( s * Stream ) Stats ( ) ( sent , dropped uint64 ) { return atomic . LoadUint64 ( & s . sent ) , atomic . LoadUint64 ( & s . dropped ) }


func (s *Stream) Run() (err error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	defer func() {
		if err != nil {
			if grpc.Code(err) == codes.Canceled {
				s.log.Debug("streambuffer: context canceled")
				err = context.Canceled
				return
			}
			if grpc.Code(err) == codes.DeadlineExceeded {
				s.log.Debug("streambuffer: context deadline exceeded")
				err = context.DeadlineExceeded
				return
			}
		}
	}()

	stream, err := s.setupFunc()
	if err != nil {
		s.log.WithError(err).Debug("streambuffer: setup returned error")
		return err
	}

	recvErr := make(chan error)
	defer func() {
		go func() { // empty the recvErr channel on return
			<-recvErr
		}()
	}()

	go func() {
		for {
			var r interface{}
			if s.recvFunc != nil {
				r = s.recvFunc()
			} else {
				r = new(empty.Empty) // Generic proto message if not interested in received values
			}
			err := stream.RecvMsg(r)
			if err != nil {
				s.log.WithError(err).Debug("streambuffer: error from stream.RecvMsg")
				recvErr <- err
				close(recvErr)
				return
			}
			if s.recvFunc != nil {
				s.recvMsg(r)
			}
		}
	}()

	defer stream.CloseSend()

	for {
		select {
		case err := <-recvErr:
			return err
		case <-stream.Context().Done():
			s.log.WithError(stream.Context().Err()).Debug("streambuffer: context done")
			return stream.Context().Err()
		case msg := <-s.sendBuffer:
			if err = stream.SendMsg(msg); err != nil {
				s.log.WithError(err).Debug("streambuffer: error from stream.SendMsg")
				return err
			}
			atomic.AddUint64(&s.sent, 1)
		}
	}
}

// Run the stream.
//
// This calls the underlying grpc.ClientStreams methods to send and receive messages over the stream.
// Run returns the error returned by any of those functions, or context.Canceled if the context is canceled.

Run the stream . This calls the underlying grpc . ClientStreams methods to send and receive messages over the stream . Run returns the error returned by any of those functions or context . Canceled if the context is canceled .


func ServerOptions(log ttnlog.Interface) []grpc.ServerOption {
	return []grpc.ServerOption{
		grpc.UnaryInterceptor(UnaryServerInterceptor(log)),
		grpc.StreamInterceptor(StreamServerInterceptor(log)),
	}
}

func ServerOptions ( log ttnlog . Interface ) [ ] grpc . ServerOption { return [ ] grpc . ServerOption { grpc . UnaryInterceptor ( UnaryServerInterceptor ( log ) ) , grpc . StreamInterceptor ( StreamServerInterceptor ( log ) ) , } }


func ClientOptions(log ttnlog.Interface) []grpc.DialOption {
	return []grpc.DialOption{
		grpc.WithUnaryInterceptor(UnaryClientInterceptor(log)),
		grpc.WithStreamInterceptor(StreamClientInterceptor(log)),
	}
}

func ClientOptions ( log ttnlog . Interface ) [ ] grpc . DialOption { return [ ] grpc . DialOption { grpc . WithUnaryInterceptor ( UnaryClientInterceptor ( log ) ) , grpc . WithStreamInterceptor ( StreamClientInterceptor ( log ) ) , } }


func UnaryServerInterceptor(log ttnlog.Interface) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		log := getLog(log).WithField("method", info.FullMethod)
		log = log.WithFields(FieldsFromIncomingContext(ctx))
		start := time.Now()
		resp, err = handler(ctx, req)
		log = log.WithField("duration", time.Since(start))
		if err != nil {
			log.WithError(err).Debug("rpc-server: call failed")
			return
		}
		log.Debug("rpc-server: call done")
		return
	}
}

func UnaryServerInterceptor ( log ttnlog . Interface ) grpc . UnaryServerInterceptor { return func ( ctx context . Context , req interface { } , info * grpc . UnaryServerInfo , handler grpc . UnaryHandler ) ( resp interface { } , err error ) { log := getLog ( log ) . WithField ( " " , info . FullMethod ) log = log . WithFields ( FieldsFromIncomingContext ( ctx ) ) start := time . Now ( ) resp , err = handler ( ctx , req ) log = log . WithField ( " " , time . Since ( start ) ) if err != nil { log . WithError ( err ) . Debug ( " " ) return } log . Debug ( " " ) return } }

// UnaryServerInterceptor logs unary RPCs on the server side


func StreamServerInterceptor(log ttnlog.Interface) grpc.StreamServerInterceptor {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
		log := getLog(log).WithField("method", info.FullMethod)
		log = log.WithFields(FieldsFromIncomingContext(ss.Context()))
		start := time.Now()
		log.Debug("rpc-server: stream starting")
		err = handler(srv, ss)
		log = log.WithField("duration", time.Since(start))
		if err != nil {
			if err == context.Canceled || grpc.Code(err) == codes.Canceled {
				log.Debug("rpc-server: stream canceled")
				return
			}
			log.WithError(err).Debug("rpc-server: stream failed")
			return
		}
		log.Debug("rpc-server: stream done")
		return
	}
}

func StreamServerInterceptor ( log ttnlog . Interface ) grpc . StreamServerInterceptor { return func ( srv interface { } , ss grpc . ServerStream , info * grpc . StreamServerInfo , handler grpc . StreamHandler ) ( err error ) { log := getLog ( log ) . WithField ( " " , info . FullMethod ) log = log . WithFields ( FieldsFromIncomingContext ( ss . Context ( ) ) ) start := time . Now ( ) log . Debug ( " " ) err = handler ( srv , ss ) log = log . WithField ( " " , time . Since ( start ) ) if err != nil { if err == context . Canceled || grpc . Code ( err ) == codes . Canceled { log . Debug ( " " ) return } log . WithError ( err ) . Debug ( " " ) return } log . Debug ( " " ) return } }

// StreamServerInterceptor logs streaming RPCs on the server side


func UnaryClientInterceptor(log ttnlog.Interface) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
		log := getLog(log).WithField("method", method)
		log = log.WithFields(FieldsFromOutgoingContext(ctx))
		start := time.Now()
		err = invoker(ctx, method, req, reply, cc, opts...)
		log = log.WithField("duration", time.Since(start))
		if err != nil {
			log.WithError(err).Debug("rpc-client: call failed")
			return
		}
		log.Debug("rpc-client: call done")
		return
	}
}

func UnaryClientInterceptor ( log ttnlog . Interface ) grpc . UnaryClientInterceptor { return func ( ctx context . Context , method string , req , reply interface { } , cc * grpc . ClientConn , invoker grpc . UnaryInvoker , opts ... grpc . CallOption ) ( err error ) { log := getLog ( log ) . WithField ( " " , method ) log = log . WithFields ( FieldsFromOutgoingContext ( ctx ) ) start := time . Now ( ) err = invoker ( ctx , method , req , reply , cc , opts ... ) log = log . WithField ( " " , time . Since ( start ) ) if err != nil { log . WithError ( err ) . Debug ( " " ) return } log . Debug ( " " ) return } }

// UnaryClientInterceptor logs unary RPCs on the client side


func StreamClientInterceptor(log ttnlog.Interface) grpc.StreamClientInterceptor {
	return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) {
		log := getLog(log).WithField("method", method)
		log = log.WithFields(FieldsFromOutgoingContext(ctx))
		log.Debug("rpc-client: stream starting")
		stream, err = streamer(ctx, desc, cc, method, opts...)
		if err != nil {
			if err == context.Canceled || grpc.Code(err) == codes.Canceled {
				log.Debug("rpc-client: stream canceled")
				return
			}
			log.WithError(err).Debug("rpc-client: stream failed")
			return
		}
		go func() {
			<-stream.Context().Done()
			if err := stream.Context().Err(); err != nil {
				log = log.WithError(err)
			}
			log.Debug("rpc-client: stream done")
		}()
		return
	}
}

func StreamClientInterceptor ( log ttnlog . Interface ) grpc . StreamClientInterceptor { return func ( ctx context . Context , desc * grpc . StreamDesc , cc * grpc . ClientConn , method string , streamer grpc . Streamer , opts ... grpc . CallOption ) ( stream grpc . ClientStream , err error ) { log := getLog ( log ) . WithField ( " " , method ) log = log . WithFields ( FieldsFromOutgoingContext ( ctx ) ) log . Debug ( " " ) stream , err = streamer ( ctx , desc , cc , method , opts ... ) if err != nil { if err == context . Canceled || grpc . Code ( err ) == codes . Canceled { log . Debug ( " " ) return } log . WithError ( err ) . Debug ( " " ) return } go func ( ) { <- stream . Context ( ) . Done ( ) if err := stream . Context ( ) . Err ( ) ; err != nil { log = log . WithError ( err ) } log . Debug ( " " ) } ( ) return } }

// StreamClientInterceptor logs streaming RPCs on the client side


func (c *Config) defaults() {
	if c.BufferSize == 0 {
		c.BufferSize = 100
	}

	if c.Prefix == "" {
		c.Prefix = "logs"
	}
}

func ( c * Config ) defaults ( ) { if c . BufferSize == 0 { c . BufferSize = 100 } if c . Prefix == " " { c . Prefix = " " } }

// defaults applies defaults to the config.

defaults applies defaults to the config .


func (h *Handler) Flush() {
	h.mu.Lock()
	defer h.mu.Unlock()
	if h.batch != nil {
		go h.flush(h.batch)
		h.batch = nil
	}
}

func ( h * Handler ) Flush ( ) { h . mu . Lock ( ) defer h . mu . Unlock ( ) if h . batch != nil { go h . flush ( h . batch ) h . batch = nil } }


func New(w io.Writer) *Handler {
	var useColor bool
	if os.Getenv("COLORTERM") != "" {
		useColor = true
	}
	if term := os.Getenv("TERM"); term != "" {
		for _, substring := range colorTermSubstrings {
			if strings.Contains(term, substring) {
				useColor = true
				break
			}
		}
	}
	return &Handler{
		Writer:   w,
		UseColor: useColor,
	}
}

func New ( w io . Writer ) * Handler { var useColor bool if os . Getenv ( " " ) != " " { useColor = true } if term := os . Getenv ( " " ) ; term != " " { for _ , substring := range colorTermSubstrings { if strings . Contains ( term , substring ) { useColor = true break } } } return & Handler { Writer : w , UseColor : useColor , } }


func (h *Handler) HandleLog(e *log.Entry) error {
	color := Colors[e.Level]
	level := Strings[e.Level]

	var fields []field

	for k, v := range e.Fields {
		fields = append(fields, field{k, v})
	}

	sort.Sort(byName(fields))

	h.mu.Lock()
	defer h.mu.Unlock()

	if h.UseColor {
		fmt.Fprintf(h.Writer, "\033[%dm%6s\033[0m %-40s", color, level, e.Message)
	} else {
		fmt.Fprintf(h.Writer, "%6s %-40s", level, e.Message)
	}

	for _, f := range fields {
		var value interface{}
		switch t := f.Value.(type) {
		case []byte: // addresses and EUIs are []byte
			value = fmt.Sprintf("%X", t)
		case [21]byte: // bundle IDs [21]byte
			value = fmt.Sprintf("%X-%X-%X-%X", t[0], t[1:9], t[9:17], t[17:])
		default:
			value = f.Value
		}

		if h.UseColor {
			fmt.Fprintf(h.Writer, " \033[%dm%s\033[0m=%v", color, f.Name, value)
		} else {
			fmt.Fprintf(h.Writer, " %s=%v", f.Name, value)
		}

	}

	fmt.Fprintln(h.Writer)

	return nil
}

func
(
h
*
Handler
)
HandleLog
(
e
*
log
.
Entry
)
error
{
color
:=
Colors
[
e
.
Level
]
level
:=
Strings
[
e
.
Level
]
var
fields
[
]
field
for
k
,
v
:=
range
e
.
Fields
{
fields
=
append
(
fields
,
field
{
k
,
v
}
)
}
sort
.
Sort
(
byName
(
fields
)
)
h
.
mu
.
Lock
(
)
defer
h
.
mu
.
Unlock
(
)
if
h
.
UseColor
{
fmt
.
Fprintf
(
h
.
Writer
,
"
\033
\033
"
,
color
,
level
,
e
.
Message
)
}
else
{
fmt
.
Fprintf
(
h
.
Writer
,
"
"
,
level
,
e
.
Message
)
}
for
_
,
f
:=
range
fields
{
var
value
interface
{
}
switch
t
:=
f
.
Value
.
(
type
)
{
case
[
]
byte
:
// addresses and EUIs are []byte
value
=
fmt
.
Sprintf
(
"
"
,
t
)
case
[
21
]
byte
:
// bundle IDs [21]byte
value
=
fmt
.
Sprintf
(
"
"
,
t
[
0
]
,
t
[
1
:
9
]
,
t
[
9
:
17
]
,
t
[
17
:
]
)
default
:
value
=
f
.
Value
}
if
h
.
UseColor
{
fmt
.
Fprintf
(
h
.
Writer
,
"
\033
\033
"
,
color
,
f
.
Name
,
value
)
}
else
{
fmt
.
Fprintf
(
h
.
Writer
,
"
"
,
f
.
Name
,
value
)
}
}
fmt
.
Fprintln
(
h
.
Writer
)
return
}


func New(seed int64) random.Interface {
	return &TTNRandom{
		Interface: &random.TTNRandom{
			Source: rand.New(rand.NewSource(seed)),
		},
	}
}

func New ( seed int64 ) random . Interface { return & TTNRandom { Interface : & random . TTNRandom { Source : rand . New ( rand . NewSource ( seed ) ) , } , } }

// New returns a new Random, in most cases you can also just use the global funcs

New returns a new Random in most cases you can also just use the global funcs


func (self *UriTemplate) Names() []string {
	names := make([]string, 0, len(self.parts))

	for _, p := range self.parts {
		if len(p.raw) > 0 || len(p.terms) == 0 {
			continue
		}

		for _, term := range p.terms {
			names = append(names, term.name)
		}
	}

	return names
}

func ( self * UriTemplate ) Names ( ) [ ] string { names := make ( [ ] string , 0 , len ( self . parts ) ) for _ , p := range self . parts { if len ( p . raw ) > 0 || len ( p . terms ) == 0 { continue } for _ , term := range p . terms { names = append ( names , term . name ) } } return names }

// Names returns the names of all variables within the template.

Names returns the names of all variables within the template .