1 val) {\n val = val2;\n }\n } else {\n val += val2;\n }\n count += 1;\n }\n }\n\n if (!isMaxPooling) {\n val /= float(count);\n }\n\n outColor = vec4(val);\n}\n'),this.poolingFragmentsProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\nprecision highp isampler2D;\n\nin vec2 outTex;\nuniform sampler2D x;\nuniform isampler2D poolIndexMap;\nuniform int channels;\nuniform int poolSize;\nuniform bool isMaxPooling;\nout vec4 outColor;\n\nvoid main() {\n ivec2 inputSize = textureSize(x, 0);\n ivec2 outputSize = textureSize(poolIndexMap, 0);\n int out_x = int(float(channels) * outTex.x);\n int out_y = int(float(outputSize[1]) * outTex.y);\n\n float val = 0.;\n int count = 0;\n for (int i = 0; i < poolSize; ++i) {\n int poolIndex = texelFetch(poolIndexMap, ivec2(i, out_y), 0).r;\n int fragmentIndex = int(floor(float(poolIndex) / float(inputSize[1])));\n if (poolIndex != -1) {\n poolIndex = int(mod(float(poolIndex), float(inputSize[1])));\n float val2 = texelFetch(x, ivec2(fragmentIndex * channels + out_x, poolIndex), 0).r;\n if (isMaxPooling) {\n if (count == 0 || val2 > val) {\n val = val2;\n }\n } else {\n val += val2;\n }\n count += 1;\n }\n }\n\n if (!isMaxPooling) {\n val /= float(count);\n }\n\n outColor = vec4(val);\n}\n'))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_calcOutputShape(e){if(!(this.outputShape&&this.inputPadding)){const[t,a,r]=e,[o,n]=this.poolSize,i='same'===this.padding?kn((t+this.strides[0]-1)/this.strides[0]):kn((t-o+this.strides[0])/this.strides[0]),s='same'===this.padding?kn((a+this.strides[1]-1)/this.strides[1]):kn((a-n+this.strides[1])/this.strides[1]),u='same'===this.padding?An(0,kn((i-1)*this.strides[0]+o-t)):0,l='same'===this.padding?An(0,kn((s-1)*this.strides[1]+n-a)):0,p=kn(u/2),d=kn(l/2);this.outputShape=[i,s,r],this.inputPadding=[p,u-p,d,l-d]}}_padInput(e){if('same'===this.padding){const[t,a,r]=e.tensor.shape,[n,i,u,l]=this.inputPadding,p=new o.default([],[t+n+i,a+u+l,r]);return'max'===this.poolingFunc&&s.default.assigns(p.tensor,Number.NEGATIVE_INFINITY),s.default.assign(p.tensor.hi(t+n,a+u,r).lo(n,u,0),e.tensor),p}return e}_callCPU(e){'channels_first'===this.dataFormat&&(e.tensor=e.tensor.transpose(1,2,0)),this._calcOutputShape(e.tensor.shape),e=this._padInput(e);const[t,a,r]=e.tensor.shape,[n,u]=this.poolSize;this.output=new o.default([],this.outputShape);const l=new o.default([],[n,u,r]),[p,d,c,h]=this.inputPadding;for(let o=0,i=0,g;o<=t-n;o+=this.strides[0],i++){g=0,ot-d&&(g=o+n-(t-d));for(let t=0,p=0,d;t<=a-u;t+=this.strides[1],p++){d=0,ta-h&&(d=t+u-(a-h));const m=(n-g)*(u-d);s.default.assign(l.tensor,e.tensor.hi(o+n,t+u,r).lo(o,t,0));for(let e=0;e1 val) {\n val = val2;\n }\n } else {\n val += val2;\n }\n count += 1;\n }\n }\n\n if (!isMaxPooling) {\n val /= float(count);\n }\n\n outColor = vec4(val);\n}\n'),this.poolingFragmentsProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\nprecision highp isampler2D;\n\nin vec2 outTex;\nuniform sampler2D x;\nuniform isampler2D poolIndexMap;\nuniform int channels;\nuniform int poolSize;\nuniform bool isMaxPooling;\nout vec4 outColor;\n\nvoid main() {\n ivec2 inputSize = textureSize(x, 0);\n ivec2 outputSize = textureSize(poolIndexMap, 0);\n int out_x = int(float(channels) * outTex.x);\n int out_y = int(float(outputSize[1]) * outTex.y);\n\n float val = 0.;\n int count = 0;\n for (int i = 0; i < poolSize; ++i) {\n int poolIndex = texelFetch(poolIndexMap, ivec2(i, out_y), 0).r;\n int fragmentIndex = int(floor(float(poolIndex) / float(inputSize[1])));\n if (poolIndex != -1) {\n poolIndex = int(mod(float(poolIndex), float(inputSize[1])));\n float val2 = texelFetch(x, ivec2(fragmentIndex * channels + out_x, poolIndex), 0).r;\n if (isMaxPooling) {\n if (count == 0 || val2 > val) {\n val = val2;\n }\n } else {\n val += val2;\n }\n count += 1;\n }\n }\n\n if (!isMaxPooling) {\n val /= float(count);\n }\n\n outColor = vec4(val);\n}\n'))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_calcOutputShape(e){if(!(this.outputShape&&this.inputPadding)){const[t,a,r,o]=e,[n,i,s]=this.poolSize,u='same'===this.padding?kn((t+this.strides[0]-1)/this.strides[0]):kn((t-n+this.strides[0])/this.strides[0]),l='same'===this.padding?kn((a+this.strides[1]-1)/this.strides[1]):kn((a-i+this.strides[1])/this.strides[1]),p='same'===this.padding?kn((r+this.strides[2]-1)/this.strides[2]):kn((r-s+this.strides[2])/this.strides[2]),d='same'===this.padding?An(0,kn((u-1)*this.strides[0]+n-t)):0,c='same'===this.padding?An(0,kn((l-1)*this.strides[1]+i-a)):0,h='same'===this.padding?An(0,kn((p-1)*this.strides[2]+s-r)):0,g=kn(d/2),m=kn(c/2),f=kn(h/2);this.outputShape=[u,l,p,o],this.inputPadding=[g,d-g,m,c-m,f,h-f]}}_padInput(e){if('same'===this.padding){const[t,a,r,n]=e.tensor.shape,[i,u,l,p,d,c]=this.inputPadding,h=new o.default([],[t+i+u,a+l+p,r+d+c,n]);return'max'===this.poolingFunc&&s.default.assigns(h.tensor,Number.NEGATIVE_INFINITY),s.default.assign(h.tensor.hi(t+i,a+l,r+d,n).lo(i,l,d,0),e.tensor),h}return e}_callCPU(e){'channels_first'===this.dataFormat&&(e.tensor=e.tensor.transpose(1,2,3,0)),this._calcOutputShape(e.tensor.shape),e=this._padInput(e);const[t,a,r,n]=e.tensor.shape,[u,l,p]=this.poolSize;this.output=new o.default([],this.outputShape);let d=new o.default([],[u,l,p,n]);const[c,h,g,m,f,_]=this.inputPadding;for(let o=0,i=0,x;o<=t-u;o+=this.strides[0],i++){x=0,ot-h&&(x=o+u-(t-h));for(let t=0,h=0,c;t<=a-l;t+=this.strides[1],h++){c=0,ta-m&&(c=t+l-(a-m));for(let a=0,g=0,m;a<=r-p;a+=this.strides[2],g++){m=0,ar-_&&(m=a+p-(r-_));const y=(u-x)*(l-c)*(p-m);s.default.assign(d.tensor,e.tensor.hi(o+u,t+l,a+p,n).lo(o,t,a,0));for(let e=0;e maxval) {\n maxval = val;\n }\n }\n outColor = vec4(maxval);\n } else {\n // GlobalAveragePooling\n float sum = 0.0;\n for (int j = 0; j < size[1]; ++j) {\n float val = texelFetch(x, ivec2(out_x, j), 0).r;\n sum += val;\n }\n outColor = vec4(sum / float(channelDataSize));\n }\n}\n'))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){const[t,a]=e.tensor.shape;this.output=new o.default([],[a]);for(let r=0;r maxval) {\n maxval = val;\n }\n }\n outColor = vec4(maxval);\n } else {\n // GlobalAveragePooling\n float sum = 0.0;\n for (int j = 0; j < size[1]; ++j) {\n float val = texelFetch(x, ivec2(out_x, j), 0).r;\n sum += val;\n }\n outColor = vec4(sum / float(channelDataSize));\n }\n}\n'))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){'channels_first'===this.dataFormat&&(e.tensor=e.tensor.transpose(1,2,0));const[t,a,r]=e.tensor.shape;this.output=new o.default([],[r]);for(let o=0;o maxval) {\n maxval = val;\n }\n }\n outColor = vec4(maxval);\n } else {\n // GlobalAveragePooling\n float sum = 0.0;\n for (int j = 0; j < size[1]; ++j) {\n float val = texelFetch(x, ivec2(out_x, j), 0).r;\n sum += val;\n }\n outColor = vec4(sum / float(channelDataSize));\n }\n}\n'))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){'channels_first'===this.dataFormat&&(e.tensor=e.tensor.transpose(1,2,3,0));const[t,a,r,s]=e.tensor.shape;this.output=new o.default([],[s]);for(let o=0;o{s.default.assign(i.tensor,a.tensor),(0,rf.gemv)(1,this.weights.kernel.tensor.transpose(1,0),u.tensor,1,r.tensor),(0,rf.gemv)(1,this.weights.recurrent_kernel.tensor.transpose(1,0),i.tensor,1,o.tensor),this._combine(a.tensor,r.tensor,o.tensor,this.weights.bias.tensor),this.activationFunc(a)};for(let t=0,n=e.tensor.shape[0];ts.default.assigns(e.tensor,0)),l(),this.returnSequences&&s.default.assign(this.hiddenStateSequence.tensor.pick(t,null),a.tensor)}this.output=this.returnSequences?this.hiddenStateSequence:a,this.stateful&&(this.currentHiddenState=a)}_stepGPU(){Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.previousHiddenState,inputs:[{input:this.currentHiddenState,name:'source'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXH,inputs:[{input:this.currentX,name:'A'},{input:this.weights.kernel,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHH,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.recurrent_kernel,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentHiddenStatePreactiv,inputs:[{input:this.tempXH,name:'t1'},{input:this.tempHH,name:'t2'},{input:this.weights.bias,name:'bias'}]}),'linear'===this.activation?this.currentHiddenState=this.currentHiddenStatePreactiv:Kh.webgl2.runProgram({program:this.activationProgram,output:this.currentHiddenState,inputs:[{input:this.currentHiddenStatePreactiv,name:'x'}]})}_callGPU(e){e.glTexture||e.createGLTexture({type:'2d',format:'float'});const t=this.units;this.currentHiddenState&&this.stateful||(this.currentHiddenState=new n.default([],[t]),this.currentHiddenState.createGLTexture({type:'2d',format:'float'})),this.currentHiddenStatePreactiv||(this.currentHiddenStatePreactiv=new n.default([],[t]),this.currentHiddenStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXH||(this.tempXH=new n.default([],[t]),this.tempXH.createGLTexture({type:'2d',format:'float'})),this.tempHH||(this.tempHH=new n.default([],[t]),this.tempHH.createGLTexture({type:'2d',format:'float'})),this.previousHiddenState||(this.previousHiddenState=new n.default([],[t]),this.previousHiddenState.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequence||(this.hiddenStateSequence=new n.default([],[e.glTextureShape[0],t]),this.hiddenStateSequence.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequenceCopy||(this.hiddenStateSequenceCopy=new n.default([],[e.glTextureShape[0],t]),this.hiddenStateSequenceCopy.createGLTexture({type:'2d',format:'float'})),this.currentX||(this.currentX=new n.default([],[e.glTextureShape[1]]),this.currentX.createGLTexture({type:'2d',format:'float'}));for(let t=0,a=e.glTextureShape[0];t{this.weights[e].createGLTexture({type:'2d',format:'float'})})}}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){const t=this.weights.b_i.tensor.shape[0],a=this.weights.b_c.tensor.shape[0],r=this.weights.b_f.tensor.shape[0],o=this.weights.b_o.tensor.shape[0],i=new n.default([],[t]),u=new n.default([],[t]),l=new n.default([],[t]),p=new n.default([],[r]),d=new n.default([],[r]),c=new n.default([],[r]),h=new n.default([],[o]),g=new n.default([],[o]),m=new n.default([],[o]),f=new n.default([],[a]),_=new n.default([],[a]),x=new n.default([],[a]),y=this.stateful&&this.previousCandidate?this.previousCandidate:new n.default([],[a]),v=this.stateful&&this.currentHiddenState?this.currentHiddenState:new n.default([],[a]),b=new n.default([],[a]);this.hiddenStateSequence=new n.default([],[e.tensor.shape[0],a]);const S=new n.default([],[e.tensor.shape[1]]),T=()=>{s.default.assign(b.tensor,v.tensor),(0,rf.gemv)(1,this.weights.W_i.tensor.transpose(1,0),S.tensor,1,u.tensor),(0,rf.gemv)(1,this.weights.U_i.tensor.transpose(1,0),b.tensor,1,l.tensor),this._combine(i.tensor,u.tensor,l.tensor,this.weights.b_i.tensor),this.recurrentActivationFunc(i),(0,rf.gemv)(1,this.weights.W_f.tensor.transpose(1,0),S.tensor,1,d.tensor),(0,rf.gemv)(1,this.weights.U_f.tensor.transpose(1,0),b.tensor,1,c.tensor),this._combine(p.tensor,d.tensor,c.tensor,this.weights.b_f.tensor),this.recurrentActivationFunc(p),(0,rf.gemv)(1,this.weights.W_o.tensor.transpose(1,0),S.tensor,1,g.tensor),(0,rf.gemv)(1,this.weights.U_o.tensor.transpose(1,0),b.tensor,1,m.tensor),this._combine(h.tensor,g.tensor,m.tensor,this.weights.b_o.tensor),this.recurrentActivationFunc(h),(0,rf.gemv)(1,this.weights.W_c.tensor.transpose(1,0),S.tensor,1,_.tensor),(0,rf.gemv)(1,this.weights.U_c.tensor.transpose(1,0),b.tensor,1,x.tensor),this._combine(f.tensor,_.tensor,x.tensor,this.weights.b_c.tensor),this.activationFunc(f),this._update(f.tensor,y.tensor,i.tensor,p.tensor),s.default.assign(y.tensor,f.tensor),this.activationFunc(f),s.default.mul(v.tensor,h.tensor,f.tensor)};for(let t=0,a=e.tensor.shape[0];ts.default.assigns(e.tensor,0)),T(),s.default.assign(this.hiddenStateSequence.tensor.pick(t,null),v.tensor)}this.output=this.returnSequences?this.hiddenStateSequence:v,this.stateful&&(this.previousCandidate=y,this.currentHiddenState=v)}_stepGPU(){Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.previousHiddenState,inputs:[{input:this.currentHiddenState,name:'source'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXI,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_i,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHI,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_i,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentInputGateStatePreactiv,inputs:[{input:this.tempXI,name:'t1'},{input:this.tempHI,name:'t2'},{input:this.weights.b_i,name:'bias'}]}),'linear'===this.recurrentActivation?this.currentInputGateState=this.currentInputGateStatePreactiv:Kh.webgl2.runProgram({program:this.recurrentActivationProgram,output:this.currentInputGateState,inputs:[{input:this.currentInputGateStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXF,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_f,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHF,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_f,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentForgetGateStatePreactiv,inputs:[{input:this.tempXF,name:'t1'},{input:this.tempHF,name:'t2'},{input:this.weights.b_f,name:'bias'}]}),'linear'===this.recurrentActivation?this.currentForgetGateState=this.currentForgetGateStatePreactiv:Kh.webgl2.runProgram({program:this.recurrentActivationProgram,output:this.currentForgetGateState,inputs:[{input:this.currentForgetGateStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXO,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_o,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHO,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_o,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentOutputGateStatePreactiv,inputs:[{input:this.tempXO,name:'t1'},{input:this.tempHO,name:'t2'},{input:this.weights.b_o,name:'bias'}]}),'linear'===this.recurrentActivation?this.currentOutputGateState=this.currentOutputGateStatePreactiv:Kh.webgl2.runProgram({program:this.recurrentActivationProgram,output:this.currentOutputGateState,inputs:[{input:this.currentOutputGateStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXC,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_c,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHC,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_c,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentCandidatePreactiv,inputs:[{input:this.tempXC,name:'t1'},{input:this.tempHC,name:'t2'},{input:this.weights.b_c,name:'bias'}]}),'linear'===this.activation?this.currentCandidate=this.currentCandidatePreactiv:Kh.webgl2.runProgram({program:this.activationProgram,output:this.currentCandidate,inputs:[{input:this.currentCandidatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.currentCandidateCopy,inputs:[{input:this.currentCandidate,name:'source'}]}),Kh.webgl2.runProgram({program:this.updateProgram,output:this.currentCandidate,inputs:[{input:this.currentCandidateCopy,name:'c'},{input:this.previousCandidate,name:'ctm1'},{input:this.currentInputGateState,name:'i'},{input:this.currentForgetGateState,name:'f'}]}),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.previousCandidate,inputs:[{input:this.currentCandidate,name:'source'}]}),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.currentCandidatePreactiv,inputs:[{input:this.currentCandidate,name:'source'}]}),'linear'===this.activation?this.currentCandidate=this.currentCandidatePreactiv:Kh.webgl2.runProgram({program:this.activationProgram,output:this.currentCandidate,inputs:[{input:this.currentCandidatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.gateProductProgram,output:this.currentHiddenState,inputs:[{input:this.currentOutputGateState,name:'t1'},{input:this.currentCandidate,name:'t2'}]})}_callGPU(e){e.glTexture||e.createGLTexture({type:'2d',format:'float'});const t=this.weights.b_i.glTextureShape[1],a=this.weights.b_c.glTextureShape[1],r=this.weights.b_f.glTextureShape[1],o=this.weights.b_o.glTextureShape[1];this.currentInputGateState||(this.currentInputGateState=new n.default([],[t]),this.currentInputGateState.createGLTexture({type:'2d',format:'float'})),this.currentInputGateStatePreactiv||(this.currentInputGateStatePreactiv=new n.default([],[t]),this.currentInputGateStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXI||(this.tempXI=new n.default([],[t]),this.tempXI.createGLTexture({type:'2d',format:'float'})),this.tempHI||(this.tempHI=new n.default([],[t]),this.tempHI.createGLTexture({type:'2d',format:'float'})),this.currentForgetGateState||(this.currentForgetGateState=new n.default([],[r]),this.currentForgetGateState.createGLTexture({type:'2d',format:'float'})),this.currentForgetGateStatePreactiv||(this.currentForgetGateStatePreactiv=new n.default([],[r]),this.currentForgetGateStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXF||(this.tempXF=new n.default([],[r]),this.tempXF.createGLTexture({type:'2d',format:'float'})),this.tempHF||(this.tempHF=new n.default([],[r]),this.tempHF.createGLTexture({type:'2d',format:'float'})),this.currentOutputGateState||(this.currentOutputGateState=new n.default([],[o]),this.currentOutputGateState.createGLTexture({type:'2d',format:'float'})),this.currentOutputGateStatePreactiv||(this.currentOutputGateStatePreactiv=new n.default([],[o]),this.currentOutputGateStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXO||(this.tempXO=new n.default([],[o]),this.tempXO.createGLTexture({type:'2d',format:'float'})),this.tempHO||(this.tempHO=new n.default([],[o]),this.tempHO.createGLTexture({type:'2d',format:'float'})),this.currentCandidate||(this.currentCandidate=new n.default([],[a]),this.currentCandidate.createGLTexture({type:'2d',format:'float'})),this.currentCandidateCopy||(this.currentCandidateCopy=new n.default([],[a]),this.currentCandidateCopy.createGLTexture({type:'2d',format:'float'})),this.currentCandidatePreactiv||(this.currentCandidatePreactiv=new n.default([],[a]),this.currentCandidatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXC||(this.tempXC=new n.default([],[a]),this.tempXC.createGLTexture({type:'2d',format:'float'})),this.tempHC||(this.tempHC=new n.default([],[a]),this.tempHC.createGLTexture({type:'2d',format:'float'})),this.previousCandidate&&this.stateful||(this.previousCandidate=new n.default([],[a]),this.previousCandidate.createGLTexture({type:'2d',format:'float'})),this.currentHiddenState&&this.stateful||(this.currentHiddenState=new n.default([],[a]),this.currentHiddenState.createGLTexture({type:'2d',format:'float'})),this.previousHiddenState||(this.previousHiddenState=new n.default([],[a]),this.previousHiddenState.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequence||(this.hiddenStateSequence=new n.default([],[e.glTextureShape[0],a]),this.hiddenStateSequence.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequenceCopy||(this.hiddenStateSequenceCopy=new n.default([],[e.glTextureShape[0],a]),this.hiddenStateSequenceCopy.createGLTexture({type:'2d',format:'float'})),this.currentX||(this.currentX=new n.default([],[e.glTextureShape[1]]),this.currentX.createGLTexture({type:'2d',format:'float'}));for(let t=0,a=e.glTextureShape[0];t{this.weights[e].createGLTexture({type:'2d',format:'float'})})}}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){const t=this.weights.b_z.tensor.shape[0],a=this.weights.b_r.tensor.shape[0],r=this.weights.b_h.tensor.shape[0],o=new n.default([],[t]),u=new n.default([],[t]),l=new n.default([],[t]),i=new n.default([],[a]),p=new n.default([],[a]),d=new n.default([],[a]),c=this.stateful&&this.currentHiddenState?this.currentHiddenState:new n.default([],[r]),h=new n.default([],[r]),g=new n.default([],[r]),m=new n.default([],[r]);this.hiddenStateSequence=new n.default([],[e.tensor.shape[0],r]);const f=new n.default([],[e.tensor.shape[1]]),_=()=>{s.default.assign(m.tensor,c.tensor),(0,rf.gemv)(1,this.weights.W_z.tensor.transpose(1,0),f.tensor,1,u.tensor),(0,rf.gemv)(1,this.weights.U_z.tensor.transpose(1,0),m.tensor,1,l.tensor),this._combine(o.tensor,u.tensor,l.tensor,this.weights.b_z.tensor),this.recurrentActivationFunc(o),(0,rf.gemv)(1,this.weights.W_r.tensor.transpose(1,0),f.tensor,1,p.tensor),(0,rf.gemv)(1,this.weights.U_r.tensor.transpose(1,0),m.tensor,1,d.tensor),this._combine(i.tensor,p.tensor,d.tensor,this.weights.b_r.tensor),this.recurrentActivationFunc(i),s.default.muleq(i.tensor,m.tensor),(0,rf.gemv)(1,this.weights.W_h.tensor.transpose(1,0),f.tensor,1,h.tensor),(0,rf.gemv)(1,this.weights.U_h.tensor.transpose(1,0),i.tensor,1,g.tensor),this._combine(c.tensor,h.tensor,g.tensor,this.weights.b_h.tensor),this.activationFunc(c),this._update(c.tensor,m.tensor,o.tensor)};for(let t=0,a=e.tensor.shape[0];ts.default.assigns(e.tensor,0)),_(),this.returnSequences&&s.default.assign(this.hiddenStateSequence.tensor.pick(t,null),c.tensor)}this.output=this.returnSequences?this.hiddenStateSequence:c,this.stateful&&(this.currentHiddenState=c)}_stepGPU(){Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.previousHiddenState,inputs:[{input:this.currentHiddenState,name:'source'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXZ,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_z,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHZ,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_z,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentUpdateGateStatePreactiv,inputs:[{input:this.tempXZ,name:'t1'},{input:this.tempHZ,name:'t2'},{input:this.weights.b_z,name:'bias'}]}),'linear'===this.recurrentActivation?this.currentUpdateGateState=this.currentUpdateGateStatePreactiv:Kh.webgl2.runProgram({program:this.recurrentActivationProgram,output:this.currentUpdateGateState,inputs:[{input:this.currentUpdateGateStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXR,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_r,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHR,inputs:[{input:this.previousHiddenState,name:'A'},{input:this.weights.U_r,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentResetGateStatePreactiv,inputs:[{input:this.tempXR,name:'t1'},{input:this.tempHR,name:'t2'},{input:this.weights.b_r,name:'bias'}]}),'linear'===this.recurrentActivation?this.currentResetGateState=this.currentResetGateStatePreactiv:Kh.webgl2.runProgram({program:this.recurrentActivationProgram,output:this.currentResetGateState,inputs:[{input:this.currentResetGateStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.currentResetGateStateCopy,inputs:[{input:this.currentResetGateState,name:'source'}]}),Kh.webgl2.runProgram({program:this.gateProductProgram,output:this.currentResetGateState,inputs:[{input:this.currentResetGateStateCopy,name:'t1'},{input:this.previousHiddenState,name:'t2'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempXH,inputs:[{input:this.currentX,name:'A'},{input:this.weights.W_h,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.matMulProgram,output:this.tempHH,inputs:[{input:this.currentResetGateState,name:'A'},{input:this.weights.U_h,name:'B'}],uniforms:[{value:0,type:'bool',name:'addC'}]}),Kh.webgl2.runProgram({program:this.gateSummationProgram,output:this.currentHiddenStatePreactiv,inputs:[{input:this.tempXH,name:'t1'},{input:this.tempHH,name:'t2'},{input:this.weights.b_h,name:'bias'}]}),'linear'===this.activation?this.currentHiddenState=this.currentHiddenStatePreactiv:Kh.webgl2.runProgram({program:this.activationProgram,output:this.currentHiddenState,inputs:[{input:this.currentHiddenStatePreactiv,name:'x'}]}),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.currentHiddenStateCopy,inputs:[{input:this.currentHiddenState,name:'source'}]}),Kh.webgl2.runProgram({program:this.updateProgram,output:this.currentHiddenState,inputs:[{input:this.currentHiddenStateCopy,name:'h'},{input:this.previousHiddenState,name:'htm1'},{input:this.currentUpdateGateState,name:'z'}]})}_callGPU(e){e.glTexture||e.createGLTexture({type:'2d',format:'float'});const t=this.weights.b_z.glTextureShape[1],a=this.weights.b_r.glTextureShape[1],r=this.weights.b_h.glTextureShape[1];this.currentHiddenState&&this.stateful||(this.currentHiddenState=new n.default([],[r]),this.currentHiddenState.createGLTexture({type:'2d',format:'float'})),this.currentHiddenStateCopy||(this.currentHiddenStateCopy=new n.default([],[r]),this.currentHiddenStateCopy.createGLTexture({type:'2d',format:'float'})),this.currentHiddenStatePreactiv||(this.currentHiddenStatePreactiv=new n.default([],[r]),this.currentHiddenStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.currentUpdateGateState||(this.currentUpdateGateState=new n.default([],[t]),this.currentUpdateGateState.createGLTexture({type:'2d',format:'float'})),this.currentUpdateGateStatePreactiv||(this.currentUpdateGateStatePreactiv=new n.default([],[t]),this.currentUpdateGateStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXZ||(this.tempXZ=new n.default([],[t]),this.tempXZ.createGLTexture({type:'2d',format:'float'})),this.tempHZ||(this.tempHZ=new n.default([],[t]),this.tempHZ.createGLTexture({type:'2d',format:'float'})),this.currentResetGateState||(this.currentResetGateState=new n.default([],[a]),this.currentResetGateState.createGLTexture({type:'2d',format:'float'})),this.currentResetGateStateCopy||(this.currentResetGateStateCopy=new n.default([],[a]),this.currentResetGateStateCopy.createGLTexture({type:'2d',format:'float'})),this.currentResetGateStatePreactiv||(this.currentResetGateStatePreactiv=new n.default([],[a]),this.currentResetGateStatePreactiv.createGLTexture({type:'2d',format:'float'})),this.tempXR||(this.tempXR=new n.default([],[a]),this.tempXR.createGLTexture({type:'2d',format:'float'})),this.tempHR||(this.tempHR=new n.default([],[a]),this.tempHR.createGLTexture({type:'2d',format:'float'})),this.tempXH||(this.tempXH=new n.default([],[r]),this.tempXH.createGLTexture({type:'2d',format:'float'})),this.tempHH||(this.tempHH=new n.default([],[r]),this.tempHH.createGLTexture({type:'2d',format:'float'})),this.previousHiddenState||(this.previousHiddenState=new n.default([],[r]),this.previousHiddenState.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequence||(this.hiddenStateSequence=new n.default([],[e.glTextureShape[0],r]),this.hiddenStateSequence.createGLTexture({type:'2d',format:'float'})),this.hiddenStateSequenceCopy||(this.hiddenStateSequenceCopy=new n.default([],[e.glTextureShape[0],r]),this.hiddenStateSequenceCopy.createGLTexture({type:'2d',format:'float'})),this.currentX||(this.currentX=new n.default([],[e.glTextureShape[1]]),this.currentX.createGLTexture({type:'2d',format:'float'}));for(let t=0,a=e.glTextureShape[0];t=e.tensor.shape.length?e.createGLTexture({type:'2d',format:'float'}):2=a.length?this.slice.createGLTexture({type:'2d',format:'float'}):(this.slice.reshapeTo2DSquare(),this.slice.createGLTexture({type:'2d',format:'float'}))),2>=this.inputShape.length?Kh.webgl2.runProgram({program:this.selectSliceProgram,output:this.slice,inputs:[{input:e,name:'x'}],uniforms:[{value:0,type:'int',name:'t'}]}):Kh.webgl2.runProgram({program:this.mapInputProgram,output:this.slice,inputs:[{input:e,name:'x'},{input:this.indexMaps[0],name:'indexMap'}],uniforms:[{value:e.glTextureShape[1],type:'int',name:'inputCols'}]}),this.wrappedLayer._callGPU(this.slice),this.sliceOutput=this.wrappedLayer.output,this.output||(2>=this.inputShape.length?(this.outputShape=[t,this.sliceOutput.glTextureShape[1]],this.output=new o.default([],this.outputShape),this.outputCopy=new o.default([],this.outputShape),this.output.createGLTexture({type:'2d',format:'float'}),this.outputCopy.createGLTexture({type:'2d',format:'float'})):(this.outputShape=[t,...this.sliceOutput.originalShape],this.output=new o.default([],this.outputShape),this.outputCopy=new o.default([],this.outputShape),this.output.reshapeTo2DSquare(),this.outputCopy.reshapeTo2DSquare(),this.output.createGLTexture({type:'2d',format:'float'}),this.outputCopy.createGLTexture({type:'2d',format:'float'}),this._createOutputIndexMap(this.sliceOutput.indicesForReshaped))),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.outputCopy,inputs:[{input:this.output,name:'source'}]}),2>=this.inputShape.length?Kh.webgl2.runProgram({program:this.copySliceOutputProgram,output:this.output,inputs:[{input:this.outputCopy,name:'outputCopy'},{input:this.sliceOutput,name:'sliceOutput'}],uniforms:[{value:0,type:'int',name:'t'},{value:t,type:'int',name:'timesteps'}]}):Kh.webgl2.runProgram({program:this.mapSliceOutputProgram,output:this.output,inputs:[{input:this.outputCopy,name:'outputCopy'},{input:this.sliceOutput,name:'sliceOutput'},{input:this.outputIndexMaps[0],name:'indexMap'}]});for(let a=1;a=this.inputShape.length?Kh.webgl2.runProgram({program:this.selectSliceProgram,output:this.slice,inputs:[{input:e,name:'x'}],uniforms:[{value:a,type:'int',name:'t'}]}):Kh.webgl2.runProgram({program:this.mapInputProgram,output:this.slice,inputs:[{input:e,name:'x'},{input:this.indexMaps[a],name:'indexMap'}],uniforms:[{value:e.glTextureShape[1],type:'int',name:'inputCols'}]}),this.wrappedLayer._callGPU(this.slice),this.sliceOutput=this.wrappedLayer.output,Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.outputCopy,inputs:[{input:this.output,name:'source'}]}),2>=this.inputShape.length?Kh.webgl2.runProgram({program:this.copySliceOutputProgram,output:this.output,inputs:[{input:this.outputCopy,name:'outputCopy'},{input:this.sliceOutput,name:'sliceOutput'}],uniforms:[{value:a,type:'int',name:'t'},{value:t,type:'int',name:'timesteps'}]}):Kh.webgl2.runProgram({program:this.mapSliceOutputProgram,output:this.output,inputs:[{input:this.outputCopy,name:'outputCopy'},{input:this.sliceOutput,name:'sliceOutput'},{input:this.outputIndexMaps[a],name:'indexMap'}]});0===this.outbound.length&&(this.output.transferFromGLTexture(),this.output.is2DReshaped?this.output.reshapeFrom2D():this.output.is2DSquareReshaped&&this.output.reshapeFrom2DSquare())}}t.default=s});Ce(q_);var U_=ke(function(e,t){function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),t.default=void 0;var r=a(Zh),o=a(gg),n=a(dg),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,a):{};r.get||r.set?Object.defineProperty(t,a,r):t[a]=e[a]}return t.default=e,t}(O_);class s extends r.default{constructor(e={}){super(e),this.layerClass='Bidirectional';const{layer:t,merge_mode:a='concat'}=e;t||this.throwError('wrapped layer is undefined.'),['SimpleRNN','GRU','LSTM'].includes(t.class_name)||this.throwError(`cannot wrap ${t.class_name} layer.`),['concat','sum','mul','ave'].includes(a)||this.throwError(`merge_mode ${a} not supported.`);const r=Object.assign({},t.config,{gpu:e.gpu}),o=Object.assign({},t.config,{gpu:e.gpu});o.go_backwards=!o.go_backwards,this.forwardLayer=new i[t.class_name](r),this.backwardLayer=new i[t.class_name](o),this.forwardLayer.outbound=[null],this.backwardLayer.outbound=[null],this.mergeMode=a,this.returnSequences=t.config.return_sequences,this.gpu&&(this.copyTextureProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\n\nin vec2 outTex;\nuniform sampler2D source;\nout vec4 outColor;\n\nvoid main(void) {\n outColor = texture(source, vec2(outTex.x, outTex.y));\n}\n'),'concat'===this.mergeMode?this.mergeProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\n\nin vec2 outTex;\nuniform sampler2D forward;\nuniform sampler2D backward;\nout vec4 outColor;\n\nvoid main() {\n ivec2 size = textureSize(forward, 0);\n int out_x = int(float(size[0] * 2) * outTex.x);\n int out_y = int(float(size[1]) * outTex.y);\n\n if (out_x >= 0 && out_x < size[0]) {\n outColor = vec4(texelFetch(forward, ivec2(out_x, out_y), 0).r);\n } else {\n outColor = vec4(texelFetch(backward, ivec2(out_x - size[0], size[1] - out_y - 1), 0).r);\n }\n}\n'):'sum'===this.mergeMode?this.mergeProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\n\nin vec2 outTex;\nuniform sampler2D forward;\nuniform sampler2D backward;\nout vec4 outColor;\n\nvoid main() {\n ivec2 size = textureSize(forward, 0);\n int out_x = int(float(size[0]) * outTex.x);\n int out_y = int(float(size[1]) * outTex.y);\n\n float forward_val = texelFetch(forward, ivec2(out_x, out_y), 0).r;\n float backward_val = texelFetch(backward, ivec2(out_x, size[1] - out_y - 1), 0).r;\n\n outColor = vec4(forward_val + backward_val);\n}\n'):'mul'===this.mergeMode?this.mergeProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\n\nin vec2 outTex;\nuniform sampler2D forward;\nuniform sampler2D backward;\nout vec4 outColor;\n\nvoid main() {\n ivec2 size = textureSize(forward, 0);\n int out_x = int(float(size[0]) * outTex.x);\n int out_y = int(float(size[1]) * outTex.y);\n\n float forward_val = texelFetch(forward, ivec2(out_x, out_y), 0).r;\n float backward_val = texelFetch(backward, ivec2(out_x, size[1] - out_y - 1), 0).r;\n\n outColor = vec4(forward_val * backward_val);\n}\n'):'ave'===this.mergeMode&&(this.mergeProgram=Kh.webgl2.compileProgram('#version 300 es\nprecision highp float;\n\nin vec2 outTex;\nuniform sampler2D forward;\nuniform sampler2D backward;\nout vec4 outColor;\n\nvoid main() {\n ivec2 size = textureSize(forward, 0);\n int out_x = int(float(size[0]) * outTex.x);\n int out_y = int(float(size[1]) * outTex.y);\n\n float forward_val = texelFetch(forward, ivec2(out_x, out_y), 0).r;\n float backward_val = texelFetch(backward, ivec2(out_x, size[1] - out_y - 1), 0).r;\n\n outColor = vec4(0.5 * (forward_val + backward_val));\n}\n')))}setWeights(e){this.forwardLayer.setWeights(e.slice(0,e.length/2)),this.backwardLayer.setWeights(e.slice(e.length/2))}call(e){return this.gpu?this._callGPU(e):this._callCPU(e),this.output}_callCPU(e){this.forwardLayer._callCPU(new o.default(e.tensor.data,e.tensor.shape)),this.backwardLayer._callCPU(new o.default(e.tensor.data,e.tensor.shape));const t=this.forwardLayer.output,a=this.backwardLayer.output;this.returnSequences&&(a.tensor=a.tensor.step(-1));const r=t.tensor.shape.slice();'concat'===this.mergeMode&&(r[r.length-1]+=a.tensor.shape[r.length-1]),this.output=new o.default([],r),'concat'===this.mergeMode?this.returnSequences?(n.default.assign(this.output.tensor.hi(r[0],t.tensor.shape[1]).lo(0,0),t.tensor),n.default.assign(this.output.tensor.hi(r[0],r[1]).lo(0,t.tensor.shape[1]),a.tensor)):(n.default.assign(this.output.tensor.hi(t.tensor.shape[0]).lo(0),t.tensor),n.default.assign(this.output.tensor.hi(r[0]).lo(t.tensor.shape[0]),a.tensor)):'sum'===this.mergeMode?(n.default.addeq(this.output.tensor,t.tensor),n.default.addeq(this.output.tensor,a.tensor)):'mul'===this.mergeMode?(n.default.assigns(this.output.tensor,1),n.default.muleq(this.output.tensor,t.tensor),n.default.muleq(this.output.tensor,a.tensor)):'ave'===this.mergeMode&&(n.default.addeq(this.output.tensor,t.tensor),n.default.addeq(this.output.tensor,a.tensor),n.default.divseq(this.output.tensor,2))}_callGPU(e){e.glTexture||e.createGLTexture({type:'2d',format:'float'}),this.inputCopy||(this.inputCopy=new o.default([],e.glTextureShape),this.inputCopy.createGLTexture({type:'2d',format:'float'})),Kh.webgl2.runProgram({program:this.copyTextureProgram,output:this.inputCopy,inputs:[{input:e,name:'source'}]}),this.forwardLayer._callGPU(e),this.backwardLayer._callGPU(this.inputCopy);const t=this.forwardLayer.output,a=this.backwardLayer.output,r=t.glTextureShape.slice();'concat'===this.mergeMode&&(r[1]+=a.glTextureShape[1]),this.output||(this.output=new o.default([],r),this.output.createGLTexture({type:'2d',format:'float'}),!this.returnSequences&&(this.output.is1D=!0)),Kh.webgl2.runProgram({program:this.mergeProgram,output:this.output,inputs:[{input:t,name:'forward'},{input:a,name:'backward'}]}),0===this.outbound.length&&this.output.transferFromGLTexture()}}t.default=s});Ce(U_);var B_=ke(function(e,t){function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),Object.defineProperty(t,'TimeDistributed',{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(t,'Bidirectional',{enumerable:!0,get:function(){return o.default}});var r=a(q_),o=a(U_)});Ce(B_);var N_=ke(function(e,t){Object.defineProperty(t,'__esModule',{value:!0});var a={InputLayer:!0};Object.defineProperty(t,'InputLayer',{enumerable:!0,get:function(){return r.default}});var r=function(e){return e&&e.__esModule?e:{default:e}}(mg);Object.keys(zg).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return zg[e]}})}),Object.keys(ym).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return ym[e]}})}),Object.keys(Zf).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return Zf[e]}})}),Object.keys(Yf).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return Yf[e]}})}),Object.keys(d_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return d_[e]}})}),Object.keys(g_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return g_[e]}})}),Object.keys(f_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f_[e]}})}),Object.keys(L_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L_[e]}})}),Object.keys(O_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return O_[e]}})}),Object.keys(B_).forEach(function(e){'default'===e||'__esModule'===e||Object.prototype.hasOwnProperty.call(a,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B_[e]}})})});Ce(N_);var V_=ke(function(e,t){function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),t.default=void 0;var r=a(gg),o=a(dg),n=a(tm),i=a(Yg);t.default=class{constructor(e={}){if(this.modelLayersMap=e.modelLayersMap,this.gpu=e.gpu,!this.modelLayersMap)throw new Error(`[CAM] modelLayersMap is required`)}initialize(){if(this.modelLayersMap.forEach((e)=>{'GlobalAveragePooling2D'===e.layerClass&&(this.enabled=!0,this.poolLayer=e)}),this.enabled&&!this.data){this.featureMaps=this.modelLayersMap.get(this.poolLayer.inbound[0]).output;let e=this.poolLayer;for(e.outbound.length||(this.weights=this.poolLayer.output);e.outbound.length;)e=this.modelLayersMap.get(e.outbound[0]),this.weights=e.weights.kernel?e.weights.kernel:this.poolLayer.output;if(this.inputShape=this.featureMaps.is2DReshaped?this.featureMaps.originalShape.slice(0,2):this.featureMaps.tensor.shape.slice(0,2),1===this.weights.tensor.shape.length)this.shape=this.inputShape;else{const e=this.weights.tensor.shape[1];this.shape=[...this.inputShape,e]}this.data=new Float32Array(this.shape.reduce((e,t)=>e*t,1))}}update(){if(this.enabled){this.featureMaps=this.modelLayersMap.get(this.poolLayer.inbound[0]).output,this.gpu?this._updateGPU():this._updateCPU();const e=o.default.inf(this.output.tensor),t=o.default.sup(this.output.tensor);o.default.divseq(o.default.subseq(this.output.tensor,e),t-e),this.data=this.output.tensor.data}}_updateCPU(){if(this.featureMaps.is2DReshaped||this.featureMaps.reshapeTo2D(),1===this.weights.tensor.shape.length){this.output||(this.output=new r.default([],this.shape));const e=new r.default([],[this.shape[0]*this.shape[1]]);(0,rf.gemv)(1,this.featureMaps.tensor,this.weights.tensor,1,e.tensor),this.output.replaceTensorData(e.tensor.data)}else this.output||(this.output=new r.default([],this.shape)),this.output.reshapeTo2D(),(0,n.default)(this.output.tensor,this.featureMaps.tensor,this.weights.tensor,1,1),this.output.reshapeFrom2D();o.default.maxseq(this.output.tensor,0),this.featureMaps.is2DReshaped&&this.featureMaps.reshapeFrom2D()}_updateGPU(){this.output||(this.output=new r.default([],this.shape));const e=this.weights.is1D;!this.output.glTexture&&e?this.output.createGLTexture({type:'2d',format:'float'}):(this.output.reshapeTo2D(),this.output.createGLTexture({type:'2d',format:'float'}));const t=e?this.weights.glTextureShape[1]:this.weights.glTextureShape[0];if(!this.program){const a=(0,i.default)('cam',this.output.glTextureShape,t,e);this.program=Kh.webgl2.compileProgram(a)}Kh.webgl2.runProgram({program:this.program,output:this.output,inputs:[{input:this.featureMaps,name:'featureMaps'},{input:this.weights,name:'weights'}]}),this.output.transferFromGLTexture(),this.output.is2DReshaped&&this.output.reshapeFrom2D()}}});Ce(V_);var H_=ke(function(e,t){Object.defineProperty(t,'__esModule',{value:!0}),Object.defineProperty(t,'CAM',{enumerable:!0,get:function(){return a.default}});var a=function(e){return e&&e.__esModule?e:{default:e}}(V_)});Ce(H_);var W_=Oo,X_=ke(function(e,t){var a=t;a.length=function(e){var t=e.length;if(!t)return 0;for(var a=0;1<--t%4&&'='===e.charAt(t);)++a;return In(3*e.length)/4-a};for(var r=Array(64),o=Array(123),n=0;64>n;)o[r[n]=26>n?n+65:52>n?n+71:62>n?n-4:43|n-59]=n++;a.encode=function(e,a,o){for(var n=null,s=[],u=0,i=0,l,t;a>2],l=(3&t)<<4,i=1):1==i?(s[u++]=r[l|t>>4],l=(15&t)<<2,i=2):2==i?(s[u++]=r[l|t>>6],s[u++]=r[63&t],i=0):void 0,8191>4,i=t,u=2):2==u?(a[r++]=(15&i)<<4|(60&t)>>2,i=t,u=3):3==u?(a[r++]=(3&i)<<6|t,u=0):void 0}if(1==u)throw Error(s);return r-n},a.test=function(e){return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}),$_=qo;qo.prototype.on=function(e,t,a){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:a||this}),this},qo.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var a=this._listeners[e],r=0;ra?t+=1:2048>a?t+=2:55296==(64512&a)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t},a.read=function(e,a,r){var o=r-a;if(1>o)return'';for(var n=null,s=[],u=0,i;ai?s[u++]=i:191i?s[u++]=(31&i)<<6|63&e[a++]:239i?(i=((7&i)<<18|(63&e[a++])<<12|(63&e[a++])<<6|63&e[a++])-65536,s[u++]=55296+(i>>10),s[u++]=56320+(1023&i)):s[u++]=(15&i)<<12|(63&e[a++])<<6|63&e[a++],8191n?t[a++]=n:2048>n?(t[a++]=192|n>>6,t[a++]=128|63&n):55296==(64512&n)&&56320==(64512&(i=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&i),++o,t[a++]=240|n>>18,t[a++]=128|63&n>>12,t[a++]=128|63&n>>6,t[a++]=128|63&n):(t[a++]=224|n>>12,t[a++]=128|63&n>>6,t[a++]=128|63&n);return a-r}}),Y_=Xo,J_=$o,ex=$o.zero=new $o(0,0);ex.toNumber=function(){return 0},ex.zzEncode=ex.zzDecode=function(){return this},ex.length=function(){return 1};var tx=$o.zeroHash='\0\0\0\0\0\0\0\0';$o.fromNumber=function(e){if(0===e)return ex;var t=0>e;t&&(e=-e);var a=e>>>0,r=(e-a)/4294967296>>>0;return t&&(r=~r>>>0,a=~a>>>0,4294967295<++a&&(a=0,4294967295<++r&&(r=0))),new $o(a,r)},$o.from=function(e){if('number'==typeof e)return $o.fromNumber(e);if(rx.isString(e))if(rx.Long)e=rx.Long.fromString(e);else return $o.fromNumber(parseInt(e,10));return e.low||e.high?new $o(e.low>>>0,e.high>>>0):ex},$o.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,a=~this.hi>>>0;return t||(a=a+1>>>0),-(t+4294967296*a)}return this.lo+4294967296*this.hi},$o.prototype.toLong=function(e){return rx.Long?new rx.Long(0|this.lo,0|this.hi,!!e):{low:0|this.lo,high:0|this.hi,unsigned:!!e}};var ax=String.prototype.charCodeAt;$o.fromHash=function(e){return e===tx?ex:new $o((ax.call(e,0)|ax.call(e,1)<<8|ax.call(e,2)<<16|ax.call(e,3)<<24)>>>0,(ax.call(e,4)|ax.call(e,5)<<8|ax.call(e,6)<<16|ax.call(e,7)<<24)>>>0)},$o.prototype.toHash=function(){return Dn(255&this.lo,255&this.lo>>>8,255&this.lo>>>16,this.lo>>>24,255&this.hi,255&this.hi>>>8,255&this.hi>>>16,this.hi>>>24)},$o.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},$o.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},$o.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,a=this.hi>>>24;return 0==a?0==t?16384>e?128>e?1:2:2097152>e?3:4:16384>t?128>t?5:6:2097152>t?7:8:128>a?9:10};var rx=ke(function(e,t){function a(e,t,a){for(var r=Object.keys(t),o=0;o(e>>>=0)?1:16384>e?2:2097152>e?3:268435456>e?4:5,e)).len,this},Yo.prototype.int32=function(e){return 0>e?this._push(an,10,nx.fromNumber(e)):this.uint32(e)},Yo.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},Yo.prototype.uint64=function(e){var t=nx.from(e);return this._push(an,t.length(),t)},Yo.prototype.int64=Yo.prototype.uint64,Yo.prototype.sint64=function(e){var t=nx.from(e).zzEncode();return this._push(an,t.length(),t)},Yo.prototype.bool=function(e){return this._push(Jo,1,e?1:0)},Yo.prototype.fixed32=function(e){return this._push(rn,4,e>>>0)},Yo.prototype.sfixed32=Yo.prototype.fixed32,Yo.prototype.fixed64=function(e){var t=nx.from(e);return this._push(rn,4,t.lo)._push(rn,4,t.hi)},Yo.prototype.sfixed64=Yo.prototype.fixed64,Yo.prototype.float=function(e){return this._push(rx.float.writeFloatLE,4,e)},Yo.prototype.double=function(e){return this._push(rx.float.writeDoubleLE,8,e)};var lx=rx.Array.prototype.set?function(e,t,a){t.set(e,a)}:function(e,t,a){for(var r=0;r>>0;if(!t)return this._push(Jo,1,0);if(rx.isString(e)){var a=Yo.alloc(t=ix.length(e));ix.decode(e,a,0),e=a}return this.uint32(t)._push(lx,t,e)},Yo.prototype.string=function(e){var t=sx.length(e);return t?this.uint32(t)._push(sx.write,t,e):this._push(Jo,1,0)},Yo.prototype.fork=function(){return this.states=new Qo(this),this.head=this.tail=new Ko(Zo,0,0),this.len=0,this},Yo.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ko(Zo,0,0),this.len=0),this},Yo.prototype.ldelim=function(){var e=this.head,t=this.tail,a=this.len;return this.reset().uint32(a),a&&(this.tail.next=e.next,this.tail=t,this.len+=a),this},Yo.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),a=0;e;)e.fn(e.val,t,a),a+=e.len,e=e.next;return t},Yo._configure=function(e){ux=e};var px=on;(on.prototype=Object.create(ox.prototype)).constructor=on;var dx=rx.Buffer;on.alloc=function(e){return(on.alloc=rx._Buffer_allocUnsafe)(e)};var cx=dx&&dx.prototype instanceof Uint8Array&&'set'===dx.prototype.set.name?function(e,t,a){t.set(e,a)}:function(e,t,a){if(e.copy)e.copy(t,a,0,e.length);else for(var r=0;r>>0;return this.uint32(t),t&&this._push(cx,t,e),this},on.prototype.string=function(e){var t=dx.byteLength(e);return this.uint32(t),t&&this._push(nn,t,e),this};var hx=un,gx=rx.LongBits,mx=rx.utf8,fx='undefined'==typeof Uint8Array?function(e){if(Array.isArray(e))return new un(e);throw Error('illegal buffer')}:function(e){if(e instanceof Uint8Array||Array.isArray(e))return new un(e);throw Error('illegal buffer')},_x;un.create=rx.Buffer?function(e){return(un.create=function(e){return rx.Buffer.isBuffer(e)?new _x(e):fx(e)})(e)}:fx,un.prototype._slice=rx.Array.prototype.subarray||rx.Array.prototype.slice,un.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,128>this.buf[this.pos++])return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,128>this.buf[this.pos++])return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,128>this.buf[this.pos++])return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,128>this.buf[this.pos++])return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,128>this.buf[this.pos++])return e;if((this.pos+=5)>this.len)throw this.pos=this.len,sn(this,10);return e}}(),un.prototype.int32=function(){return 0|this.uint32()},un.prototype.sint32=function(){var e=this.uint32();return 0|e>>>1^-(1&e)},un.prototype.bool=function(){return 0!==this.uint32()},un.prototype.fixed32=function(){if(this.pos+4>this.len)throw sn(this,4);return pn(this.buf,this.pos+=4)},un.prototype.sfixed32=function(){if(this.pos+4>this.len)throw sn(this,4);return 0|pn(this.buf,this.pos+=4)},un.prototype.float=function(){if(this.pos+4>this.len)throw sn(this,4);var e=rx.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},un.prototype.double=function(){if(this.pos+8>this.len)throw sn(this,4);var e=rx.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},un.prototype.bytes=function(){var e=this.uint32(),t=this.pos,a=this.pos+e;if(a>this.len)throw sn(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,a):t===a?new this.buf.constructor(0):this._slice.call(this.buf,t,a)},un.prototype.string=function(){var e=this.bytes();return mx.read(e,0,e.length)},un.prototype.skip=function(e){if('number'==typeof e){if(this.pos+e>this.len)throw sn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw sn(this);while(128&this.buf[this.pos++]);return this},un.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:do{if(4==(e=7&this.uint32()))break;this.skipType(e)}while(!0);break;case 5:this.skip(4);break;default:throw Error('invalid wire type '+e+' at offset '+this.pos);}return this},un._configure=function(e){_x=e;var t=rx.Long?'toLong':'toNumber';rx.merge(un.prototype,{int64:function(){return ln.call(this)[t](!1)},uint64:function(){return ln.call(this)[t](!0)},sint64:function(){return ln.call(this).zzDecode()[t](!1)},fixed64:function(){return dn.call(this)[t](!0)},sfixed64:function(){return dn.call(this)[t](!1)}})};var xx=cn;(cn.prototype=Object.create(hx.prototype)).constructor=cn,rx.Buffer&&(cn.prototype._slice=rx.Buffer.prototype.slice),cn.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Rn(this.pos+e,this.len))};var yx=hn;(hn.prototype=Object.create(rx.EventEmitter.prototype)).constructor=hn,hn.prototype.rpcCall=function e(t,a,r,o,n){if(!o)throw TypeError('request must be specified');var i=this;if(!n)return rx.asPromise(e,i,t,a,r,o);if(!i.rpcImpl)return void setTimeout(function(){n(Error('already ended'))},0);try{return i.rpcImpl(t,a[i.requestDelimited?'encodeDelimited':'encode'](o).finish(),function(e,a){if(e)return i.emit('error',e,t),n(e);if(null===a)return void i.end(!0);if(!(a instanceof r))try{a=r[i.responseDelimited?'decodeDelimited':'decode'](a)}catch(e){return i.emit('error',e,t),n(e)}return i.emit('data',a,t),n(null,a)})}catch(e){return i.emit('error',e,t),void setTimeout(function(){n(e)},0)}},hn.prototype.end=function(e){return this.rpcImpl&&(!e&&this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit('end').off()),this};var vx=ke(function(e,t){t.Service=yx}),bx={},Sx=ke(function(e,t){function a(){r.Reader._configure(r.BufferReader),r.util._configure()}var r=t;r.build='minimal',r.Writer=ox,r.BufferWriter=px,r.Reader=hx,r.BufferReader=xx,r.util=rx,r.rpc=vx,r.roots=bx,r.configure=a,r.Writer._configure(r.BufferWriter),a()}),Tx=Sx,wx=ke(function(e,t){Object.defineProperty(t,'__esModule',{value:!0}),t.default=t.Model=t.Weights=void 0;var a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,a):{};r.get||r.set?Object.defineProperty(t,a,r):t[a]=e[a]}return t.default=e,t}(Tx);const r=a.Reader,o=a.Writer,n=a.util,s=a.roots['default']||(a.roots['default']={});t.default=s;const i=s.Weights=(()=>{function e(e){if(this.shape=[],e)for(let t=Object.keys(e),a=0;a>>3){case 1:o.layerName=e.string();break;case 2:o.weightName=e.string();break;case 3:if(o.shape&&o.shape.length||(o.shape=[]),2==(7&t))for(let t=e.uint32()+e.pos;e.pos>>0}return null!=e.type&&(t.type=e.type+''),null!=e.data&&('string'==typeof e.data?n.base64.decode(e.data,t.data=n.newBuffer(n.base64.length(e.data)),0):e.data.length&&(t.data=e.data)),null!=e.quantizeMin&&(t.quantizeMin=+e.quantizeMin),null!=e.quantizeMax&&(t.quantizeMax=+e.quantizeMax),t},e.toObject=function(e,t){t||(t={});let a={};if((t.arrays||t.defaults)&&(a.shape=[]),t.defaults&&(a.layerName='',a.weightName='',a.type='',a.data=t.bytes===String?'':[],a.quantizeMin=0,a.quantizeMax=0),null!=e.layerName&&e.hasOwnProperty('layerName')&&(a.layerName=e.layerName),null!=e.weightName&&e.hasOwnProperty('weightName')&&(a.weightName=e.weightName),e.shape&&e.shape.length){a.shape=[];for(let t=0;t{function e(e){if(this.modelWeights=[],e)for(let t=Object.keys(e),a=0;a>>3){case 1:o.id=e.string();break;case 2:o.name=e.string();break;case 3:o.kerasVersion=e.string();break;case 4:o.backend=e.string();break;case 5:o.modelConfig=e.string();break;case 6:o.modelWeights&&o.modelWeights.length||(o.modelWeights=[]),o.modelWeights.push(s.Weights.decode(e,e.uint32()));break;default:e.skipType(7&t);}}return o},e.decodeDelimited=function(e){return e instanceof r||(e=new r(e)),this.decode(e,e.uint32())},e.verify=function(e){if('object'!=typeof e||null===e)return'object expected';if(null!=e.id&&e.hasOwnProperty('id')&&!n.isString(e.id))return'id: string expected';if(null!=e.name&&e.hasOwnProperty('name')&&!n.isString(e.name))return'name: string expected';if(null!=e.kerasVersion&&e.hasOwnProperty('kerasVersion')&&!n.isString(e.kerasVersion))return'kerasVersion: string expected';if(null!=e.backend&&e.hasOwnProperty('backend')&&!n.isString(e.backend))return'backend: string expected';if(null!=e.modelConfig&&e.hasOwnProperty('modelConfig')&&!n.isString(e.modelConfig))return'modelConfig: string expected';if(null!=e.modelWeights&&e.hasOwnProperty('modelWeights')){if(!Array.isArray(e.modelWeights))return'modelWeights: array expected';for(let t=0,a;t{if(e in g){const t=new g[e]({modelLayersMap:this.modelLayersMap,gpu:this.gpu});this.visMap.set(e,t)}}),this._ready=this._initialize()}checkGPUSupport(){return Kh.webgl2.isSupported}ready(){return this._ready}_interrupt(){_.cancel()}async _initialize(){this.events.emit('loadingProgress',0);try{const e=this.filesystem?this._dataRequestFS():this._dataRequestHTTP(this.headers);await e}catch(e){console.log(e),this._interrupt()}this.events.emit('loadingProgress',100),this._buildDAG(),this.inputLayerNames.forEach((e)=>{const t=this.modelLayersMap.get(e);t.call(this.inputTensorsMap.get(e)),t.hasOutput=!0,t.visited=!0});const e=this.pauseAfterLayerCalls;return this.pauseAfterLayerCalls=!0,this.runningProgress=0,this.events.emit('initProgress',0),await this._traverseDAG(this.inputLayerNames,'initProgress'),this.pauseAfterLayerCalls=e,this.finishedLayerNames=[],this.modelLayersMap.forEach((e)=>{e.hasOutput=!1,e.visited=!1}),this.visMap.forEach((e)=>{e.initialize()}),this.events.emit('initProgress',100),!0}async _dataRequestHTTP(e={}){try{const t=await d.default.get(this.filepath,{responseType:'arraybuffer',headers:e,onDownloadProgress:(t)=>{if(t.lengthComputable){const e=En(100*t.loaded/t.total);this.events.emit('loadingProgress',e)}},cancelToken:_.token});this._decodeProtobuf(new Uint8Array(t.data))}catch(e){if(d.default.isCancel(e))console.log('[Model] Data request canceled',e.message);else throw e}}async _dataRequestFS(){const e=p.default.promisify(kx.readFile);try{const t=await e(this.filepath);this._decodeProtobuf(t)}catch(e){throw e}}_decodeProtobuf(e){const t=f.default.Model.verify(e);if(t)throw new Error(`[Model] Invalid model - check protobuf serialization: {err}`);const a=f.default.Model.decode(e);this.id=a.id,this.name=a.name,this.kerasVersion=a.kerasVersion,this.backend=a.backend,this.modelConfig=JSON.parse(a.modelConfig),this.modelWeights=a.modelWeights}toggleGPU(e){this.gpu='undefined'==typeof e?!this.gpu:e,this.modelLayersMap.forEach((e)=>{e.toggleGPU(this.gpu)}),this.visMap.forEach((e)=>{e.gpu=this.gpu}),this.resetInputTensors()}resetInputTensors(){this.inputLayerNames.forEach((e)=>{const t=this.modelLayersMap.get(e);this.inputTensorsMap.set(e,new m.default([],t.shape))})}_buildDAG(){const e=this.modelConfig.class_name;let t=[];if('Sequential'===e?t=this.modelConfig.config:'Model'===e&&(t=this.modelConfig.config.layers),!(Array.isArray(t)&&t.length))throw new Error('[Model] Model configuration does not contain any layers.');t.forEach((a,r)=>{const o=a.class_name,n=a.config;if('Model'===e&&'Sequential'===o)n.forEach((e,t)=>{const r=e.class_name,o=e.config,i=0===t?a.inbound_nodes[0].map((e)=>e[0]):[n[t-1].config.name];this._createLayer(r,o,i)});else if(!(o in h))throw new Error(`[Model] Layer ${o} specified in model configuration is not implemented!`);else{if('Sequential'===e&&0===r){const e='input',t=n.batch_input_shape.slice(1),a=new h.InputLayer({name:e,shape:t,gpu:this.gpu});this.modelLayersMap.set(e,a),this.inputTensorsMap.set(e,new m.default([],t)),this.inputLayerNames.push(e)}else if('Model'===e&&'InputLayer'===o){const e=n.batch_input_shape.slice(1);this.inputTensorsMap.set(n.name,new m.default([],e)),this.inputLayerNames.push(n.name)}let i=[];if('Sequential'===e)i=0===r?['input']:[t[r-1].config.name];else if('Model'===e){const e=a.inbound_nodes;e&&e.length&&(i=e[0].map((e)=>e[0]))}this._createLayer(o,n,i)}}),this.modelLayersMap.forEach((e)=>{this.modelLayersInfo.push((0,l.default)(e,['name','description','layerClass','inbound','outbound'])),0===e.outbound.length&&this.outputLayerNames.push(e.name)}),this.inputLayerNames.sort(),this.outputLayerNames.sort()}_createLayer(e,t,a){const r=new h[e](Object.assign({},t,{gpu:this.gpu}));let o=[];if('Bidirectional'===e){const e=r.forwardLayer.params.map((e)=>`${t.name}/forward_${t.layer.config.name}/${e}`),a=r.backwardLayer.params.map((e)=>`${t.name}/backward_${t.layer.config.name}/${e}`);o=e.concat(a)}else o='TimeDistributed'===e?r.layer.params.map((e)=>`${t.name}/${e}`):r.params.map((e)=>`${t.name}/${e}`);if(o&&o.length){const e=o.map((e)=>{const t=(0,u.default)(this.modelWeights,(t)=>{const a=new RegExp(`^.*${e}`);return a.test(t.weightName)});if(!t)throw new Error(`[Model] error loading weights.`);const{data:a,shape:r,type:o}=t,n=new ArrayBuffer(a.byteLength),i=new Uint8Array(n);if(i.set(new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),'uint8'===o){const{quantizeMin:e,quantizeMax:a}=t,o=new Float32Array(i);for(let t=0,r=o.length;t{this.modelLayersMap.get(t.name).inbound.push(e),this.modelLayersMap.get(e).outbound.push(t.name)})}async _traverseDAG(e,t){if(0===e.length)return this.runningProgress=100,this.events.emit(t,100),!0;if(1===e.length){const a=e[0],r=this.modelLayersMap.get(a);if('InputLayer'===r.layerClass)this.finishedLayerNames.push(this.modelLayersMap.get(a).name);else{const e=this.modelLayersMap.get(a);if(e.visited)return!1;const t=e.inbound.map((e)=>this.modelLayersMap.get(e));if(!(0,s.default)((0,i.default)(t,'hasOutput')))return!1;e.isMergeLayer?e.call((0,i.default)(t,'output')):e.call(t[0].output),e.hasOutput=!0,e.visited=!0,this.finishedLayerNames.push(e.name),this.pauseAfterLayerCalls&&(await p.default.delay(0))}this.runningProgress+=100/this.modelLayersMap.size,this.events.emit(t,this.runningProgress),await this._traverseDAG(r.outbound,t)}else await p.default.all(e.map((e)=>this._traverseDAG([e],t)))}_maybeTransferIntermediateOutputs(){this.gpu&&this.transferLayerOutputs&&this.modelLayersMap.forEach((e)=>{e.output&&e.output.glTexture&&(Kh.webgl2.bindOutputTexture(e.output.glTexture,e.output.glTextureShape),e.output.transferFromGLTexture(),e.output.is2DReshaped&&e.output.reshapeFrom2D())})}loadData(e){this.inputLayerNames.forEach((t)=>{const a=this.modelLayersMap.get(t);this.inputTensorsMap.get(t).replaceTensorData(e[t]),a.call(this.inputTensorsMap.get(t)),a.hasOutput=!0,a.visited=!0})}async predict(e){if(this.isRunning=!0,this.runningProgress=0,this.events.emit('predictProgress',0),!(0,n.default)((0,o.default)(e).sort(),this.inputLayerNames))throw this.isRunning=!1,new Error('[Model] predict() must take an object where the keys are the named inputs of the model: '+JSON.stringify(this.inputLayerNames));if(!(0,s.default)(this.inputLayerNames,(t)=>e[t]instanceof Float32Array))throw this.isRunning=!1,new Error('[Model] predict() must take an object where the values are the flattened data as Float32Array.');this.finishedLayerNames=[],this.modelLayersMap.forEach((e)=>{e.hasOutput=!1,e.visited=!1});let t=(0,c.default)();this.loadData(e),this.predictStats.loadData=(0,c.default)()-t,t=(0,c.default)(),await this._traverseDAG(this.inputLayerNames,'predictProgress'),this.predictStats.forwardPass=(0,c.default)()-t,this._maybeTransferIntermediateOutputs();const a=this.modelConfig.class_name,r={};if('Sequential'===a){const e=this.modelLayersMap.get(this.outputLayerNames[0]);r.output=e.output.tensor.data}else'Model'===a&&this.outputLayerNames.forEach((e)=>{const t=this.modelLayersMap.get(e);r[e]=t.output.tensor.data});return t=(0,c.default)(),this.visMap.forEach((e)=>{e.update()}),this.predictStats.visualizations=(0,c.default)()-t,this.isRunning=!1,this.events.emit('predictProgress',100),r}layerCall(e,t){if(!this.modelLayersMap.has(e))return;let a=t instanceof m.default?t:new m.default(t.data,t.shape);const r=this.modelLayersMap.get(e);return r.call(a)}cleanup(){Kh.webgl2.clearRefs(),this.modelLayersMap.clear(),this.inputTensorsMap.clear(),this.visMap.clear(),delete this.modelWeights}}});Ce(Fx);var Mx=Ss.isFinite,Dx=gn,Ix=1/0,Ex=mn,Rx=Sg({args:['array','scalar','index'],body:function(e,t,a){var r=t,o;for(o=0;oa[o]+s)return!1}return!0};var r=a(Dx),o=a(Ex),n=a(Ax)});Ce(Lx);var jx=ke(function(e,t){function a(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,a):{};r.get||r.set?Object.defineProperty(t,a,r):t[a]=e[a]}return t.default=e,t}function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),Object.defineProperty(t,'Model',{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,'Tensor',{enumerable:!0,get:function(){return n.default}}),t.testUtils=t.layers=t.activations=t.default=t.GPU_SUPPORT=void 0;var o=r(Fx),n=r(gg),i=a(Eg);t.activations=i;var s=a(N_);t.layers=s;var u=a(Lx);t.testUtils=u;const l=Kh.webgl2.isSupported;t.GPU_SUPPORT=l;const p={Model:o.default,Tensor:n.default,GPU_SUPPORT:l,activations:i,layers:s,testUtils:u};t.default=p}),zx=Ce(jx),Gx=function(e,t,a,r){return new(a||(a=Promise))(function(o,n){function i(e){try{u(r.next(e))}catch(t){n(t)}}function s(e){try{u(r['throw'](e))}catch(t){n(t)}}function u(e){e.done?o(e.value):new a(function(t){t(e.value)}).then(i,s)}u((r=r.apply(e,t||[])).next())})},Ox=!1;try{Ox='[object process]'===Object.prototype.toString.call(global.process)}catch(t){}var qx=r('MODEL_PATH')||'/dist/model.bin',Ux=new zx.Model({filepath:Ox?__dirname+'/model.bin':qx,gpu:!1,filesystem:Ox});(function(e){e[e.TD=0]='TD',e[e.IHS=1]='IHS',e[e.HS=2]='HS',e[e.TU=3]='TU',e[e.DT=4]='DT',e[e.DB=5]='DB'})(e.AvailablePatterns||(e.AvailablePatterns={}));class Bx extends Hn{}Bx.predictPattern=xn,Bx.hasDoubleBottom=yn,Bx.hasDoubleTop=vn,Bx.hasHeadAndShoulder=bn,Bx.hasInverseHeadAndShoulder=Sn,Bx.isTrendingUp=Tn,Bx.isTrendingDown=wn;let Nx=Pn();e.getAvailableIndicators=Pn,e.AvailableIndicators=Nx,e.FixedSizeLinkedList=qn,e.CandleData=Un,e.CandleList=Bn,e.sma=n,e.SMA=Wn,e.ema=i,e.EMA=Xn,e.wma=s,e.WMA=$n,e.wema=u,e.WEMA=Kn,e.macd=l,e.MACD=Zn,e.rsi=c,e.RSI=Jn,e.bollingerbands=g,e.BollingerBands=ti,e.adx=_,e.ADX=si,e.atr=x,e.ATR=ui,e.truerange=f,e.TrueRange=ni,e.roc=y,e.ROC=li,e.kst=v,e.KST=pi,e.psar=b,e.PSAR=di,e.stochastic=S,e.Stochastic=ci,e.williamsr=T,e.WilliamsR=hi,e.adl=w,e.ADL=gi,e.obv=P,e.OBV=mi,e.trix=C,e.TRIX=fi,e.forceindex=k,e.ForceIndex=_i,e.cci=F,e.CCI=xi,e.awesomeoscillator=M,e.AwesomeOscillator=yi,e.vwap=D,e.VWAP=vi,e.volumeprofile=R,e.VolumeProfile=bi,e.mfi=L,e.MFI=Ti,e.stochasticrsi=j,e.StochasticRSI=wi,e.averagegain=p,e.AverageGain=Qn,e.averageloss=d,e.AverageLoss=Yn,e.sd=h,e.SD=ei,e.highest=z,e.Highest=Pi,e.lowest=G,e.Lowest=Ci,e.sum=O,e.Sum=ki,e.renko=q,e.HeikinAshi=Mi,e.heikinashi=U,e.bullish=ne,e.bearish=xe,e.abandonedbaby=ye,e.doji=W,e.bearishengulfingpattern=ie,e.bullishengulfingpattern=N,e.darkcloudcover=ve,e.downsidetasukigap=$,e.dragonflydoji=be,e.gravestonedoji=Se,e.bullishharami=V,e.bearishharami=se,e.bullishharamicross=H,e.bearishharamicross=ue,e.eveningdojistar=le,e.eveningstar=pe,e.morningdojistar=X,e.morningstar=B,e.bullishmarubozu=K,e.bearishmarubozu=de,e.piercingline=Z,e.bullishspinningtop=Te,e.bearishspinningtop=we,e.threeblackcrows=ce,e.threewhitesoldiers=Q,e.bullishhammerstick=Y,e.bearishhammerstick=ee,e.bullishinvertedhammerstick=J,e.bearishinvertedhammerstick=te,e.hammerpattern=ae,e.hammerpatternunconfirmed=re,e.hangingman=he,e.hangingmanunconfirmed=ge,e.shootingstar=me,e.shootingstarunconfirmed=fe,e.tweezertop=_e,e.tweezerbottom=oe,e.fibonacciretracement=Pe,e.predictPattern=xn,e.PatternDetector=Bx,e.hasDoubleBottom=yn,e.hasDoubleTop=vn,e.hasHeadAndShoulder=bn,e.hasInverseHeadAndShoulder=Sn,e.isTrendingUp=Tn,e.isTrendingDown=wn,e.setConfig=a,e.getConfig=r})(this.window=this.window||{},window);
-//# sourceMappingURL=browser.es6.js.map
+var tf = window.tf || {};(function(e,r){'use strict';function t(e){return se[e]}function a(e){let r=t('precision');return r?parseFloat(e.toPrecision(r)):e}function o(e){ie.reverseInputs(e);var r=new he(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function l(e){ie.reverseInputs(e);var r=new pe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function n(e){ie.reverseInputs(e);var r=new ge(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function s(e){ie.reverseInputs(e);var r=new de(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function u(e){ie.reverseInputs(e);var r=new ve(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function i(e){ie.reverseInputs(e);var r=new ce(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function h(e){ie.reverseInputs(e);var r=new me(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function p(e){ie.reverseInputs(e);var r=new xe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function g(e){ie.reverseInputs(e);var r=new we(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function d(e){ie.reverseInputs(e);var r=new fe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function v(e){ie.reverseInputs(e);var r=new be(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function c(e){ie.reverseInputs(e);var r=new Se(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function m(e){ie.reverseInputs(e);var r=new Ce(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function x(e){ie.reverseInputs(e);var r=new Ee(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function w(e){ie.reverseInputs(e);var r=new Ve(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function f(e){ie.reverseInputs(e);var r=new He(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function I(e){ie.reverseInputs(e);var r=new ke(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function _(e){ie.reverseInputs(e);var r=new Te(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function P(e){ie.reverseInputs(e);var r=new De(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function b(e){ie.reverseInputs(e);var r=new Ae(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function q(e){ie.reverseInputs(e);var r=new Be(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function S(e){ie.reverseInputs(e);var r=new ze(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function C(e){ie.reverseInputs(e);var r=new Le(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function E(e){ie.reverseInputs(e);var r=new Me(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function V(e){ie.reverseInputs(e);var r=new je(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function H(e,r,t,a){return e<=t&&r>=t||t<=e&&a>=e}function k(e){ie.reverseInputs(e);var r=new Re(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function T(e){ie.reverseInputs(e);var r=new Oe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function D(e){ie.reverseInputs(e);var r=new Fe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function A(e){ie.reverseInputs(e);var r=new Ue(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function B(e){ie.reverseInputs(e);var r=new We(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function z(e){ie.reverseInputs(e);var r=new Ge(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}function L(e){ie.reverseInputs(e);var r=new Ne(e).result;return e.reversedInput&&(r.open.reverse(),r.high.reverse(),r.low.reverse(),r.close.reverse(),r.volume.reverse(),r.timestamp.reverse()),ie.reverseInputs(e),r}function M(e){ie.reverseInputs(e);var r=new Xe(e).result;return e.reversedInput&&(r.open.reverse(),r.high.reverse(),r.low.reverse(),r.close.reverse(),r.volume.reverse(),r.timestamp.reverse()),ie.reverseInputs(e),r}function j(e){return new lr().hasPattern(e)}function R(e){return new nr().hasPattern(e)}function y(e){return new sr().hasPattern(e)}function O(e){return new ur().hasPattern(e)}function F(e,r){var t=function(e,r,t){return e+(r-e)*t},a=[],o=new Number((e.length-1)/(r-1));a[0]=e[0];for(var l=1;le+r*r,0),t=te(r);return e.map((e)=>e/t)}function W(){return zr(this,void 0,void 0,function*(){return Rr?Promise.resolve(!0):yr?jr:(jr=new Promise(function(e){return zr(this,void 0,void 0,function*(){if(Lr){console.log('Nodejs Environment detected ');var t=require('@tensorflow/tfjs-node'),a=require('path').resolve(__dirname,'../tf_model/model.json');Br=yield r.loadModel(t.io.fileSystem(a))}else{if(console.log('Browser Environment detected '),'undefined'==typeof r||'undefined'==typeof r.loadModel)return console.log('Tensorflow js not imported, pattern detection may not work'),Rr=!1,yr=!1,void e();Br=yield r.loadModel('/tf_model/model.json')}return Rr=!0,yr=!1,void e()})}),void(yr=!0))})}function G(e){return zr(this,void 0,void 0,function*(){yield W(),300>e.values.length&&console.warn('Pattern detector requires atleast 300 data points for a reliable prediction, received just ',e.values.length),ie.reverseInputs(e);var t=e.values,a=yield Br.predict(r.tensor2d([U(F(t,400))])),o=r.argMax(a,1).get(0);return ie.reverseInputs(e),{patternId:o,pattern:Mr[o],probability:100*a.get(0,4)}})}function N(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.DB})}function X(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.DT})}function K(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.HS})}function Q(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.IHS})}function Y(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.TU})}function Z(r){return zr(this,void 0,void 0,function*(){var t=yield G(r);return t.patternId===e.AvailablePatterns.TD})}function $(){return['sma','ema','wma','wema','macd','rsi','bollingerbands','adx','atr','truerange','roc','kst','psar','stochastic','williamsr','adl','obv','trix','cci','awesomeoscillator','forceindex','vwap','volumeprofile','renko','heikinashi','stochasticrsi','mfi','averagegain','averageloss','highest','lowest','sum','FixedSizeLinkedList','sd','bullish','bearish','abandonedbaby','doji','bearishengulfingpattern','bullishengulfingpattern','darkcloudcover','downsidetasukigap','dragonflydoji','gravestonedoji','bullishharami','bearishharami','bullishharamicross','bearishharamicross','eveningdojistar','eveningstar','morningdojistar','morningstar','bullishmarubozu','bearishmarubozu','piercingline','bullishspinningtop','bearishspinningtop','threeblackcrows','threewhitesoldiers','bullishhammerstick','bearishhammerstick','bullishinvertedhammerstick','bearishinvertedhammerstick','hammerpattern','hammerpatternunconfirmed','hangingman','hangingmanunconfirmed','shootingstar','shootingstarunconfirmed','tweezertop','tweezerbottom','predictPattern','hasDoubleBottom','hasDoubleTop','hasHeadAndShoulder','hasInverseHeadAndShoulder','isTrendingUp','isTrendingDown']}var J=Math.min,ee=Math.max,re=Math.abs,te=Math.sqrt;class ae{constructor(e,r,t){this.next=t,t&&(t.prev=this),this.prev=r,r&&(r.next=this),this.data=e}}class oe{constructor(){this._length=0}get head(){return this._head&&this._head.data}get tail(){return this._tail&&this._tail.data}get current(){return this._current&&this._current.data}get length(){return this._length}push(e){this._tail=new ae(e,this._tail),0===this._length&&(this._head=this._tail,this._current=this._head,this._next=this._head),this._length++}pop(){var e=this._tail;if(0!==this._length)return(this._length--,0===this._length)?(this._head=this._tail=this._current=this._next=void 0,e.data):(this._tail=e.prev,this._tail.next=void 0,this._current===e&&(this._current=this._tail,this._next=void 0),e.data)}shift(){var e=this._head;if(0!==this._length)return(this._length--,0===this._length)?(this._head=this._tail=this._current=this._next=void 0,e.data):(this._head=this._head.next,this._current===e&&(this._current=this._head,this._next=this._current.next),e.data)}unshift(e){this._head=new ae(e,void 0,this._head),0===this._length&&(this._tail=this._head,this._next=this._head),this._length++}unshiftCurrent(){var e=this._current;return e===this._head||2>this._length?e&&e.data:(e===this._tail?(this._tail=e.prev,this._tail.next=void 0,this._current=this._tail):(e.next.prev=e.prev,e.prev.next=e.next,this._current=e.prev),this._next=this._current.next,e.next=this._head,e.prev=void 0,this._head.prev=e,this._head=e,e.data)}removeCurrent(){var e=this._current;if(0!==this._length)return(this._length--,0===this._length)?(this._head=this._tail=this._current=this._next=void 0,e.data):(e===this._tail?(this._tail=e.prev,this._tail.next=void 0,this._current=this._tail):e===this._head?(this._head=e.next,this._head.prev=void 0,this._current=this._head):(e.next.prev=e.prev,e.prev.next=e.next,this._current=e.prev),this._next=this._current.next,e.data)}resetCursor(){return this._current=this._next=this._head,this}next(){var e=this._next;if(void 0!==e)return this._next=e.next,this._current=e,e.data}}class le extends oe{constructor(e,r,t,a){if(super(),this.size=e,this.maintainHigh=r,this.maintainLow=t,this.maintainSum=a,this.totalPushed=0,this.periodHigh=0,this.periodLow=Infinity,this.periodSum=0,!e||'number'!=typeof e)throw'Size required and should be a number.';this._push=this.push,this.push=function(e){this.add(e),this.totalPushed++}}add(e){this.length===this.size?(this.lastShift=this.shift(),this._push(e),this.maintainHigh&&this.lastShift==this.periodHigh&&this.calculatePeriodHigh(),this.maintainLow&&this.lastShift==this.periodLow&&this.calculatePeriodLow(),this.maintainSum&&(this.periodSum-=this.lastShift)):this._push(e),this.maintainHigh&&this.periodHigh<=e&&(this.periodHigh=e),this.maintainLow&&this.periodLow>=e&&(this.periodLow=e),this.maintainSum&&(this.periodSum+=e)}*iterator(){for(this.resetCursor();this.next();)yield this.current}calculatePeriodHigh(){for(this.resetCursor(),this.next()&&(this.periodHigh=this.current);this.next();)this.periodHigh<=this.current&&(this.periodHigh=this.current)}calculatePeriodLow(){for(this.resetCursor(),this.next()&&(this.periodLow=this.current);this.next();)this.periodLow>=this.current&&(this.periodLow=this.current)}}class ne{constructor(){this.open=[],this.high=[],this.low=[],this.close=[],this.volume=[],this.timestamp=[]}}let se={};class ue{}class ie{constructor(e){this.format=e.format||a}static reverseInputs(e){e.reversedInput&&(e.values?e.values.reverse():void 0,e.open?e.open.reverse():void 0,e.high?e.high.reverse():void 0,e.low?e.low.reverse():void 0,e.close?e.close.reverse():void 0,e.volume?e.volume.reverse():void 0,e.timestamp?e.timestamp.reverse():void 0)}getResult(){return this.result}}class he extends ie{constructor(e){super(e),this.period=e.period,this.price=e.values;this.generator=function*(e){var r,t=new oe,a=0,o=1,l=yield;for(t.push(0);;)o{var r=this.generator.next(e);r.value!==void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e).value;if(r!=void 0)return this.format(r)}}he.calculate=o;class pe extends ie{constructor(e){super(e);var r,t=e.period,a=e.values;this.result=[],r=new he({period:t,values:[]});this.generator=function*(){for(var e,a=yield;;)void 0!=e&&void 0!==a?(e=(a-e)*(2/(t+1))+e,a=yield e):(a=yield,e=r.nextValue(a),e&&(a=yield e))}(),this.generator.next(),this.generator.next(),a.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e).value;if(r!=void 0)return this.format(r)}}pe.calculate=l;class ge extends ie{constructor(e){super(e);var r=e.period,t=e.values;this.result=[],this.generator=function*(){for(let t=new oe;;)if(t.length{var r=this.generator.next(e);r.value!=void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e).value;if(r!=void 0)return this.format(r)}}ge.calculate=n;class de extends ie{constructor(e){super(e);var r,t=e.period,a=e.values;this.result=[],r=new he({period:t,values:[]});this.generator=function*(){for(var e,a=yield;;)void 0!=e&&void 0!==a?(e=(a-e)*(1/t)+e,a=yield e):(a=yield,e=r.nextValue(a),void 0!==e&&(a=yield e))}(),this.generator.next(),this.generator.next(),a.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e).value;if(r!=void 0)return this.format(r)}}de.calculate=s;class ve extends ie{constructor(e){super(e);var r=e.SimpleMAOscillator?he:pe,t=e.SimpleMASignal?he:pe,a=new r({period:e.fastPeriod,values:[],format:(e)=>e}),o=new r({period:e.slowPeriod,values:[],format:(e)=>e}),l=new t({period:e.signalPeriod,values:[],format:(e)=>e}),n=this.format;this.result=[],this.generator=function*(){for(var r,t,s,u,i,h,p=0;;){if(p{var r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){var r=this.generator.next(e).value;return r}}ve.calculate=u;class ce extends ie{constructor(e){super(e);let r=e.values,t=e.period,a=this.format;this.generator=function*(e){var r,t,o=yield,l=1,n=0,s=o;for(o=yield;;)t=o-s,t=0{var r=this.generator.next(e);r.value!==void 0&&this.result.push(r.value)})}nextValue(e){return this.generator.next(e).value}}ce.calculate=i;class me extends ie{constructor(e){super(e);let r=e.values,t=e.period,a=this.format;this.generator=function*(e){var r,t,o=yield,l=1,n=0,s=o;for(o=yield;;)t=s-o,t=0{var r=this.generator.next(e);r.value!==void 0&&this.result.push(r.value)})}nextValue(e){return this.generator.next(e).value}}me.calculate=h;class xe extends ie{constructor(e){super(e);var r=e.period,t=e.values,a=new ce({period:r,values:[]}),o=new me({period:r,values:[]});let l=1;this.generator=function*(){for(var e,r,t,n,s=yield;;)e=a.nextValue(s),r=o.nextValue(s),void 0!==e&&void 0!==r&&(0===r?n=100:0===e?n=0:(t=e/r,t=isNaN(t)?0:t,n=parseFloat((100-100/(1+t)).toFixed(2)))),l++,s=yield n}(r),this.generator.next(),this.result=[],t.forEach((e)=>{var r=this.generator.next(e);r.value!==void 0&&this.result.push(r.value)})}nextValue(e){return this.generator.next(e).value}}xe.calculate=p;class we extends ie{constructor(e){super(e);var r=e.period,t=e.values,a=new he({period:r,values:[],format:(e)=>e});this.result=[],this.generator=function*(){var e,t,o=new le(r);e=yield;for(var l;;){if(o.push(e),t=a.nextValue(e),t){let e=0;for(let r of o.iterator())e+=Math.pow(r-t,2);l=te(e/r)}e=yield l}}(),this.generator.next(),t.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return this.format(r.value)}}we.calculate=g;class fe extends ie{constructor(e){super(e);var r,t,a=e.period,o=e.values,l=e.stdDev,n=this.format;this.result=[],r=new he({period:a,values:[],format:(e)=>e}),t=new we({period:a,values:[],format:(e)=>e}),this.generator=function*(){var e,a,o,s;for(a=yield;;){if(o=r.nextValue(a),s=t.nextValue(a),o){let r=n(o),t=n(o+s*l),u=n(o-s*l),i=n((a-u)/(t-u));e={middle:r,upper:t,lower:u,pb:i}}a=yield e}}(),this.generator.next(),o.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){return this.generator.next(e).value}}fe.calculate=d;class Ie extends ie{constructor(e){super(e),this.period=e.period,this.price=e.values;this.generator=function*(e){for(var r=new oe,t=0,a=1,o=yield,l=0;;)a{var r=this.generator.next(e);r.value!=void 0&&this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e).value;if(r!=void 0)return this.format(r)}}Ie.calculate=function(e){ie.reverseInputs(e);var r=new Ie(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r};class _e extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=this.format;if(r.length!=t.length)throw'Inputs(low,high) not of equal size';this.result=[],this.generator=function*(){for(var e,r,t=yield;;){if(r){let o=t.high-r.high,l=r.low-t.low;e=a(l>o&&0{var o=this.generator.next({high:t[a],low:r[a]});o.value!==void 0&&this.result.push(o.value)})}static calculate(e){ie.reverseInputs(e);var r=new _e(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}nextValue(e){return this.generator.next(e).value}}class Pe extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=this.format;if(r.length!=t.length)throw'Inputs(low,high) not of equal size';this.result=[],this.generator=function*(){for(var e,r,t=yield;;){if(r){let o=t.high-r.high,l=r.low-t.low;e=a(o>l&&0{var o=this.generator.next({high:t[a],low:r[a]});o.value!==void 0&&this.result.push(o.value)})}static calculate(e){ie.reverseInputs(e);var r=new Pe(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r}nextValue(e){return this.generator.next(e).value}}class be extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=e.close,o=this.format;if(r.length!=t.length)throw'Inputs(low,high) not of equal size';this.result=[],this.generator=function*(){for(var e,r,t=yield;;)void 0==e&&(e=t.close,t=yield r),r=ee(t.high-t.low,isNaN(re(t.high-e))?0:re(t.high-e),isNaN(re(t.low-e))?0:re(t.low-e)),e=t.close,void 0!=r&&(r=o(r)),t=yield r}(),this.generator.next(),r.forEach((e,o)=>{var l=this.generator.next({high:t[o],low:r[o],close:a[o]});l.value!=void 0&&this.result.push(l.value)})}nextValue(e){return this.generator.next(e).value}}be.calculate=v;class qe extends ue{}class Se extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=e.close,o=e.period,l=this.format,n=new Pe({high:[],low:[]}),s=new _e({high:[],low:[]}),u=new Ie({period:o,values:[],format:(e)=>e}),i=new Ie({period:o,values:[],format:(e)=>e}),h=new Ie({period:o,values:[],format:(e)=>e}),p=new de({period:o,values:[],format:(e)=>e}),g=new be({low:[],high:[],close:[]});if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';this.result=[],qe,this.generator=function*(){var e,r,t,a,o,l,d,v=yield;for(e=0,r=0,t=0;;){let e=g.nextValue(v),r=n.nextValue(v),t=s.nextValue(v);if(e===void 0){v=yield;continue}let c=h.nextValue(e),m=u.nextValue(r),x=i.nextValue(t);if(c!=void 0&&m!=void 0&&x!=void 0){a=100*m/c,o=100*x/c;let e=re(a-o),r=a+o;l=100*(e/r),d=p.nextValue(l)}v=yield{adx:d,pdi:a,mdi:o}}}(),this.generator.next(),r.forEach((e,o)=>{var n=this.generator.next({high:t[o],low:r[o],close:a[o]});n.value!=void 0&&n.value.adx!=void 0&&this.result.push({adx:l(n.value.adx),pdi:l(n.value.pdi),mdi:l(n.value.mdi)})})}nextValue(e){let r=this.generator.next(e).value;if(r!=void 0&&r.adx!=void 0)return{adx:this.format(r.adx),pdi:this.format(r.pdi),mdi:this.format(r.mdi)}}}Se.calculate=c;class Ce extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=e.close,o=e.period,l=this.format;if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';var n=new be({low:[],high:[],close:[]}),s=new de({period:o,values:[],format:(e)=>e});this.result=[],this.generator=function*(){for(var e,r,t=yield;;)r=n.nextValue({low:t.low,high:t.high,close:t.close}),e=void 0===r?void 0:s.nextValue(r),t=yield e}(),this.generator.next(),r.forEach((e,o)=>{var n=this.generator.next({high:t[o],low:r[o],close:a[o]});n.value!==void 0&&this.result.push(l(n.value))})}nextValue(e){return this.generator.next(e).value}}Ce.calculate=m;class Ee extends ie{constructor(e){super(e);var r=e.period,t=e.values;this.result=[],this.generator=function*(){let e=1;for(var t,a=new le(r),o=yield;;)a.push(o),e{var r=this.generator.next(e);r.value==void 0||isNaN(r.value)||this.result.push(this.format(r.value))})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0&&!isNaN(r.value))return this.format(r.value)}}Ee.calculate=x;class Ve extends ie{constructor(e){super(e);let r=e.values,t=e.ROCPer1,a=e.ROCPer2,o=e.ROCPer3,l=e.ROCPer4,n=e.SMAROCPer1,s=e.SMAROCPer2,u=e.SMAROCPer3,i=e.SMAROCPer4,h=e.signalPeriod,p=new Ee({period:t,values:[]}),g=new Ee({period:a,values:[]}),d=new Ee({period:o,values:[]}),v=new Ee({period:l,values:[]}),c=new he({period:n,values:[],format:(e)=>e}),m=new he({period:s,values:[],format:(e)=>e}),x=new he({period:u,values:[],format:(e)=>e}),w=new he({period:i,values:[],format:(e)=>e}),f=new he({period:h,values:[],format:(e)=>e});var I=this.format;this.result=[];let _=ee(t+n,a+s,o+u,l+i);this.generator=function*(){for(let e,r,t,a,o,l,n,s=1,u=yield;;){let i=p.nextValue(u),h=g.nextValue(u),P=d.nextValue(u),b=v.nextValue(u);r=i===void 0?void 0:c.nextValue(i),t=h===void 0?void 0:m.nextValue(h),a=P===void 0?void 0:x.nextValue(P),o=b===void 0?void 0:w.nextValue(b),s<_?s++:e=1*r+2*t+3*a+4*o,l=e===void 0?void 0:f.nextValue(e),n=e===void 0?void 0:{kst:I(e),signal:l?I(l):void 0},u=yield n}}(),this.generator.next(),r.forEach((e)=>{let r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){let r=this.generator.next(e);if(r.value!=void 0)return r.value}}Ve.calculate=w;class He extends ie{constructor(e){super(e);let r=e.high||[],t=e.low||[];this.result=[],this.generator=function*(e,r){for(let t,a,o,l,n=!0,s=e,u=yield;;)t?(o+=s*(a-o),n?(o=J(o,l.low,u.low),t.high>a&&(a=t.high,s=J(s+e,r))):(o=ee(o,l.high,u.high),t.lowo)&&(s=e,o=a,n=!n,a=n?t.high:t.low)):(o=u.low,a=u.high),l=u,t&&(u=t),t=yield o}(e.step,e.max),this.generator.next(),t.forEach((e,a)=>{var o=this.generator.next({high:r[a],low:t[a]});o.value!==void 0&&this.result.push(o.value)})}nextValue(e){let r=this.generator.next(e);if(r.value!==void 0)return r.value}}He.calculate=f;class ke extends ie{constructor(e){super(e);let r=e.low,t=e.high,a=e.close,o=e.period,l=e.signalPeriod,n=this.format;if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';this.result=[],this.generator=function*(){let e,r,t=1,a=new le(o,!0,!1),s=new le(o,!1,!0),u=new he({period:l,values:[],format:(e)=>e});for(var i=yield;;){if(a.push(i.high),s.push(i.low),t{var l=this.generator.next({high:t[o],low:r[o],close:a[o]});l.value!==void 0&&this.result.push(l.value)})}nextValue(e){let r=this.generator.next(e);if(r.value!==void 0)return r.value}}ke.calculate=I;class Te extends ie{constructor(e){super(e);let r=e.low,t=e.high,a=e.close,o=e.period,l=this.format;if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';this.result=[],this.generator=function*(){let e,r,t=1,a=new le(o,!0,!1),n=new le(o,!1,!0);var s=yield;for(let u;;){if(a.push(s.high),n.push(s.low),t{var l=this.generator.next({high:t[o],low:r[o],close:a[o]});l.value!==void 0&&this.result.push(l.value)})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return this.format(r.value)}}Te.calculate=_;class De extends ie{constructor(e){super(e);var r=e.high,t=e.low,a=e.close,o=e.volume;if(t.length!==r.length||r.length!==a.length||r.length!==o.length)throw'Inputs(low,high, close, volumes) not of equal size';this.result=[],this.generator=function*(){var e,r=0;for(e=yield;;){let t=(e.close-e.low-(e.high-e.close))/(e.high-e.low);t=isNaN(t)?1:t;let a=t*e.volume;r+=a,e=yield Math.round(r)}}(),this.generator.next(),r.forEach((e,r)=>{var l={high:e,low:t[r],close:a[r],volume:o[r]},n=this.generator.next(l);n.value!=void 0&&this.result.push(n.value)})}nextValue(e){return this.generator.next(e).value}}De.calculate=P;class Ae extends ie{constructor(e){super(e);var r=e.close,t=e.volume;this.result=[],this.generator=function*(){var e,r,t=0;for(e=yield,e.close&&'number'==typeof e.close&&(r=e.close,e=yield);;)r{let o={close:r[a],volume:t[a]},l=this.generator.next(o);l.value!=void 0&&this.result.push(l.value)})}nextValue(e){return this.generator.next(e).value}}Ae.calculate=b;class Be extends ie{constructor(e){super(e);let r=e.values,t=e.period,a=this.format,o=new pe({period:t,values:[],format:(e)=>e}),l=new pe({period:t,values:[],format:(e)=>e}),n=new pe({period:t,values:[],format:(e)=>e}),s=new Ee({period:1,values:[],format:(e)=>e});this.result=[],this.generator=function*(){for(let e=yield;;){let r=o.nextValue(e),t=r?l.nextValue(r):void 0,u=t?n.nextValue(t):void 0,i=u?s.nextValue(u):void 0;e=yield i?a(i):void 0}}(),this.generator.next(),r.forEach((e)=>{let r=this.generator.next(e);r.value!==void 0&&this.result.push(r.value)})}nextValue(e){let r=this.generator.next(e);if(r.value!==void 0)return r.value}}Be.calculate=q;class ze extends ie{constructor(e){super(e);var r=e.close,t=e.volume,a=e.period||1;if(t.length!==r.length)throw'Inputs(volume, close) not of equal size';let o=new pe({values:[],period:a});this.result=[],this.generator=function*(){var e=yield,r=yield;for(let t;;)t=(r.close-e.close)*r.volume,e=r,r=yield o.nextValue(t)}(),this.generator.next(),t.forEach((e,a)=>{var o=this.generator.next({close:r[a],volume:t[a]});o.value!=void 0&&this.result.push(o.value)})}nextValue(e){let r=this.generator.next(e).value;if(r!=void 0)return r}}ze.calculate=S;class Le extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=e.close,o=e.period,l=this.format;var n=new le(o),s=new he({period:o,values:[],format:(e)=>e});if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';this.result=[],this.generator=function*(){for(var e=yield;;){let r=(e.high+e.low+e.close)/3;n.push(r);let t,a=s.nextValue(r),o=null,l=0;if(a!=void 0){for(let e of n.iterator())l+=re(e-a);o=l/20,t=(r-a)/(.015*o)}e=yield t}}(),this.generator.next(),r.forEach((e,o)=>{var l=this.generator.next({high:t[o],low:r[o],close:a[o]});l.value!=void 0&&this.result.push(l.value)})}nextValue(e){let r=this.generator.next(e).value;if(r!=void 0)return r}}Le.calculate=C;class Me extends ie{constructor(e){super(e);var r=e.high,t=e.low,a=e.fastPeriod,o=e.slowPeriod,l=new he({values:[],period:o}),n=new he({values:[],period:a});this.result=[],this.generator=function*(){var e,r,t,a,o;for(r=yield;;)t=(r.high+r.low)/2,a=l.nextValue(t),o=n.nextValue(t),void 0!==a&&void 0!==o&&(e=o-a),r=yield e}(),this.generator.next(),r.forEach((e,r)=>{var a={high:e,low:t[r]},o=this.generator.next(a);o.value!=void 0&&this.result.push(this.format(o.value))})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return this.format(r.value)}}Me.calculate=E;class je extends ie{constructor(e){super(e);var r=e.low,t=e.high,a=e.close,o=e.volume,l=this.format;if(r.length!==t.length||t.length!==a.length)throw'Inputs(low,high, close) not of equal size';this.result=[],this.generator=function*(){var e=yield;for(let r=0,t=0;;){let a=(e.high+e.low+e.close)/3,o=e.volume*a;r+=o,t+=e.volume,e=yield r/t}}(),this.generator.next(),r.forEach((e,l)=>{var n=this.generator.next({high:t[l],low:r[l],close:a[l],volume:o[l]});n.value!=void 0&&this.result.push(n.value)})}nextValue(e){let r=this.generator.next(e).value;if(r!=void 0)return r}}je.calculate=V;class Re extends ie{constructor(e){super(e);var r=e.high,t=e.low,a=e.close,o=e.open,l=e.volume,n=e.noOfBars;if(t.length!==r.length||r.length!==a.length||r.length!==l.length)throw'Inputs(low,high, close, volumes) not of equal size';this.result=[];var s=ee(...r,...t,...a,...o),u=J(...r,...t,...a,...o),i=u;for(let h=0;hv?g+=c:p+=c)}this.result.push({rangeStart:e,rangeEnd:h,bullishVolume:p,bearishVolume:g,totalVolume:d})}}nextValue(){throw'Next value not supported for volume profile'}}Re.calculate=k;class ye extends ie{constructor(e){super(e),this.result=[],this.generator=function*(){for(let e=yield;;)e=yield(e.high+e.low+e.close)/3}(),this.generator.next(),e.low.forEach((r,t)=>{var a=this.generator.next({high:e.high[t],low:e.low[t],close:e.close[t]});this.result.push(a.value)})}nextValue(e){var r=this.generator.next(e).value;return r}}ye.calculate=function(e){ie.reverseInputs(e);var r=new ye(e).result;return e.reversedInput&&r.reverse(),ie.reverseInputs(e),r};class Oe extends ie{constructor(e){super(e);var r=e.high,t=e.low,a=e.close,o=e.volume,l=e.period,n=new ye({low:[],high:[],close:[]}),s=new le(l,!1,!1,!0),u=new le(l,!1,!1,!0);if(t.length!==r.length||r.length!==a.length||r.length!==o.length)throw'Inputs(low,high, close, volumes) not of equal size';this.result=[],this.generator=function*(){var e,r,t,a,o,i,h=0;let p=null,g=null;for(r=yield,t=r.close,r=yield;;){var{high:d,low:v,close:c,volume:m}=r,x=0,w=0;p=n.nextValue({high:d,low:v,close:c}),h=p*m,null!=p&&null!=g&&(p>g?x=h:w=h,s.push(x),u.push(w),a=s.periodSum,i=u.periodSum,s.totalPushed>=l&&s.totalPushed>=l&&(o=a/i,e=100-100/(1+o))),g=p,r=yield e}}(),this.generator.next(),r.forEach((e,r)=>{var l={high:e,low:t[r],close:a[r],volume:o[r]},n=this.generator.next(l);n.value!=void 0&&this.result.push(parseFloat(n.value.toFixed(2)))})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return parseFloat(r.value.toFixed(2))}}Oe.calculate=T;class Fe extends ie{constructor(e){super(e);let r=e.values,t=e.rsiPeriod,a=e.stochasticPeriod,o=e.kPeriod,l=e.dPeriod,n=this.format;this.result=[],this.generator=function*(){let e,r,n,s,u=new xe({period:t,values:[]}),i=new ke({period:a,high:[],low:[],close:[],signalPeriod:o}),h=new he({period:l,values:[],format:(e)=>e});for(var p=yield;;){if(e=u.nextValue(p),void 0!==e){var g={high:e,low:e,close:e};r=i.nextValue(g),void 0!==r&&void 0!==r.d&&(n=h.nextValue(r.d),void 0!==n&&(s={stochRSI:r.k,k:r.d,d:n}))}p=yield s}}(),this.generator.next(),r.forEach((e)=>{var r=this.generator.next(e);r.value!==void 0&&this.result.push(r.value)})}nextValue(e){let r=this.generator.next(e);if(r.value!==void 0)return r.value}}Fe.calculate=D;class Ue extends ie{constructor(e){super(e);var r=e.values,t=e.period;this.result=[];var a=new le(t,!0,!1,!1);this.generator=function*(){var e,r;for(e=yield;;)a.push(e),a.totalPushed>=t&&(r=a.periodHigh),e=yield r}(),this.generator.next(),r.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return r.value}}Ue.calculate=A;class We extends ie{constructor(e){super(e);var r=e.values,t=e.period;this.result=[];var a=new le(t,!1,!0,!1);this.generator=function*(){var e,r;for(e=yield;;)a.push(e),a.totalPushed>=t&&(r=a.periodLow),e=yield r}(),this.generator.next(),r.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return r.value}}We.calculate=B;class Ge extends ie{constructor(e){super(e);var r=e.values,t=e.period;this.result=[];var a=new le(t,!1,!1,!0);this.generator=function*(){var e,r;for(e=yield;;)a.push(e),a.totalPushed>=t&&(r=a.periodSum),e=yield r}(),this.generator.next(),r.forEach((e)=>{var r=this.generator.next(e);r.value!=void 0&&this.result.push(r.value)})}nextValue(e){var r=this.generator.next(e);if(r.value!=void 0)return r.value}}Ge.calculate=z;class Ne extends ie{constructor(e){super(e);this.format;let r=e.useATR,t=e.brickSize||0;if(r){let r=m(Object.assign({},e));t=r[r.length-1]}if(this.result=new ne,0===t)return void console.error('Not enough data to calculate brickSize for renko when using ATR');let a=0,o=0,l=Infinity,n=0,s=0,u=0;this.generator=function*(){for(let e=yield;;){if(0==a){a=e.close,o=e.high,l=e.low,n=e.close,s=e.volume,u=e.timestamp,e=yield;continue}let r=re(e.close-n),i=re(e.close-a);if(r>=t&&i>=t){let u=r>i?a:n,h={open:u,high:o>e.high?o:e.high,low:le.close?u-t:u+t,volume:s+e.volume,timestamp:e.timestamp};a=h.open,o=h.close,l=h.close,n=h.close,s=0,e=yield h}else o=o>e.high?o:e.high,l=l{var a=this.generator.next({open:e.open[t],high:e.high[t],low:e.low[t],close:e.close[t],volume:e.volume[t],timestamp:e.timestamp[t]});a.value&&(this.result.open.push(a.value.open),this.result.high.push(a.value.high),this.result.low.push(a.value.low),this.result.close.push(a.value.close),this.result.volume.push(a.value.volume),this.result.timestamp.push(a.value.timestamp))})}nextValue(){return console.error('Cannot calculate next value on Renko, Every value has to be recomputed for every change, use calcualte method'),null}}Ne.calculate=L;class Xe extends ie{constructor(e){super(e);this.format;this.result=new ne;let r=null,t=0,a=Infinity,o=0,l=0,n=0;this.generator=function*(){for(let e=yield,s=null;;){if(null==r)r=(e.close+e.open)/2,t=e.high,a=e.low,o=(e.close+e.open+e.high+e.low)/4,l=e.volume||0,n=e.timestamp||0,s={open:r,high:t,low:a,close:o,volume:e.volume||0,timestamp:e.timestamp||0};else{let l=(e.close+e.open+e.high+e.low)/4,n=(r+o)/2,u=ee(n,l,e.high),i=J(e.low,n,l);s={close:l,open:n,high:u,low:i,volume:e.volume||0,timestamp:e.timestamp||0},o=l,r=n,t=u,a=i}e=yield s}}(),this.generator.next(),e.low.forEach((r,t)=>{var a=this.generator.next({open:e.open[t],high:e.high[t],low:e.low[t],close:e.close[t],volume:e.volume?e.volume[t]:e.volume,timestamp:e.timestamp?e.timestamp[t]:e.timestamp});a.value&&(this.result.open.push(a.value.open),this.result.high.push(a.value.high),this.result.low.push(a.value.low),this.result.close.push(a.value.close),this.result.volume.push(a.value.volume),this.result.timestamp.push(a.value.timestamp))})}nextValue(e){var r=this.generator.next(e).value;return r}}Xe.calculate=M;class Ke{constructor(){}approximateEqual(e,r){let t=1*parseFloat(re(e-r).toPrecision(4)),a=1*parseFloat((1e-3*e).toPrecision(4));return t<=a}logic(){throw'this has to be implemented'}getAllPatternIndex(e){if(e.close.lengthr.call(this,e)?t:void 0).filter((e)=>e)}hasPattern(e){if(e.close.lengtha<=e.close.length-r);return t}}class Qe extends Ke{constructor(){super(),this.name='MorningStar',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2];return tu&&o>s&&ss&&n(r+t)/2}}class Ye extends Ke{constructor(){super(),this.name='BullishEngulfingPattern',this.requiredCount=2}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1];return tl&&t>l&&rl&&tu&&a>s}}class $e extends Ke{constructor(){super(),this.requiredCount=2,this.name='BullishHaramiCross'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=this.approximateEqual(l,n);return r>l&&tu&&a>s&&i}}class Je extends Ke{constructor(){super(),this.name='Doji',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=this.approximateEqual(r,t),n=l&&this.approximateEqual(r,a),s=l&&this.approximateEqual(t,o);return l&&n==s}}class er extends Ke{constructor(){super(),this.name='MorningDojiStar',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2],d=new Je().hasPattern({open:[l],close:[n],high:[s],low:[u]});return ts&&n(r+t)/2}}class rr extends Ke{constructor(){super(),this.requiredCount=3,this.name='DownsideTasukiGap'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2];return ti&&si&&nl&&hl&&n>(r+t)/2&&n>l}}class or extends Ke{constructor(){super(),this.name='ThreeWhiteSoldiers',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2];return s>a&&p>s&&rl&&li&&ir;return l=l&&this.approximateEqual(t,a),l=l&&t-r<=2*(r-o),l}}class nr extends Ke{constructor(){super(),this.name='BullishInvertedHammerStick',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=t>r;return l=l&&this.approximateEqual(r,o),l=l&&t-r<=2*(a-t),l}}class sr extends Ke{constructor(){super(),this.name='BearishHammerStick',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=r>t;return l=l&&this.approximateEqual(r,a),l=l&&r-t<=2*(t-o),l}}class ur extends Ke{constructor(){super(),this.name='BearishInvertedHammerStick',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=r>t;return l=l&&this.approximateEqual(t,o),l=l&&r-t<=2*(a-r),l}}class ir extends Ke{constructor(){super(),this.name='HammerPattern',this.requiredCount=5}logic(e){let r=this.downwardTrend(e);return r=r&&this.includesHammer(e),r=r&&this.hasConfirmation(e),r}downwardTrend(e,r=!0){let t=r?3:4,a=i({values:e.close.slice(0,t),period:t-1}),o=h({values:e.close.slice(0,t),period:t-1});return o>a}includesHammer(e,r=!0){let t=r?3:4,a=r?4:void 0,o={open:e.open.slice(t,a),close:e.close.slice(t,a),low:e.low.slice(t,a),high:e.high.slice(t,a)},l=y(o);return l=l||O(o),l=l||j(o),l=l||R(o),l}hasConfirmation(e){let r={open:e.open[3],close:e.close[3],low:e.low[3],high:e.high[3]},t={open:e.open[4],close:e.close[4],low:e.low[4],high:e.high[4]},a=t.openr}}let gr=[new Ye,new rr,new Ze,new $e,new er,new Qe,new tr,new ar,new or,new lr,new nr,new ir,new hr,new pr];class dr extends Ke{constructor(){super(),this.name='Bullish Candlesticks'}hasPattern(e){return gr.reduce(function(r,t){let a=t.hasPattern(e);return r||a},!1)}}class vr extends Ke{constructor(){super(),this.name='BearishEngulfingPattern',this.requiredCount=2}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1];return t>r&&rn}}class cr extends Ke{constructor(){super(),this.requiredCount=2,this.name='BearishHarami'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1];return rl&&t>n&&rs}}class mr extends Ke{constructor(){super(),this.requiredCount=2,this.name='BearishHaramiCross'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=this.approximateEqual(l,n);return rl&&t>n&&rs&&i}}class xr extends Ke{constructor(){super(),this.name='EveningDojiStar',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2],d=new Je().hasPattern({open:[l],close:[n],high:[s],low:[u]});return t>r&&d&&s>a&&u>a&&ii&&i>h&&h<(r+t)/2}}class wr extends Ke{constructor(){super(),this.name='EveningStar',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2];return t>r&&aa&&u>a&&ii&&i>h&&h<(r+t)/2}}class fr extends Ke{constructor(){super(),this.name='BearishMarubozu',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=this.approximateEqual(r,a)&&this.approximateEqual(o,t)&&r>t&&r>o;return l}}class Ir extends Ke{constructor(){super(),this.name='ThreeBlackCrows',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2];return o>u&&u>g&&r>t&&l>n&&i>h&&r>l&&l>t&&l>i&&i>n}}class _r extends Ke{constructor(){super(),this.name='HangingMan',this.requiredCount=5}logic(e){let r=this.upwardTrend(e);return r=r&&this.includesHammer(e),r=r&&this.hasConfirmation(e),r}upwardTrend(e,r=!0){let t=r?3:4,a=i({values:e.close.slice(0,t),period:t-1}),o=h({values:e.close.slice(0,t),period:t-1});return a>o}includesHammer(e,r=!0){let t=r?3:4,a=r?4:void 0,o={open:e.open.slice(t,a),close:e.close.slice(t,a),low:e.low.slice(t,a),high:e.high.slice(t,a)},l=y(o);return l=l||j(o),l}hasConfirmation(e){let r={open:e.open[3],close:e.close[3],low:e.low[3],high:e.high[3]},t={open:e.open[4],close:e.close[4],low:e.low[4],high:e.high[4]},a=t.open>t.close;return a&&r.close>t.close}}class Pr extends _r{constructor(){super(),this.name='HangingManUnconfirmed'}logic(e){let r=this.upwardTrend(e,!1);return r=r&&this.includesHammer(e,!1),r}}class br extends Ke{constructor(){super(),this.name='ShootingStar',this.requiredCount=5}logic(e){let r=this.upwardTrend(e);return r=r&&this.includesHammer(e),r=r&&this.hasConfirmation(e),r}upwardTrend(e,r=!0){let t=r?3:4,a=i({values:e.close.slice(0,t),period:t-1}),o=h({values:e.close.slice(0,t),period:t-1});return a>o}includesHammer(e,r=!0){let t=r?3:4,a=r?4:void 0,o={open:e.open.slice(t,a),close:e.close.slice(t,a),low:e.low.slice(t,a),high:e.high.slice(t,a)},l=O(o);return l=l||R(o),l}hasConfirmation(e){let r={open:e.open[3],close:e.close[3],low:e.low[3],high:e.high[3]},t={open:e.open[4],close:e.close[4],low:e.low[4],high:e.high[4]},a=t.open>t.close;return a&&r.close>t.close}}class qr extends br{constructor(){super(),this.name='ShootingStarUnconfirmed'}logic(e){let r=this.upwardTrend(e,!1);return r=r&&this.includesHammer(e,!1),r}}class Sr extends Ke{constructor(){super(),this.name='TweezerTop',this.requiredCount=5}logic(e){return this.upwardTrend(e)&&e.high[3]==e.high[4]}upwardTrend(e){let r=i({values:e.close.slice(0,3),period:2}),t=h({values:e.close.slice(0,3),period:2});return r>t}}let Cr=[new vr,new cr,new mr,new xr,new wr,new fr,new Ir,new sr,new ur,new _r,new Pr,new br,new qr,new Sr];class Er extends Ke{constructor(){super(),this.name='Bearish Candlesticks'}hasPattern(e){return Cr.reduce(function(r,t){return r||t.hasPattern(e)},!1)}}class Vr extends Ke{constructor(){super(),this.name='AbandonedBaby',this.requiredCount=3}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=e.open[1],n=e.close[1],s=e.high[1],u=e.low[1],i=e.open[2],h=e.close[2],p=e.high[2],g=e.low[2],d=new Je().hasPattern({open:[l],close:[n],high:[s],low:[u]});return ts&&h>i&&pr&&na&&n<(t+r)/2&&n>r}}class kr extends Ke{constructor(){super(),this.requiredCount=1,this.name='DragonFlyDoji'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=this.approximateEqual(r,t),n=l&&this.approximateEqual(r,a),s=l&&this.approximateEqual(t,o);return l&&n&&!s}}class Tr extends Ke{constructor(){super(),this.requiredCount=1,this.name='GraveStoneDoji'}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=this.approximateEqual(r,t),n=l&&this.approximateEqual(r,a),s=l&&this.approximateEqual(t,o);return l&&s&&!n}}class Dr extends Ke{constructor(){super(),this.name='BullishSpinningTop',this.requiredCount=1}logic(e){let r=e.open[0],t=e.close[0],a=e.high[0],o=e.low[0],l=re(t-r),n=re(a-t),s=re(r-o);return l {\n var result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n if (result != undefined)\n return this.format(result);\n }\n ;\n}\nSMA.calculate = sma;\nexport function sma(input) {\n Indicator.reverseInputs(input);\n var result = new SMA(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n//STEP 6. Run the tests\n","import { Indicator } from '../indicator/indicator';\nimport { SMA } from './SMA';\nexport class EMA extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n var exponent = (2 / (period + 1));\n var sma;\n this.result = [];\n sma = new SMA({ period: period, values: [] });\n var genFn = (function* () {\n var tick = yield;\n var prevEma;\n while (true) {\n if (prevEma !== undefined && tick !== undefined) {\n prevEma = ((tick - prevEma) * exponent) + prevEma;\n tick = yield prevEma;\n }\n else {\n tick = yield;\n prevEma = sma.nextValue(tick);\n if (prevEma)\n tick = yield prevEma;\n }\n }\n });\n this.generator = genFn();\n this.generator.next();\n this.generator.next();\n priceArray.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n if (result != undefined)\n return this.format(result);\n }\n ;\n}\nEMA.calculate = ema;\nexport function ema(input) {\n Indicator.reverseInputs(input);\n var result = new EMA(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n","\"use strict\";\nimport { Indicator } from '../indicator/indicator';\nimport { LinkedList } from '../Utils/LinkedList';\nexport class WMA extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n this.result = [];\n this.generator = (function* () {\n let data = new LinkedList();\n let denominator = period * (period + 1) / 2;\n while (true) {\n if ((data.length) < period) {\n data.push(yield);\n }\n else {\n data.resetCursor();\n let result = 0;\n for (let i = 1; i <= period; i++) {\n result = result + (data.next() * i / (denominator));\n }\n var next = yield result;\n data.shift();\n data.push(next);\n }\n }\n })();\n this.generator.next();\n priceArray.forEach((tick, index) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n //STEP 5. REMOVE GET RESULT FUNCTION\n nextValue(price) {\n var result = this.generator.next(price).value;\n if (result != undefined)\n return this.format(result);\n }\n ;\n}\nWMA.calculate = wma;\n;\nexport function wma(input) {\n Indicator.reverseInputs(input);\n var result = new WMA(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n","import { Indicator } from '../indicator/indicator';\nimport { SMA } from './SMA';\nexport class WEMA extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n var exponent = 1 / period;\n var sma;\n this.result = [];\n sma = new SMA({ period: period, values: [] });\n var genFn = (function* () {\n var tick = yield;\n var prevEma;\n while (true) {\n if (prevEma !== undefined && tick !== undefined) {\n prevEma = ((tick - prevEma) * exponent) + prevEma;\n tick = yield prevEma;\n }\n else {\n tick = yield;\n prevEma = sma.nextValue(tick);\n if (prevEma !== undefined)\n tick = yield prevEma;\n }\n }\n });\n this.generator = genFn();\n this.generator.next();\n this.generator.next();\n priceArray.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n if (result != undefined)\n return this.format(result);\n }\n ;\n}\nWEMA.calculate = wema;\nexport function wema(input) {\n Indicator.reverseInputs(input);\n var result = new WEMA(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n","/**\n * Created by AAravindan on 5/4/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { SMA } from './SMA';\nimport { EMA } from './EMA';\nexport class MACDInput extends IndicatorInput {\n constructor(values) {\n super();\n this.values = values;\n this.SimpleMAOscillator = true;\n this.SimpleMASignal = true;\n }\n}\nexport class MACDOutput {\n}\nexport class MACD extends Indicator {\n constructor(input) {\n super(input);\n var oscillatorMAtype = input.SimpleMAOscillator ? SMA : EMA;\n var signalMAtype = input.SimpleMASignal ? SMA : EMA;\n var fastMAProducer = new oscillatorMAtype({ period: input.fastPeriod, values: [], format: (v) => { return v; } });\n var slowMAProducer = new oscillatorMAtype({ period: input.slowPeriod, values: [], format: (v) => { return v; } });\n var signalMAProducer = new signalMAtype({ period: input.signalPeriod, values: [], format: (v) => { return v; } });\n var format = this.format;\n this.result = [];\n this.generator = (function* () {\n var index = 0;\n var tick;\n var MACD, signal, histogram, fast, slow;\n while (true) {\n if (index < input.slowPeriod) {\n tick = yield;\n fast = fastMAProducer.nextValue(tick);\n slow = slowMAProducer.nextValue(tick);\n index++;\n continue;\n }\n if (fast && slow) {\n MACD = fast - slow;\n signal = signalMAProducer.nextValue(MACD);\n }\n histogram = MACD - signal;\n tick = yield ({\n //fast : fast,\n //slow : slow,\n MACD: format(MACD),\n signal: signal ? format(signal) : undefined,\n histogram: isNaN(histogram) ? undefined : format(histogram)\n });\n fast = fastMAProducer.nextValue(tick);\n slow = slowMAProducer.nextValue(tick);\n }\n })();\n this.generator.next();\n input.values.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n return result;\n }\n ;\n}\nMACD.calculate = macd;\nexport function macd(input) {\n Indicator.reverseInputs(input);\n var result = new MACD(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class AvgGainInput extends IndicatorInput {\n}\nexport class AverageGain extends Indicator {\n constructor(input) {\n super(input);\n let values = input.values;\n let period = input.period;\n let format = this.format;\n this.generator = (function* (period) {\n var currentValue = yield;\n var counter = 1;\n var gainSum = 0;\n var avgGain;\n var gain;\n var lastValue = currentValue;\n currentValue = yield;\n while (true) {\n gain = currentValue - lastValue;\n gain = gain > 0 ? gain : 0;\n if (gain > 0) {\n gainSum = gainSum + gain;\n }\n if (counter < period) {\n counter++;\n }\n else if (avgGain === undefined) {\n avgGain = gainSum / period;\n }\n else {\n avgGain = ((avgGain * (period - 1)) + gain) / period;\n }\n lastValue = currentValue;\n avgGain = (avgGain !== undefined) ? format(avgGain) : undefined;\n currentValue = yield avgGain;\n }\n })(period);\n this.generator.next();\n this.result = [];\n values.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nAverageGain.calculate = averagegain;\nexport function averagegain(input) {\n Indicator.reverseInputs(input);\n var result = new AverageGain(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class AvgLossInput extends IndicatorInput {\n}\nexport class AverageLoss extends Indicator {\n constructor(input) {\n super(input);\n let values = input.values;\n let period = input.period;\n let format = this.format;\n this.generator = (function* (period) {\n var currentValue = yield;\n var counter = 1;\n var lossSum = 0;\n var avgLoss;\n var loss;\n var lastValue = currentValue;\n currentValue = yield;\n while (true) {\n loss = lastValue - currentValue;\n loss = loss > 0 ? loss : 0;\n if (loss > 0) {\n lossSum = lossSum + loss;\n }\n if (counter < period) {\n counter++;\n }\n else if (avgLoss === undefined) {\n avgLoss = lossSum / period;\n }\n else {\n avgLoss = ((avgLoss * (period - 1)) + loss) / period;\n }\n lastValue = currentValue;\n avgLoss = (avgLoss !== undefined) ? format(avgLoss) : undefined;\n currentValue = yield avgLoss;\n }\n })(period);\n this.generator.next();\n this.result = [];\n values.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nAverageLoss.calculate = averageloss;\nexport function averageloss(input) {\n Indicator.reverseInputs(input);\n var result = new AverageLoss(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","/**\n * Created by AAravindan on 5/5/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { AverageGain } from '../Utils/AverageGain';\nimport { AverageLoss } from '../Utils/AverageLoss';\nexport class RSIInput extends IndicatorInput {\n}\nexport class RSI extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var values = input.values;\n var GainProvider = new AverageGain({ period: period, values: [] });\n var LossProvider = new AverageLoss({ period: period, values: [] });\n let count = 1;\n this.generator = (function* (period) {\n var current = yield;\n var lastAvgGain, lastAvgLoss, RS, currentRSI;\n while (true) {\n lastAvgGain = GainProvider.nextValue(current);\n lastAvgLoss = LossProvider.nextValue(current);\n if ((lastAvgGain !== undefined) && (lastAvgLoss !== undefined)) {\n if (lastAvgLoss === 0) {\n currentRSI = 100;\n }\n else if (lastAvgGain === 0) {\n currentRSI = 0;\n }\n else {\n RS = lastAvgGain / lastAvgLoss;\n RS = isNaN(RS) ? 0 : RS;\n currentRSI = parseFloat((100 - (100 / (1 + RS))).toFixed(2));\n }\n }\n count++;\n current = yield currentRSI;\n }\n })(period);\n this.generator.next();\n this.result = [];\n values.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nRSI.calculate = rsi;\nexport function rsi(input) {\n Indicator.reverseInputs(input);\n var result = new RSI(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { IndicatorInput, Indicator } from '../indicator/indicator';\nimport { SMA } from '../moving_averages/SMA';\nimport LinkedList from '../Utils/FixedSizeLinkedList';\n/**\n * Created by AAravindan on 5/7/16.\n */\n\"use strict\";\nexport class SDInput extends IndicatorInput {\n}\n;\nexport class SD extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n var sma = new SMA({ period: period, values: [], format: (v) => { return v; } });\n this.result = [];\n this.generator = (function* () {\n var tick;\n var mean;\n var currentSet = new LinkedList(period);\n ;\n tick = yield;\n var sd;\n while (true) {\n currentSet.push(tick);\n mean = sma.nextValue(tick);\n if (mean) {\n let sum = 0;\n for (let x of currentSet.iterator()) {\n sum = sum + (Math.pow((x - mean), 2));\n }\n sd = Math.sqrt(sum / (period));\n }\n tick = yield sd;\n }\n })();\n this.generator.next();\n priceArray.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var nextResult = this.generator.next(price);\n if (nextResult.value != undefined)\n return this.format(nextResult.value);\n }\n ;\n}\nSD.calculate = sd;\nexport function sd(input) {\n Indicator.reverseInputs(input);\n var result = new SD(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","\"use strict\";\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { SMA } from '../moving_averages/SMA';\nimport { SD } from '../Utils/SD';\nexport class BollingerBandsInput extends IndicatorInput {\n}\n;\nexport class BollingerBandsOutput extends IndicatorInput {\n}\n;\nexport class BollingerBands extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n var stdDev = input.stdDev;\n var format = this.format;\n var sma, sd;\n this.result = [];\n sma = new SMA({ period: period, values: [], format: (v) => { return v; } });\n sd = new SD({ period: period, values: [], format: (v) => { return v; } });\n this.generator = (function* () {\n var result;\n var tick;\n var calcSMA;\n var calcsd;\n tick = yield;\n while (true) {\n calcSMA = sma.nextValue(tick);\n calcsd = sd.nextValue(tick);\n if (calcSMA) {\n let middle = format(calcSMA);\n let upper = format(calcSMA + (calcsd * stdDev));\n let lower = format(calcSMA - (calcsd * stdDev));\n let pb = format((tick - lower) / (upper - lower));\n result = {\n middle: middle,\n upper: upper,\n lower: lower,\n pb: pb\n };\n }\n tick = yield result;\n }\n })();\n this.generator.next();\n priceArray.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nBollingerBands.calculate = bollingerbands;\nexport function bollingerbands(input) {\n Indicator.reverseInputs(input);\n var result = new BollingerBands(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator } from '../indicator/indicator';\nimport { LinkedList } from '../Utils/LinkedList';\n//STEP3. Add class based syntax with export\nexport class WilderSmoothing extends Indicator {\n constructor(input) {\n super(input);\n this.period = input.period;\n this.price = input.values;\n var genFn = (function* (period) {\n var list = new LinkedList();\n var sum = 0;\n var counter = 1;\n var current = yield;\n var result = 0;\n while (true) {\n if (counter < period) {\n counter++;\n sum = sum + current;\n result = undefined;\n }\n else if (counter == period) {\n counter++;\n sum = sum + current;\n result = sum;\n }\n else {\n result = result - (result / period) + current;\n }\n current = yield result;\n }\n });\n this.generator = genFn(this.period);\n this.generator.next();\n this.result = [];\n this.price.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n if (result != undefined)\n return this.format(result);\n }\n ;\n}\nWilderSmoothing.calculate = wildersmoothing;\nexport function wildersmoothing(input) {\n Indicator.reverseInputs(input);\n var result = new WilderSmoothing(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n//STEP 6. Run the tests\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\n/**\n * Created by AAravindan on 5/8/16.\n */\n/**\n * Created by AAravindan on 5/8/16.\n */\n\"use strict\";\nexport class TrueRangeInput extends IndicatorInput {\n}\n;\nexport class TrueRange extends Indicator {\n constructor(input) {\n super(input);\n var lows = input.low;\n var highs = input.high;\n var closes = input.close;\n var format = this.format;\n if (lows.length != highs.length) {\n throw ('Inputs(low,high) not of equal size');\n }\n this.result = [];\n this.generator = (function* () {\n var current = yield;\n var previousClose, result;\n while (true) {\n if (previousClose === undefined) {\n previousClose = current.close;\n current = yield result;\n }\n result = Math.max(current.high - current.low, isNaN(Math.abs(current.high - previousClose)) ? 0 : Math.abs(current.high - previousClose), isNaN(Math.abs(current.low - previousClose)) ? 0 : Math.abs(current.low - previousClose));\n previousClose = current.close;\n if (result != undefined) {\n result = format(result);\n }\n current = yield result;\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nTrueRange.calculate = truerange;\nexport function truerange(input) {\n Indicator.reverseInputs(input);\n var result = new TrueRange(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { WilderSmoothing } from '../moving_averages/WilderSmoothing';\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { MDM } from './MinusDM';\nimport { PDM } from './PlusDM';\nimport { TrueRange } from './TrueRange';\nimport { WEMA } from '../moving_averages/WEMA';\nexport class ADXInput extends IndicatorInput {\n}\n;\nexport class ADXOutput extends IndicatorInput {\n}\n;\nexport class ADX extends Indicator {\n constructor(input) {\n super(input);\n var lows = input.low;\n var highs = input.high;\n var closes = input.close;\n var period = input.period;\n var format = this.format;\n var plusDM = new PDM({\n high: [],\n low: []\n });\n var minusDM = new MDM({\n high: [],\n low: []\n });\n var emaPDM = new WilderSmoothing({ period: period, values: [], format: (v) => { return v; } });\n var emaMDM = new WilderSmoothing({ period: period, values: [], format: (v) => { return v; } });\n var emaTR = new WilderSmoothing({ period: period, values: [], format: (v) => { return v; } });\n var emaDX = new WEMA({ period: period, values: [], format: (v) => { return v; } });\n var tr = new TrueRange({\n low: [],\n high: [],\n close: [],\n });\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n this.result = [];\n ADXOutput;\n this.generator = (function* () {\n var tick = yield;\n var index = 0;\n var lastATR, lastAPDM, lastAMDM, lastPDI, lastMDI, lastDX, smoothedDX;\n lastATR = 0;\n lastAPDM = 0;\n lastAMDM = 0;\n while (true) {\n let calcTr = tr.nextValue(tick);\n let calcPDM = plusDM.nextValue(tick);\n let calcMDM = minusDM.nextValue(tick);\n if (calcTr === undefined) {\n tick = yield;\n continue;\n }\n let lastATR = emaTR.nextValue(calcTr);\n let lastAPDM = emaPDM.nextValue(calcPDM);\n let lastAMDM = emaMDM.nextValue(calcMDM);\n if ((lastATR != undefined) && (lastAPDM != undefined) && (lastAMDM != undefined)) {\n lastPDI = (lastAPDM) * 100 / lastATR;\n lastMDI = (lastAMDM) * 100 / lastATR;\n let diDiff = Math.abs(lastPDI - lastMDI);\n let diSum = (lastPDI + lastMDI);\n lastDX = (diDiff / diSum) * 100;\n smoothedDX = emaDX.nextValue(lastDX);\n // console.log(tick.high.toFixed(2), tick.low.toFixed(2), tick.close.toFixed(2) , calcTr.toFixed(2), calcPDM.toFixed(2), calcMDM.toFixed(2), lastATR.toFixed(2), lastAPDM.toFixed(2), lastAMDM.toFixed(2), lastPDI.toFixed(2), lastMDI.toFixed(2), diDiff.toFixed(2), diSum.toFixed(2), lastDX.toFixed(2));\n }\n tick = yield { adx: smoothedDX, pdi: lastPDI, mdi: lastMDI };\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value != undefined && result.value.adx != undefined) {\n this.result.push({ adx: format(result.value.adx), pdi: format(result.value.pdi), mdi: format(result.value.mdi) });\n }\n });\n }\n ;\n ;\n nextValue(price) {\n let result = this.generator.next(price).value;\n if (result != undefined && result.adx != undefined) {\n return { adx: this.format(result.adx), pdi: this.format(result.pdi), mdi: this.format(result.mdi) };\n }\n }\n ;\n}\nADX.calculate = adx;\nexport function adx(input) {\n Indicator.reverseInputs(input);\n var result = new ADX(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\n/**\n * Created by AAravindan on 5/8/16.\n */\n\"use strict\";\nimport { WEMA } from '../moving_averages/WEMA';\nimport { TrueRange } from './TrueRange';\nexport class ATRInput extends IndicatorInput {\n}\n;\nexport class ATR extends Indicator {\n constructor(input) {\n super(input);\n var lows = input.low;\n var highs = input.high;\n var closes = input.close;\n var period = input.period;\n var format = this.format;\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n var trueRange = new TrueRange({\n low: [],\n high: [],\n close: []\n });\n var wema = new WEMA({ period: period, values: [], format: (v) => { return v; } });\n this.result = [];\n this.generator = (function* () {\n var tick = yield;\n var avgTrueRange, trange;\n ;\n while (true) {\n trange = trueRange.nextValue({\n low: tick.low,\n high: tick.high,\n close: tick.close\n });\n if (trange === undefined) {\n avgTrueRange = undefined;\n }\n else {\n avgTrueRange = wema.nextValue(trange);\n }\n tick = yield avgTrueRange;\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value !== undefined) {\n this.result.push(format(result.value));\n }\n });\n }\n ;\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nATR.calculate = atr;\nexport function atr(input) {\n Indicator.reverseInputs(input);\n var result = new ATR(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport LinkedList from '../Utils/FixedSizeLinkedList';\nexport class ROCInput extends IndicatorInput {\n}\nexport class ROC extends Indicator {\n constructor(input) {\n super(input);\n var period = input.period;\n var priceArray = input.values;\n this.result = [];\n this.generator = (function* () {\n let index = 1;\n var pastPeriods = new LinkedList(period);\n ;\n var tick = yield;\n var roc;\n while (true) {\n pastPeriods.push(tick);\n if (index < period) {\n index++;\n }\n else {\n roc = ((tick - pastPeriods.lastShift) / (pastPeriods.lastShift)) * 100;\n }\n tick = yield roc;\n }\n })();\n this.generator.next();\n priceArray.forEach((tick) => {\n var result = this.generator.next(tick);\n if (result.value != undefined && (!isNaN(result.value))) {\n this.result.push(this.format(result.value));\n }\n });\n }\n nextValue(price) {\n var nextResult = this.generator.next(price);\n if (nextResult.value != undefined && (!isNaN(nextResult.value))) {\n return this.format(nextResult.value);\n }\n }\n ;\n}\nROC.calculate = roc;\n;\nexport function roc(input) {\n Indicator.reverseInputs(input);\n var result = new ROC(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { SMA } from '../moving_averages/SMA';\nimport { ROC } from './ROC';\nexport class KSTInput extends IndicatorInput {\n}\nexport class KSTOutput {\n}\nexport class KST extends Indicator {\n constructor(input) {\n super(input);\n let priceArray = input.values;\n let rocPer1 = input.ROCPer1;\n let rocPer2 = input.ROCPer2;\n let rocPer3 = input.ROCPer3;\n let rocPer4 = input.ROCPer4;\n let smaPer1 = input.SMAROCPer1;\n let smaPer2 = input.SMAROCPer2;\n let smaPer3 = input.SMAROCPer3;\n let smaPer4 = input.SMAROCPer4;\n let signalPeriod = input.signalPeriod;\n let roc1 = new ROC({ period: rocPer1, values: [] });\n let roc2 = new ROC({ period: rocPer2, values: [] });\n let roc3 = new ROC({ period: rocPer3, values: [] });\n let roc4 = new ROC({ period: rocPer4, values: [] });\n let sma1 = new SMA({ period: smaPer1, values: [], format: (v) => { return v; } });\n let sma2 = new SMA({ period: smaPer2, values: [], format: (v) => { return v; } });\n let sma3 = new SMA({ period: smaPer3, values: [], format: (v) => { return v; } });\n let sma4 = new SMA({ period: smaPer4, values: [], format: (v) => { return v; } });\n let signalSMA = new SMA({ period: signalPeriod, values: [], format: (v) => { return v; } });\n var format = this.format;\n this.result = [];\n let firstResult = Math.max(rocPer1 + smaPer1, rocPer2 + smaPer2, rocPer3 + smaPer3, rocPer4 + smaPer4);\n this.generator = (function* () {\n let index = 1;\n let tick = yield;\n let kst;\n let RCMA1, RCMA2, RCMA3, RCMA4, signal, result;\n while (true) {\n let roc1Result = roc1.nextValue(tick);\n let roc2Result = roc2.nextValue(tick);\n let roc3Result = roc3.nextValue(tick);\n let roc4Result = roc4.nextValue(tick);\n RCMA1 = (roc1Result !== undefined) ? sma1.nextValue(roc1Result) : undefined;\n RCMA2 = (roc2Result !== undefined) ? sma2.nextValue(roc2Result) : undefined;\n RCMA3 = (roc3Result !== undefined) ? sma3.nextValue(roc3Result) : undefined;\n RCMA4 = (roc4Result !== undefined) ? sma4.nextValue(roc4Result) : undefined;\n if (index < firstResult) {\n index++;\n }\n else {\n kst = (RCMA1 * 1) + (RCMA2 * 2) + (RCMA3 * 3) + (RCMA4 * 4);\n }\n signal = (kst !== undefined) ? signalSMA.nextValue(kst) : undefined;\n result = kst !== undefined ? {\n kst: format(kst),\n signal: signal ? format(signal) : undefined\n } : undefined;\n tick = yield result;\n }\n })();\n this.generator.next();\n priceArray.forEach((tick) => {\n let result = this.generator.next(tick);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n let nextResult = this.generator.next(price);\n if (nextResult.value != undefined)\n return nextResult.value;\n }\n ;\n}\nKST.calculate = kst;\nexport function kst(input) {\n Indicator.reverseInputs(input);\n var result = new KST(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { IndicatorInput, Indicator } from '../indicator/indicator';\n\"use strict\";\n/*\n There seems to be a few interpretations of the rules for this regarding which prices.\n I mean the english from which periods are included. The wording does seem to\n introduce some discrepancy so maybe that is why. I want to put the author's\n own description here to reassess this later.\n ----------------------------------------------------------------------------------------\n For the first day of entry the SAR is the previous Significant Point\n\n If long the SP is the lowest price reached while in the previous short trade\n If short the SP is the highest price reached while in the previous long trade\n\n If long:\n Find the difference between the highest price made while in the trade and the SAR for today.\n Multiple the difference by the AF and ADD the result to today's SAR to obtain the SAR for tomorrow.\n Use 0.02 for the first AF and increase it by 0.02 on every day that a new high for the trade is made.\n If a new high is not made continue to use the AF as last increased. Do not increase the AF above .20\n\n Never move the SAR for tomorrow ABOVE the previous day's LOW or today's LOW.\n If the SAR is calculated to be ABOVE the previous day's LOW or today's LOW then use the lower low between today and the previous day as the new SAR.\n Make the next day's calculations based on this SAR.\n\n If short:\n Find the difference between the lowest price made while in the trade and the SAR for today.\n Multiple the difference by the AF and SUBTRACT the result to today's SAR to obtain the SAR for tomorrow.\n Use 0.02 for the first AF and increase it by 0.02 on every day that a new high for the trade is made.\n If a new high is not made continue to use the AF as last increased. Do not increase the AF above .20\n\n Never move the SAR for tomorrow BELOW the previous day's HIGH or today's HIGH.\n If the SAR is calculated to be BELOW the previous day's HIGH or today's HIGH then use the higher high between today and the previous day as the new SAR. Make the next day's calculations based on this SAR.\n ----------------------------------------------------------------------------------------\n*/\nexport class PSARInput extends IndicatorInput {\n}\n;\nexport class PSAR extends Indicator {\n constructor(input) {\n super(input);\n let highs = input.high || [];\n let lows = input.low || [];\n var genFn = function* (step, max) {\n let curr, extreme, sar, furthest;\n let up = true;\n let accel = step;\n let prev = yield;\n while (true) {\n if (curr) {\n sar = sar + accel * (extreme - sar);\n if (up) {\n sar = Math.min(sar, furthest.low, prev.low);\n if (curr.high > extreme) {\n extreme = curr.high;\n accel = Math.min(accel + step, max);\n }\n ;\n }\n else {\n sar = Math.max(sar, furthest.high, prev.high);\n if (curr.low < extreme) {\n extreme = curr.low;\n accel = Math.min(accel + step, max);\n }\n }\n if ((up && curr.low < sar) || (!up && curr.high > sar)) {\n accel = step;\n sar = extreme;\n up = !up;\n extreme = !up ? curr.low : curr.high;\n }\n }\n else {\n // Randomly setup start values? What is the trend on first tick??\n sar = prev.low;\n extreme = prev.high;\n }\n furthest = prev;\n if (curr)\n prev = curr;\n curr = yield sar;\n }\n };\n this.result = [];\n this.generator = genFn(input.step, input.max);\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n });\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(input) {\n let nextResult = this.generator.next(input);\n if (nextResult.value !== undefined)\n return nextResult.value;\n }\n ;\n}\nPSAR.calculate = psar;\nexport function psar(input) {\n Indicator.reverseInputs(input);\n var result = new PSAR(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { IndicatorInput, Indicator } from '../indicator/indicator';\n/**\n * Created by AAravindan on 5/10/16.\n */\n\"use strict\";\nimport LinkedList from '../Utils/FixedSizeLinkedList';\nimport { SMA } from '../moving_averages/SMA';\nexport class StochasticInput extends IndicatorInput {\n}\n;\nexport class StochasticOutput {\n}\n;\nexport class Stochastic extends Indicator {\n constructor(input) {\n super(input);\n let lows = input.low;\n let highs = input.high;\n let closes = input.close;\n let period = input.period;\n let signalPeriod = input.signalPeriod;\n let format = this.format;\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n this.result = [];\n //%K = (Current Close - Lowest Low)/(Highest High - Lowest Low) * 100\n //%D = 3-day SMA of %K\n //\n //Lowest Low = lowest low for the look-back period\n //Highest High = highest high for the look-back period\n //%K is multiplied by 100 to move the decimal point two places\n this.generator = (function* () {\n let index = 1;\n let pastHighPeriods = new LinkedList(period, true, false);\n let pastLowPeriods = new LinkedList(period, false, true);\n let dSma = new SMA({\n period: signalPeriod,\n values: [],\n format: (v) => { return v; }\n });\n let k, d;\n var tick = yield;\n while (true) {\n pastHighPeriods.push(tick.high);\n pastLowPeriods.push(tick.low);\n if (index < period) {\n index++;\n tick = yield;\n continue;\n }\n let periodLow = pastLowPeriods.periodLow;\n k = (tick.close - periodLow) / (pastHighPeriods.periodHigh - periodLow) * 100;\n k = isNaN(k) ? 0 : k; //This happens when the close, high and low are same for the entire period; Bug fix for \n d = dSma.nextValue(k);\n tick = yield {\n k: format(k),\n d: (d !== undefined) ? format(d) : undefined\n };\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(input) {\n let nextResult = this.generator.next(input);\n if (nextResult.value !== undefined)\n return nextResult.value;\n }\n ;\n}\nStochastic.calculate = stochastic;\nexport function stochastic(input) {\n Indicator.reverseInputs(input);\n var result = new Stochastic(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { IndicatorInput, Indicator } from '../indicator/indicator';\nimport LinkedList from '../Utils/FixedSizeLinkedList';\nexport class WilliamsRInput extends IndicatorInput {\n}\n;\nexport class WilliamsR extends Indicator {\n constructor(input) {\n super(input);\n let lows = input.low;\n let highs = input.high;\n let closes = input.close;\n let period = input.period;\n let format = this.format;\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n this.result = [];\n //%R = (Highest High - Close)/(Highest High - Lowest Low) * -100\n //Lowest Low = lowest low for the look-back period\n //Highest High = highest high for the look-back period\n //%R is multiplied by -100 correct the inversion and move the decimal.\n this.generator = (function* () {\n let index = 1;\n let pastHighPeriods = new LinkedList(period, true, false);\n let pastLowPeriods = new LinkedList(period, false, true);\n let periodLow;\n let periodHigh;\n var tick = yield;\n let williamsR;\n while (true) {\n pastHighPeriods.push(tick.high);\n pastLowPeriods.push(tick.low);\n if (index < period) {\n index++;\n tick = yield;\n continue;\n }\n periodLow = pastLowPeriods.periodLow;\n periodHigh = pastHighPeriods.periodHigh;\n williamsR = format((periodHigh - tick.close) / (periodHigh - periodLow) * -100);\n tick = yield williamsR;\n }\n })();\n this.generator.next();\n lows.forEach((low, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n var nextResult = this.generator.next(price);\n if (nextResult.value != undefined)\n return this.format(nextResult.value);\n }\n ;\n}\nWilliamsR.calculate = williamsr;\nexport function williamsr(input) {\n Indicator.reverseInputs(input);\n var result = new WilliamsR(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","/**\n * Created by AAravindan on 5/17/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class ADLInput extends IndicatorInput {\n}\nexport class ADL extends Indicator {\n constructor(input) {\n super(input);\n var highs = input.high;\n var lows = input.low;\n var closes = input.close;\n var volumes = input.volume;\n if (!((lows.length === highs.length) && (highs.length === closes.length) && (highs.length === volumes.length))) {\n throw ('Inputs(low,high, close, volumes) not of equal size');\n }\n this.result = [];\n this.generator = (function* () {\n var result = 0;\n var tick;\n tick = yield;\n while (true) {\n let moneyFlowMultiplier = ((tick.close - tick.low) - (tick.high - tick.close)) / (tick.high - tick.low);\n moneyFlowMultiplier = isNaN(moneyFlowMultiplier) ? 1 : moneyFlowMultiplier;\n let moneyFlowVolume = moneyFlowMultiplier * tick.volume;\n result = result + moneyFlowVolume;\n tick = yield Math.round(result);\n }\n })();\n this.generator.next();\n highs.forEach((tickHigh, index) => {\n var tickInput = {\n high: tickHigh,\n low: lows[index],\n close: closes[index],\n volume: volumes[index]\n };\n var result = this.generator.next(tickInput);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nADL.calculate = adl;\nexport function adl(input) {\n Indicator.reverseInputs(input);\n var result = new ADL(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\n/**\n * Created by AAravindan on 5/17/16.\n */\n\"use strict\";\nexport class OBVInput extends IndicatorInput {\n}\nexport class OBV extends Indicator {\n constructor(input) {\n super(input);\n var closes = input.close;\n var volumes = input.volume;\n this.result = [];\n this.generator = (function* () {\n var result = 0;\n var tick;\n var lastClose;\n tick = yield;\n if (tick.close && (typeof tick.close === 'number')) {\n lastClose = tick.close;\n tick = yield;\n }\n while (true) {\n if (lastClose < tick.close) {\n result = result + tick.volume;\n }\n else if (tick.close < lastClose) {\n result = result - tick.volume;\n }\n lastClose = tick.close;\n tick = yield result;\n }\n })();\n this.generator.next();\n closes.forEach((close, index) => {\n let tickInput = {\n close: closes[index],\n volume: volumes[index]\n };\n let result = this.generator.next(tickInput);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n return this.generator.next(price).value;\n }\n ;\n}\nOBV.calculate = obv;\nexport function obv(input) {\n Indicator.reverseInputs(input);\n var result = new OBV(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","/**\n * Created by AAravindan on 5/9/16.\n */\n\"use strict\";\nimport { ROC } from './ROC.js';\nimport { EMA } from '../moving_averages/EMA.js';\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class TRIXInput extends IndicatorInput {\n}\n;\nexport class TRIX extends Indicator {\n constructor(input) {\n super(input);\n let priceArray = input.values;\n let period = input.period;\n let format = this.format;\n let ema = new EMA({ period: period, values: [], format: (v) => { return v; } });\n let emaOfema = new EMA({ period: period, values: [], format: (v) => { return v; } });\n let emaOfemaOfema = new EMA({ period: period, values: [], format: (v) => { return v; } });\n let trixROC = new ROC({ period: 1, values: [], format: (v) => { return v; } });\n this.result = [];\n this.generator = (function* () {\n let tick = yield;\n while (true) {\n let initialema = ema.nextValue(tick);\n let smoothedResult = initialema ? emaOfema.nextValue(initialema) : undefined;\n let doubleSmoothedResult = smoothedResult ? emaOfemaOfema.nextValue(smoothedResult) : undefined;\n let result = doubleSmoothedResult ? trixROC.nextValue(doubleSmoothedResult) : undefined;\n tick = yield result ? format(result) : undefined;\n }\n })();\n this.generator.next();\n priceArray.forEach((tick) => {\n let result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n nextValue(price) {\n let nextResult = this.generator.next(price);\n if (nextResult.value !== undefined)\n return nextResult.value;\n }\n ;\n}\nTRIX.calculate = trix;\nexport function trix(input) {\n Indicator.reverseInputs(input);\n var result = new TRIX(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { EMA } from '../moving_averages/EMA';\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class ForceIndexInput extends IndicatorInput {\n constructor() {\n super(...arguments);\n this.period = 1;\n }\n}\n;\nexport class ForceIndex extends Indicator {\n constructor(input) {\n super(input);\n var closes = input.close;\n var volumes = input.volume;\n var period = input.period || 1;\n if (!((volumes.length === closes.length))) {\n throw ('Inputs(volume, close) not of equal size');\n }\n let emaForceIndex = new EMA({ values: [], period: period });\n this.result = [];\n this.generator = (function* () {\n var previousTick = yield;\n var tick = yield;\n let forceIndex;\n while (true) {\n forceIndex = (tick.close - previousTick.close) * tick.volume;\n previousTick = tick;\n tick = yield emaForceIndex.nextValue(forceIndex);\n }\n })();\n this.generator.next();\n volumes.forEach((tick, index) => {\n var result = this.generator.next({\n close: closes[index],\n volume: volumes[index]\n });\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n ;\n nextValue(price) {\n let result = this.generator.next(price).value;\n if (result != undefined) {\n return result;\n }\n }\n ;\n}\nForceIndex.calculate = forceindex;\nexport function forceindex(input) {\n Indicator.reverseInputs(input);\n var result = new ForceIndex(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { SMA } from '../moving_averages/SMA';\nimport LinkedList from '../Utils/FixedSizeLinkedList';\nexport class CCIInput extends IndicatorInput {\n}\n;\nexport class CCI extends Indicator {\n constructor(input) {\n super(input);\n var lows = input.low;\n var highs = input.high;\n var closes = input.close;\n var period = input.period;\n var format = this.format;\n let constant = .015;\n var currentTpSet = new LinkedList(period);\n ;\n var tpSMACalculator = new SMA({ period: period, values: [], format: (v) => { return v; } });\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n this.result = [];\n this.generator = (function* () {\n var tick = yield;\n while (true) {\n let tp = (tick.high + tick.low + tick.close) / 3;\n currentTpSet.push(tp);\n let smaTp = tpSMACalculator.nextValue(tp);\n let meanDeviation = null;\n let cci;\n let sum = 0;\n if (smaTp != undefined) {\n //First, subtract the most recent 20-period average of the typical price from each period's typical price. \n //Second, take the absolute values of these numbers.\n //Third,sum the absolute values. \n for (let x of currentTpSet.iterator()) {\n sum = sum + (Math.abs(x - smaTp));\n }\n //Fourth, divide by the total number of periods (20). \n meanDeviation = sum / 20;\n cci = (tp - smaTp) / (constant * meanDeviation);\n }\n tick = yield cci;\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index]\n });\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n ;\n nextValue(price) {\n let result = this.generator.next(price).value;\n if (result != undefined) {\n return result;\n }\n }\n ;\n}\nCCI.calculate = cci;\nexport function cci(input) {\n Indicator.reverseInputs(input);\n var result = new CCI(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { SMA } from '../moving_averages/SMA';\nexport class AwesomeOscillatorInput extends IndicatorInput {\n}\nexport class AwesomeOscillator extends Indicator {\n constructor(input) {\n super(input);\n var highs = input.high;\n var lows = input.low;\n var fastPeriod = input.fastPeriod;\n var slowPeriod = input.slowPeriod;\n var slowSMA = new SMA({ values: [], period: slowPeriod });\n var fastSMA = new SMA({ values: [], period: fastPeriod });\n this.result = [];\n this.generator = (function* () {\n var result;\n var tick;\n var medianPrice;\n var slowSmaValue;\n var fastSmaValue;\n tick = yield;\n while (true) {\n medianPrice = (tick.high + tick.low) / 2;\n slowSmaValue = slowSMA.nextValue(medianPrice);\n fastSmaValue = fastSMA.nextValue(medianPrice);\n if (slowSmaValue !== undefined && fastSmaValue !== undefined) {\n result = fastSmaValue - slowSmaValue;\n }\n tick = yield result;\n }\n })();\n this.generator.next();\n highs.forEach((tickHigh, index) => {\n var tickInput = {\n high: tickHigh,\n low: lows[index],\n };\n var result = this.generator.next(tickInput);\n if (result.value != undefined) {\n this.result.push(this.format(result.value));\n }\n });\n }\n ;\n nextValue(price) {\n var result = this.generator.next(price);\n if (result.value != undefined) {\n return this.format(result.value);\n }\n }\n ;\n}\nAwesomeOscillator.calculate = awesomeoscillator;\nexport function awesomeoscillator(input) {\n Indicator.reverseInputs(input);\n var result = new AwesomeOscillator(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class VWAPInput extends IndicatorInput {\n}\n;\nexport class VWAP extends Indicator {\n constructor(input) {\n super(input);\n var lows = input.low;\n var highs = input.high;\n var closes = input.close;\n var volumes = input.volume;\n var format = this.format;\n if (!((lows.length === highs.length) && (highs.length === closes.length))) {\n throw ('Inputs(low,high, close) not of equal size');\n }\n this.result = [];\n this.generator = (function* () {\n var tick = yield;\n let cumulativeTotal = 0;\n let cumulativeVolume = 0;\n while (true) {\n let typicalPrice = (tick.high + tick.low + tick.close) / 3;\n let total = tick.volume * typicalPrice;\n cumulativeTotal = cumulativeTotal + total;\n cumulativeVolume = cumulativeVolume + tick.volume;\n tick = yield cumulativeTotal / cumulativeVolume;\n ;\n }\n })();\n this.generator.next();\n lows.forEach((tick, index) => {\n var result = this.generator.next({\n high: highs[index],\n low: lows[index],\n close: closes[index],\n volume: volumes[index]\n });\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n ;\n nextValue(price) {\n let result = this.generator.next(price).value;\n if (result != undefined) {\n return result;\n }\n }\n ;\n}\nVWAP.calculate = vwap;\nexport function vwap(input) {\n Indicator.reverseInputs(input);\n var result = new VWAP(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class VolumeProfileInput extends IndicatorInput {\n}\nexport class VolumeProfileOutput {\n}\nexport function priceFallsBetweenBarRange(low, high, low1, high1) {\n return (low <= low1 && high >= low1) || (low1 <= low && high1 >= low);\n}\nexport class VolumeProfile extends Indicator {\n constructor(input) {\n super(input);\n var highs = input.high;\n var lows = input.low;\n var closes = input.close;\n var opens = input.open;\n var volumes = input.volume;\n var bars = input.noOfBars;\n if (!((lows.length === highs.length) && (highs.length === closes.length) && (highs.length === volumes.length))) {\n throw ('Inputs(low,high, close, volumes) not of equal size');\n }\n this.result = [];\n var max = Math.max(...highs, ...lows, ...closes, ...opens);\n var min = Math.min(...highs, ...lows, ...closes, ...opens);\n var barRange = (max - min) / bars;\n var lastEnd = min;\n for (let i = 0; i < bars; i++) {\n let rangeStart = lastEnd;\n let rangeEnd = rangeStart + barRange;\n lastEnd = rangeEnd;\n let bullishVolume = 0;\n let bearishVolume = 0;\n let totalVolume = 0;\n for (let priceBar = 0; priceBar < highs.length; priceBar++) {\n let priceBarStart = lows[priceBar];\n let priceBarEnd = highs[priceBar];\n let priceBarOpen = opens[priceBar];\n let priceBarClose = closes[priceBar];\n let priceBarVolume = volumes[priceBar];\n if (priceFallsBetweenBarRange(rangeStart, rangeEnd, priceBarStart, priceBarEnd)) {\n totalVolume = totalVolume + priceBarVolume;\n if (priceBarOpen > priceBarClose) {\n bearishVolume = bearishVolume + priceBarVolume;\n }\n else {\n bullishVolume = bullishVolume + priceBarVolume;\n }\n }\n }\n this.result.push({\n rangeStart, rangeEnd, bullishVolume, bearishVolume, totalVolume\n });\n }\n }\n ;\n nextValue(price) {\n throw ('Next value not supported for volume profile');\n }\n ;\n}\nVolumeProfile.calculate = volumeprofile;\nexport function volumeprofile(input) {\n Indicator.reverseInputs(input);\n var result = new VolumeProfile(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","/**\n * Created by AAravindan on 5/4/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class TypicalPriceInput extends IndicatorInput {\n}\nexport class TypicalPrice extends Indicator {\n constructor(input) {\n super(input);\n this.result = [];\n this.generator = (function* () {\n let priceInput = yield;\n while (true) {\n priceInput = yield (priceInput.high + priceInput.low + priceInput.close) / 3;\n }\n })();\n this.generator.next();\n input.low.forEach((tick, index) => {\n var result = this.generator.next({\n high: input.high[index],\n low: input.low[index],\n close: input.close[index],\n });\n this.result.push(result.value);\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n return result;\n }\n ;\n}\nTypicalPrice.calculate = typicalprice;\nexport function typicalprice(input) {\n Indicator.reverseInputs(input);\n var result = new TypicalPrice(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","/**\n * Created by AAravindan on 5/17/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nimport { TypicalPrice } from '../chart_types/TypicalPrice';\nimport FixedSizeLinkedList from '../Utils/FixedSizeLinkedList';\nexport class MFIInput extends IndicatorInput {\n}\nexport class MFI extends Indicator {\n constructor(input) {\n super(input);\n var highs = input.high;\n var lows = input.low;\n var closes = input.close;\n var volumes = input.volume;\n var period = input.period;\n var typicalPrice = new TypicalPrice({ low: [], high: [], close: [] });\n var positiveFlow = new FixedSizeLinkedList(period, false, false, true);\n var negativeFlow = new FixedSizeLinkedList(period, false, false, true);\n if (!((lows.length === highs.length) && (highs.length === closes.length) && (highs.length === volumes.length))) {\n throw ('Inputs(low,high, close, volumes) not of equal size');\n }\n this.result = [];\n this.generator = (function* () {\n var result;\n var tick;\n var lastClose;\n var positiveFlowForPeriod;\n var rawMoneyFlow = 0;\n var moneyFlowRatio;\n var negativeFlowForPeriod;\n let typicalPriceValue = null;\n let prevousTypicalPrice = null;\n tick = yield;\n lastClose = tick.close; //Fist value \n tick = yield;\n while (true) {\n var { high, low, close, volume } = tick;\n var positionMoney = 0;\n var negativeMoney = 0;\n typicalPriceValue = typicalPrice.nextValue({ high, low, close });\n rawMoneyFlow = typicalPriceValue * volume;\n if ((typicalPriceValue != null) && (prevousTypicalPrice != null)) {\n typicalPriceValue > prevousTypicalPrice ? positionMoney = rawMoneyFlow : negativeMoney = rawMoneyFlow;\n positiveFlow.push(positionMoney);\n negativeFlow.push(negativeMoney);\n positiveFlowForPeriod = positiveFlow.periodSum;\n negativeFlowForPeriod = negativeFlow.periodSum;\n if ((positiveFlow.totalPushed >= period) && (positiveFlow.totalPushed >= period)) {\n moneyFlowRatio = positiveFlowForPeriod / negativeFlowForPeriod;\n result = 100 - 100 / (1 + moneyFlowRatio);\n }\n }\n prevousTypicalPrice = typicalPriceValue;\n tick = yield result;\n }\n })();\n this.generator.next();\n highs.forEach((tickHigh, index) => {\n var tickInput = {\n high: tickHigh,\n low: lows[index],\n close: closes[index],\n volume: volumes[index]\n };\n var result = this.generator.next(tickInput);\n if (result.value != undefined) {\n this.result.push(parseFloat(result.value.toFixed(2)));\n }\n });\n }\n ;\n nextValue(price) {\n var result = this.generator.next(price);\n if (result.value != undefined) {\n return (parseFloat(result.value.toFixed(2)));\n }\n }\n ;\n}\nMFI.calculate = mfi;\nexport function mfi(input) {\n Indicator.reverseInputs(input);\n var result = new MFI(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { IndicatorInput, Indicator } from '../indicator/indicator';\n/**\n * Created by AAravindan on 5/10/16.\n */\n\"use strict\";\nimport { SMA } from '../moving_averages/SMA';\nimport { RSI } from '../oscillators/RSI';\nimport { Stochastic } from '../momentum/Stochastic';\nexport class StochasticRsiInput extends IndicatorInput {\n}\n;\nexport class StochasticRSIOutput {\n}\n;\nexport class StochasticRSI extends Indicator {\n constructor(input) {\n super(input);\n let closes = input.values;\n let rsiPeriod = input.rsiPeriod;\n let stochasticPeriod = input.stochasticPeriod;\n let kPeriod = input.kPeriod;\n let dPeriod = input.dPeriod;\n let format = this.format;\n this.result = [];\n this.generator = (function* () {\n let index = 1;\n let rsi = new RSI({ period: rsiPeriod, values: [] });\n let stochastic = new Stochastic({ period: stochasticPeriod, high: [], low: [], close: [], signalPeriod: kPeriod });\n let dSma = new SMA({\n period: dPeriod,\n values: [],\n format: (v) => { return v; }\n });\n let lastRSI, stochasticRSI, d, result;\n var tick = yield;\n while (true) {\n lastRSI = rsi.nextValue(tick);\n if (lastRSI !== undefined) {\n var stochasticInput = { high: lastRSI, low: lastRSI, close: lastRSI };\n stochasticRSI = stochastic.nextValue(stochasticInput);\n if (stochasticRSI !== undefined && stochasticRSI.d !== undefined) {\n d = dSma.nextValue(stochasticRSI.d);\n if (d !== undefined)\n result = {\n stochRSI: stochasticRSI.k,\n k: stochasticRSI.d,\n d: d\n };\n }\n }\n tick = yield result;\n }\n })();\n this.generator.next();\n closes.forEach((tick, index) => {\n var result = this.generator.next(tick);\n if (result.value !== undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(input) {\n let nextResult = this.generator.next(input);\n if (nextResult.value !== undefined)\n return nextResult.value;\n }\n ;\n}\nStochasticRSI.calculate = stochasticrsi;\nexport function stochasticrsi(input) {\n Indicator.reverseInputs(input);\n var result = new StochasticRSI(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport FixedSizedLinkedList from './FixedSizeLinkedList';\nexport class HighestInput extends IndicatorInput {\n}\nexport class Highest extends Indicator {\n constructor(input) {\n super(input);\n var values = input.values;\n var period = input.period;\n this.result = [];\n var periodList = new FixedSizedLinkedList(period, true, false, false);\n this.generator = (function* () {\n var result;\n var tick;\n var high;\n tick = yield;\n while (true) {\n periodList.push(tick);\n if (periodList.totalPushed >= period) {\n high = periodList.periodHigh;\n }\n tick = yield high;\n }\n })();\n this.generator.next();\n values.forEach((value, index) => {\n var result = this.generator.next(value);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n var result = this.generator.next(price);\n if (result.value != undefined) {\n return result.value;\n }\n }\n ;\n}\nHighest.calculate = highest;\nexport function highest(input) {\n Indicator.reverseInputs(input);\n var result = new Highest(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport FixedSizedLinkedList from './FixedSizeLinkedList';\nexport class LowestInput extends IndicatorInput {\n}\nexport class Lowest extends Indicator {\n constructor(input) {\n super(input);\n var values = input.values;\n var period = input.period;\n this.result = [];\n var periodList = new FixedSizedLinkedList(period, false, true, false);\n this.generator = (function* () {\n var result;\n var tick;\n var high;\n tick = yield;\n while (true) {\n periodList.push(tick);\n if (periodList.totalPushed >= period) {\n high = periodList.periodLow;\n }\n tick = yield high;\n }\n })();\n this.generator.next();\n values.forEach((value, index) => {\n var result = this.generator.next(value);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n var result = this.generator.next(price);\n if (result.value != undefined) {\n return result.value;\n }\n }\n ;\n}\nLowest.calculate = lowest;\nexport function lowest(input) {\n Indicator.reverseInputs(input);\n var result = new Lowest(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { Indicator, IndicatorInput } from '../indicator/indicator';\nimport FixedSizedLinkedList from './FixedSizeLinkedList';\nexport class SumInput extends IndicatorInput {\n}\nexport class Sum extends Indicator {\n constructor(input) {\n super(input);\n var values = input.values;\n var period = input.period;\n this.result = [];\n var periodList = new FixedSizedLinkedList(period, false, false, true);\n this.generator = (function* () {\n var result;\n var tick;\n var high;\n tick = yield;\n while (true) {\n periodList.push(tick);\n if (periodList.totalPushed >= period) {\n high = periodList.periodSum;\n }\n tick = yield high;\n }\n })();\n this.generator.next();\n values.forEach((value, index) => {\n var result = this.generator.next(value);\n if (result.value != undefined) {\n this.result.push(result.value);\n }\n });\n }\n ;\n nextValue(price) {\n var result = this.generator.next(price);\n if (result.value != undefined) {\n return result.value;\n }\n }\n ;\n}\nSum.calculate = sum;\nexport function sum(input) {\n Indicator.reverseInputs(input);\n var result = new Sum(input).result;\n if (input.reversedInput) {\n result.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { CandleList } from '../StockData';\nimport { atr } from '../directionalmovement/ATR';\n/**\n * Created by AAravindan on 5/4/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class RenkoInput extends IndicatorInput {\n}\nclass Renko extends Indicator {\n constructor(input) {\n super(input);\n var format = this.format;\n let useATR = input.useATR;\n let brickSize = input.brickSize || 0;\n if (useATR) {\n let atrResult = atr(Object.assign({}, input));\n brickSize = atrResult[atrResult.length - 1];\n }\n this.result = new CandleList();\n ;\n if (brickSize === 0) {\n console.error('Not enough data to calculate brickSize for renko when using ATR');\n return;\n }\n let lastOpen = 0;\n let lastHigh = 0;\n let lastLow = Infinity;\n let lastClose = 0;\n let lastVolume = 0;\n let lastTimestamp = 0;\n this.generator = (function* () {\n let candleData = yield;\n while (true) {\n //Calculating first bar\n if (lastOpen === 0) {\n lastOpen = candleData.close;\n lastHigh = candleData.high;\n lastLow = candleData.low;\n lastClose = candleData.close;\n lastVolume = candleData.volume;\n lastTimestamp = candleData.timestamp;\n candleData = yield;\n continue;\n }\n let absoluteMovementFromClose = Math.abs(candleData.close - lastClose);\n let absoluteMovementFromOpen = Math.abs(candleData.close - lastOpen);\n if ((absoluteMovementFromClose >= brickSize) && (absoluteMovementFromOpen >= brickSize)) {\n let reference = absoluteMovementFromClose > absoluteMovementFromOpen ? lastOpen : lastClose;\n let calculated = {\n open: reference,\n high: lastHigh > candleData.high ? lastHigh : candleData.high,\n low: lastLow < candleData.Low ? lastLow : candleData.low,\n close: reference > candleData.close ? (reference - brickSize) : (reference + brickSize),\n volume: lastVolume + candleData.volume,\n timestamp: candleData.timestamp\n };\n lastOpen = calculated.open;\n lastHigh = calculated.close;\n lastLow = calculated.close;\n lastClose = calculated.close;\n lastVolume = 0;\n candleData = yield calculated;\n }\n else {\n lastHigh = lastHigh > candleData.high ? lastHigh : candleData.high;\n lastLow = lastLow < candleData.Low ? lastLow : candleData.low;\n lastVolume = lastVolume + candleData.volume;\n lastTimestamp = candleData.timestamp;\n candleData = yield;\n }\n }\n })();\n this.generator.next();\n input.low.forEach((tick, index) => {\n var result = this.generator.next({\n open: input.open[index],\n high: input.high[index],\n low: input.low[index],\n close: input.close[index],\n volume: input.volume[index],\n timestamp: input.timestamp[index]\n });\n if (result.value) {\n this.result.open.push(result.value.open);\n this.result.high.push(result.value.high);\n this.result.low.push(result.value.low);\n this.result.close.push(result.value.close);\n this.result.volume.push(result.value.volume);\n this.result.timestamp.push(result.value.timestamp);\n }\n });\n }\n nextValue(price) {\n console.error('Cannot calculate next value on Renko, Every value has to be recomputed for every change, use calcualte method');\n return null;\n }\n ;\n}\nRenko.calculate = renko;\nexport function renko(input) {\n Indicator.reverseInputs(input);\n var result = new Renko(input).result;\n if (input.reversedInput) {\n result.open.reverse();\n result.high.reverse();\n result.low.reverse();\n result.close.reverse();\n result.volume.reverse();\n result.timestamp.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import { CandleList } from '../StockData';\n/**\n * Created by AAravindan on 5/4/16.\n */\nimport { Indicator, IndicatorInput } from '../indicator/indicator';\nexport class HeikinAshiInput extends IndicatorInput {\n}\nexport class HeikinAshi extends Indicator {\n constructor(input) {\n super(input);\n var format = this.format;\n this.result = new CandleList();\n let lastOpen = null;\n let lastHigh = 0;\n let lastLow = Infinity;\n let lastClose = 0;\n let lastVolume = 0;\n let lastTimestamp = 0;\n this.generator = (function* () {\n let candleData = yield;\n let calculated = null;\n while (true) {\n if (lastOpen === null) {\n lastOpen = (candleData.close + candleData.open) / 2;\n lastHigh = candleData.high;\n lastLow = candleData.low;\n lastClose = (candleData.close + candleData.open + candleData.high + candleData.low) / 4;\n lastVolume = (candleData.volume || 0);\n lastTimestamp = (candleData.timestamp || 0);\n calculated = {\n open: lastOpen,\n high: lastHigh,\n low: lastLow,\n close: lastClose,\n volume: candleData.volume || 0,\n timestamp: (candleData.timestamp || 0)\n };\n }\n else {\n let newClose = (candleData.close + candleData.open + candleData.high + candleData.low) / 4;\n let newOpen = (lastOpen + lastClose) / 2;\n let newHigh = Math.max(newOpen, newClose, candleData.high);\n let newLow = Math.min(candleData.low, newOpen, newClose);\n calculated = {\n close: newClose,\n open: newOpen,\n high: newHigh,\n low: newLow,\n volume: (candleData.volume || 0),\n timestamp: (candleData.timestamp || 0)\n };\n lastClose = newClose;\n lastOpen = newOpen;\n lastHigh = newHigh;\n lastLow = newLow;\n }\n candleData = yield calculated;\n }\n })();\n this.generator.next();\n input.low.forEach((tick, index) => {\n var result = this.generator.next({\n open: input.open[index],\n high: input.high[index],\n low: input.low[index],\n close: input.close[index],\n volume: input.volume ? input.volume[index] : input.volume,\n timestamp: input.timestamp ? input.timestamp[index] : input.timestamp\n });\n if (result.value) {\n this.result.open.push(result.value.open);\n this.result.high.push(result.value.high);\n this.result.low.push(result.value.low);\n this.result.close.push(result.value.close);\n this.result.volume.push(result.value.volume);\n this.result.timestamp.push(result.value.timestamp);\n }\n });\n }\n nextValue(price) {\n var result = this.generator.next(price).value;\n return result;\n }\n ;\n}\nHeikinAshi.calculate = heikinashi;\nexport function heikinashi(input) {\n Indicator.reverseInputs(input);\n var result = new HeikinAshi(input).result;\n if (input.reversedInput) {\n result.open.reverse();\n result.high.reverse();\n result.low.reverse();\n result.close.reverse();\n result.volume.reverse();\n result.timestamp.reverse();\n }\n Indicator.reverseInputs(input);\n return result;\n}\n;\n","import CandlestickFinder from './CandlestickFinder';\nexport default class MorningStar extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'MorningStar';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let firstdaysMidpoint = ((firstdaysOpen + firstdaysClose) / 2);\n let isFirstBearish = firstdaysClose < firstdaysOpen;\n let isSmallBodyExists = ((firstdaysLow > seconddaysLow) &&\n (firstdaysLow > seconddaysHigh));\n let isThirdBullish = thirddaysOpen < thirddaysClose;\n let gapExists = ((seconddaysHigh < firstdaysLow) &&\n (seconddaysLow < firstdaysLow) &&\n (thirddaysOpen > seconddaysHigh) &&\n (seconddaysClose < thirddaysOpen));\n let doesCloseAboveFirstMidpoint = thirddaysClose > firstdaysMidpoint;\n return (isFirstBearish && isSmallBodyExists && gapExists && isThirdBullish && doesCloseAboveFirstMidpoint);\n }\n}\nexport function morningstar(data) {\n return new MorningStar().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishEngulfingPattern extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BullishEngulfingPattern';\n this.requiredCount = 2;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBullishEngulfing = ((firstdaysClose < firstdaysOpen) &&\n (firstdaysOpen > seconddaysOpen) &&\n (firstdaysClose > seconddaysOpen) &&\n (firstdaysOpen < seconddaysClose));\n return (isBullishEngulfing);\n }\n}\nexport function bullishengulfingpattern(data) {\n return new BullishEngulfingPattern().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishHarami extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 2;\n this.name = \"BullishHarami\";\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBullishHaramiPattern = ((firstdaysOpen > seconddaysOpen) &&\n (firstdaysClose < seconddaysOpen) &&\n (firstdaysClose < seconddaysClose) &&\n (firstdaysOpen > seconddaysLow) &&\n (firstdaysHigh > seconddaysHigh));\n return (isBullishHaramiPattern);\n }\n}\nexport function bullishharami(data) {\n return new BullishHarami().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishHaramiCross extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 2;\n this.name = 'BullishHaramiCross';\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBullishHaramiCrossPattern = ((firstdaysOpen > seconddaysOpen) &&\n (firstdaysClose < seconddaysOpen) &&\n (firstdaysClose < seconddaysClose) &&\n (firstdaysOpen > seconddaysLow) &&\n (firstdaysHigh > seconddaysHigh));\n let isSecondDayDoji = this.approximateEqual(seconddaysOpen, seconddaysClose);\n return (isBullishHaramiCrossPattern && isSecondDayDoji);\n }\n}\nexport function bullishharamicross(data) {\n return new BullishHaramiCross().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class Doji extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'Doji';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isOpenEqualsClose = this.approximateEqual(daysOpen, daysClose);\n let isHighEqualsOpen = isOpenEqualsClose && this.approximateEqual(daysOpen, daysHigh);\n let isLowEqualsClose = isOpenEqualsClose && this.approximateEqual(daysClose, daysLow);\n return (isOpenEqualsClose && isHighEqualsOpen == isLowEqualsClose);\n }\n}\nexport function doji(data) {\n return new Doji().hasPattern(data);\n}\n","import Doji from './Doji';\nimport CandlestickFinder from './CandlestickFinder';\nexport default class MorningDojiStar extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'MorningDojiStar';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let firstdaysMidpoint = ((firstdaysOpen + firstdaysClose) / 2);\n let isFirstBearish = firstdaysClose < firstdaysOpen;\n let dojiExists = new Doji().hasPattern({\n \"open\": [seconddaysOpen],\n \"close\": [seconddaysClose],\n \"high\": [seconddaysHigh],\n \"low\": [seconddaysLow]\n });\n let isThirdBullish = thirddaysOpen < thirddaysClose;\n let gapExists = ((seconddaysHigh < firstdaysLow) &&\n (seconddaysLow < firstdaysLow) &&\n (thirddaysOpen > seconddaysHigh) &&\n (seconddaysClose < thirddaysOpen));\n let doesCloseAboveFirstMidpoint = thirddaysClose > firstdaysMidpoint;\n return (isFirstBearish && dojiExists && isThirdBullish && gapExists &&\n doesCloseAboveFirstMidpoint);\n }\n}\nexport function morningdojistar(data) {\n return new MorningDojiStar().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class DownsideTasukiGap extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 3;\n this.name = 'DownsideTasukiGap';\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let isFirstBearish = firstdaysClose < firstdaysOpen;\n let isSecondBearish = seconddaysClose < seconddaysOpen;\n let isThirdBullish = thirddaysClose > thirddaysOpen;\n let isFirstGapExists = seconddaysHigh < firstdaysLow;\n let isDownsideTasukiGap = ((seconddaysOpen > thirddaysOpen) &&\n (seconddaysClose < thirddaysOpen) &&\n (thirddaysClose > seconddaysOpen) &&\n (thirddaysClose < firstdaysClose));\n return (isFirstBearish && isSecondBearish && isThirdBullish && isFirstGapExists && isDownsideTasukiGap);\n }\n}\nexport function downsidetasukigap(data) {\n return new DownsideTasukiGap().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishMarubozu extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BullishMarubozu';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBullishMarbozu = this.approximateEqual(daysClose, daysHigh) &&\n this.approximateEqual(daysLow, daysOpen) &&\n daysOpen < daysClose &&\n daysOpen < daysHigh;\n return (isBullishMarbozu);\n }\n}\nexport function bullishmarubozu(data) {\n return new BullishMarubozu().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class PiercingLine extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 2;\n this.name = 'PiercingLine';\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let firstdaysMidpoint = ((firstdaysOpen + firstdaysClose) / 2);\n let isDowntrend = seconddaysLow < firstdaysLow;\n let isFirstBearish = firstdaysClose < firstdaysOpen;\n let isSecondBullish = seconddaysClose > seconddaysOpen;\n let isPiercingLinePattern = ((firstdaysLow > seconddaysOpen) &&\n (seconddaysClose > firstdaysMidpoint));\n return (isDowntrend && isFirstBearish && isPiercingLinePattern && isSecondBullish);\n }\n}\nexport function piercingline(data) {\n return new PiercingLine().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class ThreeWhiteSoldiers extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'ThreeWhiteSoldiers';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let isUpTrend = seconddaysHigh > firstdaysHigh &&\n thirddaysHigh > seconddaysHigh;\n let isAllBullish = firstdaysOpen < firstdaysClose &&\n seconddaysOpen < seconddaysClose &&\n thirddaysOpen < thirddaysClose;\n let doesOpenWithinPreviousBody = firstdaysClose > seconddaysOpen &&\n seconddaysOpen < firstdaysHigh &&\n seconddaysHigh > thirddaysOpen &&\n thirddaysOpen < seconddaysClose;\n return (isUpTrend && isAllBullish && doesOpenWithinPreviousBody);\n }\n}\nexport function threewhitesoldiers(data) {\n return new ThreeWhiteSoldiers().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishHammerStick extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BullishHammerStick';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBullishHammer = daysClose > daysOpen;\n isBullishHammer = isBullishHammer && this.approximateEqual(daysClose, daysHigh);\n isBullishHammer = isBullishHammer && (daysClose - daysOpen) <= 2 * (daysOpen - daysLow);\n return isBullishHammer;\n }\n}\nexport function bullishhammerstick(data) {\n return new BullishHammerStick().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishInvertedHammerStick extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BullishInvertedHammerStick';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBullishInvertedHammer = daysClose > daysOpen;\n isBullishInvertedHammer = isBullishInvertedHammer && this.approximateEqual(daysOpen, daysLow);\n isBullishInvertedHammer = isBullishInvertedHammer && (daysClose - daysOpen) <= 2 * (daysHigh - daysClose);\n return isBullishInvertedHammer;\n }\n}\nexport function bullishinvertedhammerstick(data) {\n return new BullishInvertedHammerStick().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishHammerStick extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BearishHammerStick';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBearishHammer = daysOpen > daysClose;\n isBearishHammer = isBearishHammer && this.approximateEqual(daysOpen, daysHigh);\n isBearishHammer = isBearishHammer && (daysOpen - daysClose) <= 2 * (daysClose - daysLow);\n return isBearishHammer;\n }\n}\nexport function bearishhammerstick(data) {\n return new BearishHammerStick().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishInvertedHammerStick extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BearishInvertedHammerStick';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBearishInvertedHammer = daysOpen > daysClose;\n isBearishInvertedHammer = isBearishInvertedHammer && this.approximateEqual(daysClose, daysLow);\n isBearishInvertedHammer = isBearishInvertedHammer && (daysOpen - daysClose) <= 2 * (daysHigh - daysOpen);\n return isBearishInvertedHammer;\n }\n}\nexport function bearishinvertedhammerstick(data) {\n return new BearishInvertedHammerStick().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport { averageloss } from '../Utils/AverageLoss';\nimport { averagegain } from '../Utils/AverageGain';\nimport { bearishhammerstick } from './BearishHammerStick';\nimport { bearishinvertedhammerstick } from './BearishInvertedHammerStick';\nimport { bullishhammerstick } from './BullishHammerStick';\nimport { bullishinvertedhammerstick } from './BullishInvertedHammerStick';\nexport default class HammerPattern extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'HammerPattern';\n this.requiredCount = 5;\n }\n logic(data) {\n let isPattern = this.downwardTrend(data);\n isPattern = isPattern && this.includesHammer(data);\n isPattern = isPattern && this.hasConfirmation(data);\n return isPattern;\n }\n downwardTrend(data, confirm = true) {\n let end = confirm ? 3 : 4;\n // Analyze trends in closing prices of the first three or four candlesticks\n let gains = averagegain({ values: data.close.slice(0, end), period: end - 1 });\n let losses = averageloss({ values: data.close.slice(0, end), period: end - 1 });\n // Downward trend, so more losses than gains\n return losses > gains;\n }\n includesHammer(data, confirm = true) {\n let start = confirm ? 3 : 4;\n let end = confirm ? 4 : undefined;\n let possibleHammerData = {\n open: data.open.slice(start, end),\n close: data.close.slice(start, end),\n low: data.low.slice(start, end),\n high: data.high.slice(start, end),\n };\n let isPattern = bearishhammerstick(possibleHammerData);\n isPattern = isPattern || bearishinvertedhammerstick(possibleHammerData);\n isPattern = isPattern || bullishhammerstick(possibleHammerData);\n isPattern = isPattern || bullishinvertedhammerstick(possibleHammerData);\n return isPattern;\n }\n hasConfirmation(data) {\n let possibleHammer = {\n open: data.open[3],\n close: data.close[3],\n low: data.low[3],\n high: data.high[3],\n };\n let possibleConfirmation = {\n open: data.open[4],\n close: data.close[4],\n low: data.low[4],\n high: data.high[4],\n };\n // Confirmation candlestick is bullish\n let isPattern = possibleConfirmation.open < possibleConfirmation.close;\n return isPattern && possibleHammer.close < possibleConfirmation.close;\n }\n}\nexport function hammerpattern(data) {\n return new HammerPattern().hasPattern(data);\n}\n","import HammerPattern from './HammerPattern';\nexport default class HammerPatternUnconfirmed extends HammerPattern {\n constructor() {\n super();\n this.name = 'HammerPatternUnconfirmed';\n }\n logic(data) {\n let isPattern = this.downwardTrend(data, false);\n isPattern = isPattern && this.includesHammer(data, false);\n return isPattern;\n }\n}\nexport function hammerpatternunconfirmed(data) {\n return new HammerPatternUnconfirmed().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport { averageloss } from '../Utils/AverageLoss';\nimport { averagegain } from '../Utils/AverageGain';\nexport default class TweezerBottom extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'TweezerBottom';\n this.requiredCount = 5;\n }\n logic(data) {\n return this.downwardTrend(data) && data.low[3] == data.low[4];\n }\n downwardTrend(data) {\n // Analyze trends in closing prices of the first three or four candlesticks\n let gains = averagegain({ values: data.close.slice(0, 3), period: 2 });\n let losses = averageloss({ values: data.close.slice(0, 3), period: 2 });\n // Downward trend, so more losses than gains\n return losses > gains;\n }\n}\nexport function tweezerbottom(data) {\n return new TweezerBottom().hasPattern(data);\n}\n","import MorningStar from './MorningStar';\nimport BullishEngulfingPattern from './BullishEngulfingPattern';\nimport BullishHarami from './BullishHarami';\nimport BullishHaramiCross from './BullishHaramiCross';\nimport MorningDojiStar from './MorningDojiStar';\nimport DownsideTasukiGap from './DownsideTasukiGap';\nimport BullishMarubozu from './BullishMarubozu';\nimport PiercingLine from './PiercingLine';\nimport ThreeWhiteSoldiers from './ThreeWhiteSoldiers';\nimport BullishHammerStick from './BullishHammerStick';\nimport BullishInvertedHammerStick from './BullishInvertedHammerStick';\nimport HammerPattern from './HammerPattern';\nimport HammerPatternUnconfirmed from './HammerPatternUnconfirmed';\nimport CandlestickFinder from './CandlestickFinder';\nimport TweezerBottom from './TweezerBottom';\nlet bullishPatterns = [\n new BullishEngulfingPattern(),\n new DownsideTasukiGap(),\n new BullishHarami(),\n new BullishHaramiCross(),\n new MorningDojiStar(),\n new MorningStar(),\n new BullishMarubozu(),\n new PiercingLine(),\n new ThreeWhiteSoldiers(),\n new BullishHammerStick(),\n new BullishInvertedHammerStick(),\n new HammerPattern(),\n new HammerPatternUnconfirmed(),\n new TweezerBottom()\n];\nexport default class BullishPatterns extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'Bullish Candlesticks';\n }\n hasPattern(data) {\n return bullishPatterns.reduce(function (state, pattern) {\n let result = pattern.hasPattern(data);\n return state || result;\n }, false);\n }\n}\nexport function bullish(data) {\n return new BullishPatterns().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishEngulfingPattern extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BearishEngulfingPattern';\n this.requiredCount = 2;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBearishEngulfing = ((firstdaysClose > firstdaysOpen) &&\n (firstdaysOpen < seconddaysOpen) &&\n (firstdaysClose < seconddaysOpen) &&\n (firstdaysOpen > seconddaysClose));\n return (isBearishEngulfing);\n }\n}\nexport function bearishengulfingpattern(data) {\n return new BearishEngulfingPattern().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishHarami extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 2;\n this.name = 'BearishHarami';\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBearishHaramiPattern = ((firstdaysOpen < seconddaysOpen) &&\n (firstdaysClose > seconddaysOpen) &&\n (firstdaysClose > seconddaysClose) &&\n (firstdaysOpen < seconddaysLow) &&\n (firstdaysHigh > seconddaysHigh));\n return (isBearishHaramiPattern);\n }\n}\nexport function bearishharami(data) {\n return new BearishHarami().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishHaramiCross extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 2;\n this.name = 'BearishHaramiCross';\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let isBearishHaramiCrossPattern = ((firstdaysOpen < seconddaysOpen) &&\n (firstdaysClose > seconddaysOpen) &&\n (firstdaysClose > seconddaysClose) &&\n (firstdaysOpen < seconddaysLow) &&\n (firstdaysHigh > seconddaysHigh));\n let isSecondDayDoji = this.approximateEqual(seconddaysOpen, seconddaysClose);\n return (isBearishHaramiCrossPattern && isSecondDayDoji);\n }\n}\nexport function bearishharamicross(data) {\n return new BearishHaramiCross().hasPattern(data);\n}\n","import Doji from './Doji';\nimport CandlestickFinder from './CandlestickFinder';\nexport default class EveningDojiStar extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'EveningDojiStar';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let firstdaysMidpoint = ((firstdaysOpen + firstdaysClose) / 2);\n let isFirstBullish = firstdaysClose > firstdaysOpen;\n let dojiExists = new Doji().hasPattern({\n \"open\": [seconddaysOpen],\n \"close\": [seconddaysClose],\n \"high\": [seconddaysHigh],\n \"low\": [seconddaysLow]\n });\n let isThirdBearish = thirddaysOpen > thirddaysClose;\n let gapExists = ((seconddaysHigh > firstdaysHigh) &&\n (seconddaysLow > firstdaysHigh) &&\n (thirddaysOpen < seconddaysLow) &&\n (seconddaysClose > thirddaysOpen));\n let doesCloseBelowFirstMidpoint = thirddaysClose < firstdaysMidpoint;\n return (isFirstBullish && dojiExists && gapExists && isThirdBearish && doesCloseBelowFirstMidpoint);\n }\n}\nexport function eveningdojistar(data) {\n return new EveningDojiStar().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class EveningStar extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'EveningStar';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let firstdaysMidpoint = ((firstdaysOpen + firstdaysClose) / 2);\n let isFirstBullish = firstdaysClose > firstdaysOpen;\n let isSmallBodyExists = ((firstdaysHigh < seconddaysLow) &&\n (firstdaysHigh < seconddaysHigh));\n let isThirdBearish = thirddaysOpen > thirddaysClose;\n let gapExists = ((seconddaysHigh > firstdaysHigh) &&\n (seconddaysLow > firstdaysHigh) &&\n (thirddaysOpen < seconddaysLow) &&\n (seconddaysClose > thirddaysOpen));\n let doesCloseBelowFirstMidpoint = thirddaysClose < firstdaysMidpoint;\n return (isFirstBullish && isSmallBodyExists && gapExists && isThirdBearish && doesCloseBelowFirstMidpoint);\n }\n}\nexport function eveningstar(data) {\n return new EveningStar().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishMarubozu extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BearishMarubozu';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isBearishMarbozu = this.approximateEqual(daysOpen, daysHigh) &&\n this.approximateEqual(daysLow, daysClose) &&\n daysOpen > daysClose &&\n daysOpen > daysLow;\n return (isBearishMarbozu);\n }\n}\nexport function bearishmarubozu(data) {\n return new BearishMarubozu().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class ThreeBlackCrows extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'ThreeBlackCrows';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let isDownTrend = firstdaysLow > seconddaysLow &&\n seconddaysLow > thirddaysLow;\n let isAllBearish = firstdaysOpen > firstdaysClose &&\n seconddaysOpen > seconddaysClose &&\n thirddaysOpen > thirddaysClose;\n let doesOpenWithinPreviousBody = firstdaysOpen > seconddaysOpen &&\n seconddaysOpen > firstdaysClose &&\n seconddaysOpen > thirddaysOpen &&\n thirddaysOpen > seconddaysClose;\n return (isDownTrend && isAllBearish && doesOpenWithinPreviousBody);\n }\n}\nexport function threeblackcrows(data) {\n return new ThreeBlackCrows().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport { averageloss } from '../Utils/AverageLoss';\nimport { averagegain } from '../Utils/AverageGain';\nimport { bearishhammerstick } from './BearishHammerStick';\nimport { bullishhammerstick } from './BullishHammerStick';\nexport default class HangingMan extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'HangingMan';\n this.requiredCount = 5;\n }\n logic(data) {\n let isPattern = this.upwardTrend(data);\n isPattern = isPattern && this.includesHammer(data);\n isPattern = isPattern && this.hasConfirmation(data);\n return isPattern;\n }\n upwardTrend(data, confirm = true) {\n let end = confirm ? 3 : 4;\n // Analyze trends in closing prices of the first three or four candlesticks\n let gains = averagegain({ values: data.close.slice(0, end), period: end - 1 });\n let losses = averageloss({ values: data.close.slice(0, end), period: end - 1 });\n // Upward trend, so more gains than losses\n return gains > losses;\n }\n includesHammer(data, confirm = true) {\n let start = confirm ? 3 : 4;\n let end = confirm ? 4 : undefined;\n let possibleHammerData = {\n open: data.open.slice(start, end),\n close: data.close.slice(start, end),\n low: data.low.slice(start, end),\n high: data.high.slice(start, end),\n };\n let isPattern = bearishhammerstick(possibleHammerData);\n isPattern = isPattern || bullishhammerstick(possibleHammerData);\n return isPattern;\n }\n hasConfirmation(data) {\n let possibleHammer = {\n open: data.open[3],\n close: data.close[3],\n low: data.low[3],\n high: data.high[3],\n };\n let possibleConfirmation = {\n open: data.open[4],\n close: data.close[4],\n low: data.low[4],\n high: data.high[4],\n };\n // Confirmation candlestick is bearish\n let isPattern = possibleConfirmation.open > possibleConfirmation.close;\n return isPattern && possibleHammer.close > possibleConfirmation.close;\n }\n}\nexport function hangingman(data) {\n return new HangingMan().hasPattern(data);\n}\n","import HangingMan from './HangingMan';\nexport default class HangingManUnconfirmed extends HangingMan {\n constructor() {\n super();\n this.name = 'HangingManUnconfirmed';\n }\n logic(data) {\n let isPattern = this.upwardTrend(data, false);\n isPattern = isPattern && this.includesHammer(data, false);\n return isPattern;\n }\n}\nexport function hangingmanunconfirmed(data) {\n return new HangingManUnconfirmed().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport { averageloss } from '../Utils/AverageLoss';\nimport { averagegain } from '../Utils/AverageGain';\nimport { bearishinvertedhammerstick } from './BearishInvertedHammerStick';\nimport { bullishinvertedhammerstick } from './BullishInvertedHammerStick';\nexport default class ShootingStar extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'ShootingStar';\n this.requiredCount = 5;\n }\n logic(data) {\n let isPattern = this.upwardTrend(data);\n isPattern = isPattern && this.includesHammer(data);\n isPattern = isPattern && this.hasConfirmation(data);\n return isPattern;\n }\n upwardTrend(data, confirm = true) {\n let end = confirm ? 3 : 4;\n // Analyze trends in closing prices of the first three or four candlesticks\n let gains = averagegain({ values: data.close.slice(0, end), period: end - 1 });\n let losses = averageloss({ values: data.close.slice(0, end), period: end - 1 });\n // Upward trend, so more gains than losses\n return gains > losses;\n }\n includesHammer(data, confirm = true) {\n let start = confirm ? 3 : 4;\n let end = confirm ? 4 : undefined;\n let possibleHammerData = {\n open: data.open.slice(start, end),\n close: data.close.slice(start, end),\n low: data.low.slice(start, end),\n high: data.high.slice(start, end),\n };\n let isPattern = bearishinvertedhammerstick(possibleHammerData);\n isPattern = isPattern || bullishinvertedhammerstick(possibleHammerData);\n return isPattern;\n }\n hasConfirmation(data) {\n let possibleHammer = {\n open: data.open[3],\n close: data.close[3],\n low: data.low[3],\n high: data.high[3],\n };\n let possibleConfirmation = {\n open: data.open[4],\n close: data.close[4],\n low: data.low[4],\n high: data.high[4],\n };\n // Confirmation candlestick is bearish\n let isPattern = possibleConfirmation.open > possibleConfirmation.close;\n return isPattern && possibleHammer.close > possibleConfirmation.close;\n }\n}\nexport function shootingstar(data) {\n return new ShootingStar().hasPattern(data);\n}\n","import ShootingStar from './ShootingStar';\nexport default class ShootingStarUnconfirmed extends ShootingStar {\n constructor() {\n super();\n this.name = 'ShootingStarUnconfirmed';\n }\n logic(data) {\n let isPattern = this.upwardTrend(data, false);\n isPattern = isPattern && this.includesHammer(data, false);\n return isPattern;\n }\n}\nexport function shootingstarunconfirmed(data) {\n return new ShootingStarUnconfirmed().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport { averageloss } from '../Utils/AverageLoss';\nimport { averagegain } from '../Utils/AverageGain';\nexport default class TweezerTop extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'TweezerTop';\n this.requiredCount = 5;\n }\n logic(data) {\n return this.upwardTrend(data) && data.high[3] == data.high[4];\n }\n upwardTrend(data) {\n // Analyze trends in closing prices of the first three or four candlesticks\n let gains = averagegain({ values: data.close.slice(0, 3), period: 2 });\n let losses = averageloss({ values: data.close.slice(0, 3), period: 2 });\n // Upward trend, so more gains than losses\n return gains > losses;\n }\n}\nexport function tweezertop(data) {\n return new TweezerTop().hasPattern(data);\n}\n","import BearishEngulfingPattern from './BearishEngulfingPattern';\nimport BearishHarami from './BearishHarami';\nimport BearishHaramiCross from './BearishHaramiCross';\nimport EveningDojiStar from './EveningDojiStar';\nimport EveningStar from './EveningStar';\nimport BearishMarubozu from './BearishMarubozu';\nimport ThreeBlackCrows from './ThreeBlackCrows';\nimport BearishHammerStick from './BearishHammerStick';\nimport BearishInvertedHammerStick from './BearishInvertedHammerStick';\nimport HangingMan from './HangingMan';\nimport HangingManUnconfirmed from './HangingManUnconfirmed';\nimport ShootingStar from './ShootingStar';\nimport ShootingStarUnconfirmed from './ShootingStarUnconfirmed';\nimport TweezerTop from './TweezerTop';\nimport CandlestickFinder from './CandlestickFinder';\nlet bearishPatterns = [\n new BearishEngulfingPattern(),\n new BearishHarami(),\n new BearishHaramiCross(),\n new EveningDojiStar(),\n new EveningStar(),\n new BearishMarubozu(),\n new ThreeBlackCrows(),\n new BearishHammerStick(),\n new BearishInvertedHammerStick(),\n new HangingMan(),\n new HangingManUnconfirmed(),\n new ShootingStar(),\n new ShootingStarUnconfirmed(),\n new TweezerTop()\n];\nexport default class BearishPatterns extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'Bearish Candlesticks';\n }\n hasPattern(data) {\n return bearishPatterns.reduce(function (state, pattern) {\n return state || pattern.hasPattern(data);\n }, false);\n }\n}\nexport function bearish(data) {\n return new BearishPatterns().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nimport Doji from './Doji';\nexport default class AbandonedBaby extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'AbandonedBaby';\n this.requiredCount = 3;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let thirddaysOpen = data.open[2];\n let thirddaysClose = data.close[2];\n let thirddaysHigh = data.high[2];\n let thirddaysLow = data.low[2];\n let isFirstBearish = firstdaysClose < firstdaysOpen;\n let dojiExists = new Doji().hasPattern({\n \"open\": [seconddaysOpen],\n \"close\": [seconddaysClose],\n \"high\": [seconddaysHigh],\n \"low\": [seconddaysLow]\n });\n let gapExists = ((seconddaysHigh < firstdaysLow) &&\n (thirddaysLow > seconddaysHigh) &&\n (thirddaysClose > thirddaysOpen));\n let isThirdBullish = (thirddaysHigh < firstdaysOpen);\n return (isFirstBearish && dojiExists && gapExists && isThirdBullish);\n }\n}\nexport function abandonedbaby(data) {\n return new AbandonedBaby().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class DarkCloudCover extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'DarkCloudCover';\n this.requiredCount = 2;\n }\n logic(data) {\n let firstdaysOpen = data.open[0];\n let firstdaysClose = data.close[0];\n let firstdaysHigh = data.high[0];\n let firstdaysLow = data.low[0];\n let seconddaysOpen = data.open[1];\n let seconddaysClose = data.close[1];\n let seconddaysHigh = data.high[1];\n let seconddaysLow = data.low[1];\n let firstdayMidpoint = ((firstdaysClose + firstdaysOpen) / 2);\n let isFirstBullish = firstdaysClose > firstdaysOpen;\n let isSecondBearish = seconddaysClose < seconddaysOpen;\n let isDarkCloudPattern = ((seconddaysOpen > firstdaysHigh) &&\n (seconddaysClose < firstdayMidpoint) &&\n (seconddaysClose > firstdaysOpen));\n return (isFirstBullish && isSecondBearish && isDarkCloudPattern);\n }\n}\nexport function darkcloudcover(data) {\n return new DarkCloudCover().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class DragonFlyDoji extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 1;\n this.name = 'DragonFlyDoji';\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isOpenEqualsClose = this.approximateEqual(daysOpen, daysClose);\n let isHighEqualsOpen = isOpenEqualsClose && this.approximateEqual(daysOpen, daysHigh);\n let isLowEqualsClose = isOpenEqualsClose && this.approximateEqual(daysClose, daysLow);\n return (isOpenEqualsClose && isHighEqualsOpen && !isLowEqualsClose);\n }\n}\nexport function dragonflydoji(data) {\n return new DragonFlyDoji().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class GraveStoneDoji extends CandlestickFinder {\n constructor() {\n super();\n this.requiredCount = 1;\n this.name = 'GraveStoneDoji';\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let isOpenEqualsClose = this.approximateEqual(daysOpen, daysClose);\n let isHighEqualsOpen = isOpenEqualsClose && this.approximateEqual(daysOpen, daysHigh);\n let isLowEqualsClose = isOpenEqualsClose && this.approximateEqual(daysClose, daysLow);\n return (isOpenEqualsClose && isLowEqualsClose && !isHighEqualsOpen);\n }\n}\nexport function gravestonedoji(data) {\n return new GraveStoneDoji().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BullishSpinningTop extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BullishSpinningTop';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let bodyLength = Math.abs(daysClose - daysOpen);\n let upperShadowLength = Math.abs(daysHigh - daysClose);\n let lowerShadowLength = Math.abs(daysOpen - daysLow);\n let isBullishSpinningTop = bodyLength < upperShadowLength &&\n bodyLength < lowerShadowLength;\n return isBullishSpinningTop;\n }\n}\nexport function bullishspinningtop(data) {\n return new BullishSpinningTop().hasPattern(data);\n}\n","import CandlestickFinder from './CandlestickFinder';\nexport default class BearishSpinningTop extends CandlestickFinder {\n constructor() {\n super();\n this.name = 'BearishSpinningTop';\n this.requiredCount = 1;\n }\n logic(data) {\n let daysOpen = data.open[0];\n let daysClose = data.close[0];\n let daysHigh = data.high[0];\n let daysLow = data.low[0];\n let bodyLength = Math.abs(daysClose - daysOpen);\n let upperShadowLength = Math.abs(daysHigh - daysOpen);\n let lowerShadowLength = Math.abs(daysHigh - daysLow);\n let isBearishSpinningTop = bodyLength < upperShadowLength &&\n bodyLength < lowerShadowLength;\n return isBearishSpinningTop;\n }\n}\nexport function bearishspinningtop(data) {\n return new BearishSpinningTop().hasPattern(data);\n}\n","/**\n * Calcaultes the fibonacci retracements for given start and end points\n *\n * If calculating for up trend start should be low and end should be high and vice versa\n *\n * returns an array of retracements level containing [0 , 23.6, 38.2, 50, 61.8, 78.6, 100, 127.2, 161.8, 261.8, 423.6]\n *\n * @export\n * @param {number} start\n * @param {number} end\n * @returns {number[]}\n */\nexport function fibonacciretracement(start, end) {\n let levels = [0, 23.6, 38.2, 50, 61.8, 78.6, 100, 127.2, 161.8, 261.8, 423.6];\n let retracements;\n if (start < end) {\n retracements = levels.map(function (level) {\n let calculated = end - Math.abs(start - end) * (level) / 100;\n return calculated > 0 ? calculated : 0;\n });\n }\n else {\n retracements = levels.map(function (level) {\n let calculated = end + Math.abs(start - end) * (level) / 100;\n return calculated > 0 ? calculated : 0;\n });\n }\n return retracements;\n}\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var baseIsEqual = require('./_baseIsEqual');\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nmodule.exports = isEqual;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var baseFor = require('./_baseFor'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nmodule.exports = baseForOwn;\n","var isArrayLike = require('./isArrayLike');\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n}\n\nmodule.exports = createBaseEach;\n","var baseEach = require('./_baseEach'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n}\n\nmodule.exports = baseMap;\n","var arrayMap = require('./_arrayMap'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n isArray = require('./isArray');\n\n/**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\nfunction map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, baseIteratee(iteratee, 3));\n}\n\nmodule.exports = map;\n","/**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\nfunction arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n}\n\nmodule.exports = arrayEvery;\n","var baseEach = require('./_baseEach');\n\n/**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\nfunction baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n}\n\nmodule.exports = baseEvery;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","var arrayEvery = require('./_arrayEvery'),\n baseEvery = require('./_baseEvery'),\n baseIteratee = require('./_baseIteratee'),\n isArray = require('./isArray'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\nfunction every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, baseIteratee(predicate, 3));\n}\n\nmodule.exports = every;\n","var baseIteratee = require('./_baseIteratee'),\n isArrayLike = require('./isArrayLike'),\n keys = require('./keys');\n\n/**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\nfunction createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = baseIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n}\n\nmodule.exports = createFind;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","var isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","var toNumber = require('./toNumber');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nmodule.exports = toFinite;\n","var toFinite = require('./toFinite');\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nmodule.exports = toInteger;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIteratee = require('./_baseIteratee'),\n toInteger = require('./toInteger');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\nfunction findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, baseIteratee(predicate, 3), index);\n}\n\nmodule.exports = findIndex;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var assignValue = require('./_assignValue'),\n castPath = require('./_castPath'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nmodule.exports = baseSet;\n","var baseGet = require('./_baseGet'),\n baseSet = require('./_baseSet'),\n castPath = require('./_castPath');\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nmodule.exports = basePickBy;\n","var basePickBy = require('./_basePickBy'),\n hasIn = require('./hasIn');\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n}\n\nmodule.exports = basePick;\n","var Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n","var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseFlatten;\n","var baseFlatten = require('./_baseFlatten');\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nmodule.exports = flatten;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var flatten = require('./flatten'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\nfunction flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n}\n\nmodule.exports = flatRest;\n","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n","'use strict';\n\nvar bind = require('./helpers/bind');\nvar isBuffer = require('is-buffer');\n\n/*global toString:true*/\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (typeof result[key] === 'object' && typeof val === 'object') {\n result[key] = merge(result[key], val);\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%40/gi, '@').\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n }\n\n if (!utils.isArray(val)) {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction E() {\n this.message = 'String contains an invalid character';\n}\nE.prototype = new Error;\nE.prototype.code = 5;\nE.prototype.name = 'InvalidCharacterError';\n\nfunction btoa(input) {\n var str = String(input);\n var output = '';\n for (\n // initialize result and counter\n var block, charCode, idx = 0, map = chars;\n // if the next str index does not exist:\n // change the mapping table to \"=\"\n // check if d has no fractional digits\n str.charAt(idx | 0) || (map = '=', idx % 1);\n // \"8 - idx % 1 * 8\" generates the sequence 2, 4, 6, 8\n output += map.charAt(63 & block >> 8 - idx % 1 * 8)\n ) {\n charCode = str.charCodeAt(idx += 3 / 4);\n if (charCode > 0xFF) {\n throw new E();\n }\n block = block << 8 | charCode;\n }\n return output;\n}\n\nmodule.exports = btoa;\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nvar defaults = {\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Content-Type');\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data)) {\n setContentTypeIfUnset(headers, 'application/json;charset=utf-8');\n return JSON.stringify(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n /*eslint no-param-reassign:0*/\n if (typeof data === 'string') {\n try {\n data = JSON.parse(data);\n } catch (e) { /* Ignore */ }\n }\n return data;\n }],\n\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar isAbsoluteURL = require('./../helpers/isAbsoluteURL');\nvar combineURLs = require('./../helpers/combineURLs');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Support baseURL config\n if (config.baseURL && !isAbsoluteURL(config.url)) {\n config.url = combineURLs(config.baseURL, config.url);\n }\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData(\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers || {}\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData(\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData(\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar defaults = require('./../defaults');\nvar utils = require('./../utils');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = utils.merge({\n url: arguments[0]\n }, arguments[1]);\n }\n\n config = utils.merge(defaults, this.defaults, { method: 'get' }, config);\n config.method = config.method.toLowerCase();\n\n // Hook up interceptors middleware\n var chain = [dispatchRequest, undefined];\n var promise = Promise.resolve(config);\n\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n chain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n chain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(utils.merge(defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n nativeMax = Math.max;\n\n/**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\nfunction baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n}\n\nmodule.exports = baseRange;\n","var baseRange = require('./_baseRange'),\n isIterateeCall = require('./_isIterateeCall'),\n toFinite = require('./toFinite');\n\n/**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\nfunction createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n}\n\nmodule.exports = createRange;\n","\"use strict\"\n\nfunction iota(n) {\n var result = new Array(n)\n for(var i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})\")\n } else if(dimension === 3) {\n code.push(\n\"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\\\nif(s0>s1){\\\nif(s1>s2){\\\nreturn [2,1,0];\\\n}else if(s0>s2){\\\nreturn [1,2,0];\\\n}else{\\\nreturn [1,0,2];\\\n}\\\n}else if(s0>s2){\\\nreturn [2,0,1];\\\n}else if(s2>s1){\\\nreturn [0,1,2];\\\n}else{\\\nreturn [0,2,1];\\\n}}})\")\n }\n } else {\n code.push(\"ORDER})\")\n }\n }\n\n //view.set(i0, ..., v):\n code.push(\n\"proto.set=function \"+className+\"_set(\"+args.join(\",\")+\",v){\")\n if(useGetters) {\n code.push(\"return this.data.set(\"+index_str+\",v)}\")\n } else {\n code.push(\"return this.data[\"+index_str+\"]=v}\")\n }\n\n //view.get(i0, ...):\n code.push(\"proto.get=function \"+className+\"_get(\"+args.join(\",\")+\"){\")\n if(useGetters) {\n code.push(\"return this.data.get(\"+index_str+\")}\")\n } else {\n code.push(\"return this.data[\"+index_str+\"]}\")\n }\n\n //view.index:\n code.push(\n \"proto.index=function \"+className+\"_index(\", args.join(), \"){return \"+index_str+\"}\")\n\n //view.hi():\n code.push(\"proto.hi=function \"+className+\"_hi(\"+args.join(\",\")+\"){return new \"+className+\"(this.data,\"+\n indices.map(function(i) {\n return [\"(typeof i\",i,\"!=='number'||i\",i,\"<0)?this.shape[\", i, \"]:i\", i,\"|0\"].join(\"\")\n }).join(\",\")+\",\"+\n indices.map(function(i) {\n return \"this.stride[\"+i + \"]\"\n }).join(\",\")+\",this.offset)}\")\n\n //view.lo():\n var a_vars = indices.map(function(i) { return \"a\"+i+\"=this.shape[\"+i+\"]\" })\n var c_vars = indices.map(function(i) { return \"c\"+i+\"=this.stride[\"+i+\"]\" })\n code.push(\"proto.lo=function \"+className+\"_lo(\"+args.join(\",\")+\"){var b=this.offset,d=0,\"+a_vars.join(\",\")+\",\"+c_vars.join(\",\"))\n for(var i=0; i=0){\\\nd=i\"+i+\"|0;\\\nb+=c\"+i+\"*d;\\\na\"+i+\"-=d}\")\n }\n code.push(\"return new \"+className+\"(this.data,\"+\n indices.map(function(i) {\n return \"a\"+i\n }).join(\",\")+\",\"+\n indices.map(function(i) {\n return \"c\"+i\n }).join(\",\")+\",b)}\")\n\n //view.step():\n code.push(\"proto.step=function \"+className+\"_step(\"+args.join(\",\")+\"){var \"+\n indices.map(function(i) {\n return \"a\"+i+\"=this.shape[\"+i+\"]\"\n }).join(\",\")+\",\"+\n indices.map(function(i) {\n return \"b\"+i+\"=this.stride[\"+i+\"]\"\n }).join(\",\")+\",c=this.offset,d=0,ceil=Math.ceil\")\n for(var i=0; i=0){c=(c+this.stride[\"+i+\"]*i\"+i+\")|0}else{a.push(this.shape[\"+i+\"]);b.push(this.stride[\"+i+\"])}\")\n }\n code.push(\"var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}\")\n\n //Add return statement\n code.push(\"return function construct_\"+className+\"(data,shape,stride,offset){return new \"+className+\"(data,\"+\n indices.map(function(i) {\n return \"shape[\"+i+\"]\"\n }).join(\",\")+\",\"+\n indices.map(function(i) {\n return \"stride[\"+i+\"]\"\n }).join(\",\")+\",offset)}\")\n\n //Compile procedure\n var procedure = new Function(\"CTOR_LIST\", \"ORDER\", code.join(\"\\n\"))\n return procedure(CACHED_CONSTRUCTORS[dtype], order)\n}\n\nfunction arrayDType(data) {\n if(isBuffer(data)) {\n return \"buffer\"\n }\n if(hasTypedArrays) {\n switch(Object.prototype.toString.call(data)) {\n case \"[object Float64Array]\":\n return \"float64\"\n case \"[object Float32Array]\":\n return \"float32\"\n case \"[object Int8Array]\":\n return \"int8\"\n case \"[object Int16Array]\":\n return \"int16\"\n case \"[object Int32Array]\":\n return \"int32\"\n case \"[object Uint8Array]\":\n return \"uint8\"\n case \"[object Uint16Array]\":\n return \"uint16\"\n case \"[object Uint32Array]\":\n return \"uint32\"\n case \"[object Uint8ClampedArray]\":\n return \"uint8_clamped\"\n }\n }\n if(Array.isArray(data)) {\n return \"array\"\n }\n return \"generic\"\n}\n\nvar CACHED_CONSTRUCTORS = {\n \"float32\":[],\n \"float64\":[],\n \"int8\":[],\n \"int16\":[],\n \"int32\":[],\n \"uint8\":[],\n \"uint16\":[],\n \"uint32\":[],\n \"array\":[],\n \"uint8_clamped\":[],\n \"buffer\":[],\n \"generic\":[]\n}\n\n;(function() {\n for(var id in CACHED_CONSTRUCTORS) {\n CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))\n }\n});\n\nfunction wrappedNDArrayCtor(data, shape, stride, offset) {\n if(data === undefined) {\n var ctor = CACHED_CONSTRUCTORS.array[0]\n return ctor([])\n } else if(typeof data === \"number\") {\n data = [data]\n }\n if(shape === undefined) {\n shape = [ data.length ]\n }\n var d = shape.length\n if(stride === undefined) {\n stride = new Array(d)\n for(var i=d-1, sz=1; i>=0; --i) {\n stride[i] = sz\n sz *= shape[i]\n }\n }\n if(offset === undefined) {\n offset = 0\n for(var i=0; i0\n , code = []\n , vars = []\n , idx=0, pidx=0, i, j\n for(i=0; i 0) {\n code.push(\"var \" + vars.join(\",\"))\n } \n //Scan loop\n for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards\n idx = order[i]\n code.push([\"for(i\",i,\"=0;i\",i,\" 0) {\n code.push([\"index[\",pidx,\"]-=s\",pidx].join(\"\"))\n }\n code.push([\"++index[\",idx,\"]\"].join(\"\"))\n }\n code.push(\"}\")\n }\n return code.join(\"\\n\")\n}\n\n// Generate \"outer\" loops that loop over blocks of data, applying \"inner\" loops to the blocks by manipulating the local variables in such a way that the inner loop only \"sees\" the current block.\n// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary.\n// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and \"shape\" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used.\nfunction outerFill(matched, order, proc, body) {\n var dimension = order.length\n , nargs = proc.arrayArgs.length\n , blockSize = proc.blockSize\n , has_index = proc.indexArgs.length > 0\n , code = []\n for(var i=0; i0;){\"].join(\"\")) // Iterate back to front\n code.push([\"if(j\",i,\"<\",blockSize,\"){\"].join(\"\")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j).\n code.push([\"s\",order[i],\"=j\",i].join(\"\"))\n code.push([\"j\",i,\"=0\"].join(\"\"))\n code.push([\"}else{s\",order[i],\"=\",blockSize].join(\"\"))\n code.push([\"j\",i,\"-=\",blockSize,\"}\"].join(\"\"))\n if(has_index) {\n code.push([\"index[\",order[i],\"]=j\",i].join(\"\"))\n }\n }\n for(var i=0; i 0) {\n allEqual = allEqual && summary[i] === summary[i-1]\n }\n }\n if(allEqual) {\n return summary[0]\n }\n return summary.join(\"\")\n}\n\n//Generates a cwise operator\nfunction generateCWiseOp(proc, typesig) {\n\n //Compute dimension\n // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg.\n var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0\n var orders = new Array(proc.arrayArgs.length)\n var dtypes = new Array(proc.arrayArgs.length)\n for(var i=0; i 0) {\n vars.push(\"shape=SS.slice(0)\") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example)\n }\n if(proc.indexArgs.length > 0) {\n // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes.\n var zeros = new Array(dimension)\n for(var i=0; i 0) {\n code.push(\"var \" + vars.join(\",\"))\n }\n for(var i=0; i 3) {\n code.push(processBlock(proc.pre, proc, dtypes))\n }\n\n //Process body\n var body = processBlock(proc.body, proc, dtypes)\n var matched = countMatches(loopOrders)\n if(matched < dimension) {\n code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example.\n } else {\n code.push(innerFill(loopOrders[0], proc, body))\n }\n\n //Inline epilog\n if(proc.post.body.length > 3) {\n code.push(processBlock(proc.post, proc, dtypes))\n }\n \n if(proc.debug) {\n console.log(\"-----Generated cwise routine for \", typesig, \":\\n\" + code.join(\"\\n\") + \"\\n----------\")\n }\n \n var loopName = [(proc.funcName||\"unnamed\"), \"_cwise_loop_\", orders[0].join(\"s\"),\"m\",matched,typeSummary(dtypes)].join(\"\")\n var f = new Function([\"function \",loopName,\"(\", arglist.join(\",\"),\"){\", code.join(\"\\n\"),\"} return \", loopName].join(\"\"))\n return f()\n}\nmodule.exports = generateCWiseOp\n","\"use strict\"\n\n// The function below is called when constructing a cwise function object, and does the following:\n// A function object is constructed which accepts as argument a compilation function and returns another function.\n// It is this other function that is eventually returned by createThunk, and this function is the one that actually\n// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed.\n// The compilation passed to the first function object is used for compiling new functions.\n// Once this function object is created, it is called with compile as argument, where the first argument of compile\n// is bound to \"proc\" (essentially containing a preprocessed version of the user arguments to cwise).\n// So createThunk roughly works like this:\n// function createThunk(proc) {\n// var thunk = function(compileBound) {\n// var CACHED = {}\n// return function(arrays and scalars) {\n// if (dtype and order of arrays in CACHED) {\n// var func = CACHED[dtype and order of arrays]\n// } else {\n// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays)\n// }\n// return func(arrays and scalars)\n// }\n// }\n// return thunk(compile.bind1(proc))\n// }\n\nvar compile = require(\"./compile.js\")\n\nfunction createThunk(proc) {\n var code = [\"'use strict'\", \"var CACHED={}\"]\n var vars = []\n var thunkName = proc.funcName + \"_cwise_thunk\"\n \n //Build thunk\n code.push([\"return function \", thunkName, \"(\", proc.shimArgs.join(\",\"), \"){\"].join(\"\"))\n var typesig = []\n var string_typesig = []\n var proc_args = [[\"array\",proc.arrayArgs[0],\".shape.slice(\", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS).\n Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(\",\"+proc.arrayBlockIndices[0]+\")\"):\")\"].join(\"\")]\n var shapeLengthConditions = [], shapeConditions = []\n // Process array arguments\n for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices)\n shapeLengthConditions.push(\"array\" + proc.arrayArgs[0] + \".shape.length===array\" + j + \".shape.length+\" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i])))\n shapeConditions.push(\"array\" + proc.arrayArgs[0] + \".shape[shapeIndex+\" + Math.max(0,proc.arrayBlockIndices[0]) + \"]===array\" + j + \".shape[shapeIndex+\" + Math.max(0,proc.arrayBlockIndices[i]) + \"]\")\n }\n }\n // Check for shape equality\n if (proc.arrayArgs.length > 1) {\n code.push(\"if (!(\" + shapeLengthConditions.join(\" && \") + \")) throw new Error('cwise: Arrays do not all have the same dimensionality!')\")\n code.push(\"for(var shapeIndex=array\" + proc.arrayArgs[0] + \".shape.length-\" + Math.abs(proc.arrayBlockIndices[0]) + \"; shapeIndex-->0;) {\")\n code.push(\"if (!(\" + shapeConditions.join(\" && \") + \")) throw new Error('cwise: Arrays do not all have the same shape!')\")\n code.push(\"}\")\n }\n // Process scalar arguments\n for(var i=0; i0) {\n throw new Error(\"cwise: pre() block may not reference array args\")\n }\n if(i < proc.post.args.length && proc.post.args[i].count>0) {\n throw new Error(\"cwise: post() block may not reference array args\")\n }\n } else if(arg_type === \"scalar\") {\n proc.scalarArgs.push(i)\n proc.shimArgs.push(\"scalar\" + i)\n } else if(arg_type === \"index\") {\n proc.indexArgs.push(i)\n if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {\n throw new Error(\"cwise: pre() block may not reference array index\")\n }\n if(i < proc.body.args.length && proc.body.args[i].lvalue) {\n throw new Error(\"cwise: body() block may not write to array index\")\n }\n if(i < proc.post.args.length && proc.post.args[i].count > 0) {\n throw new Error(\"cwise: post() block may not reference array index\")\n }\n } else if(arg_type === \"shape\") {\n proc.shapeArgs.push(i)\n if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {\n throw new Error(\"cwise: pre() block may not write to array shape\")\n }\n if(i < proc.body.args.length && proc.body.args[i].lvalue) {\n throw new Error(\"cwise: body() block may not write to array shape\")\n }\n if(i < proc.post.args.length && proc.post.args[i].lvalue) {\n throw new Error(\"cwise: post() block may not write to array shape\")\n }\n } else if(typeof arg_type === \"object\" && arg_type.offset) {\n proc.argTypes[i] = \"offset\"\n proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })\n proc.offsetArgIndex.push(i)\n } else {\n throw new Error(\"cwise: Unknown argument type \" + proc_args[i])\n }\n }\n \n //Make sure at least one array argument was specified\n if(proc.arrayArgs.length <= 0) {\n throw new Error(\"cwise: No array arguments specified\")\n }\n \n //Make sure arguments are correct\n if(proc.pre.args.length > proc_args.length) {\n throw new Error(\"cwise: Too many arguments in pre() block\")\n }\n if(proc.body.args.length > proc_args.length) {\n throw new Error(\"cwise: Too many arguments in body() block\")\n }\n if(proc.post.args.length > proc_args.length) {\n throw new Error(\"cwise: Too many arguments in post() block\")\n }\n\n //Check debug flag\n proc.debug = !!user_args.printCode || !!user_args.debug\n \n //Retrieve name\n proc.funcName = user_args.funcName || \"cwise\"\n \n //Read in block size\n proc.blockSize = user_args.blockSize || 64\n\n return createThunk(proc)\n}\n\nmodule.exports = compileCwise\n","'use strict'\n\nvar ndarray = require('ndarray')\n\nmodule.exports = squeeze\n\nfunction squeeze (a, axes) {\n var i\n var shape = []\n var stride = []\n\n if (axes !== undefined && !Array.isArray(axes)) {\n throw new Error('axes must be an Array list of dimensions to squeeze')\n }\n\n for (i = 0; i < a.shape.length; i++) {\n if (a.shape[i] !== 1 || (axes !== undefined && axes.indexOf(i) === -1)) {\n shape.push(a.shape[i])\n stride.push(a.stride[i])\n }\n }\n\n return ndarray(a.data, shape, stride, a.offset)\n}\n","\"use strict\"\n\nvar esprima = require(\"esprima\")\nvar uniq = require(\"uniq\")\n\nvar PREFIX_COUNTER = 0\n\nfunction CompiledArgument(name, lvalue, rvalue) {\n this.name = name\n this.lvalue = lvalue\n this.rvalue = rvalue\n this.count = 0\n}\n\nfunction CompiledRoutine(body, args, thisVars, localVars) {\n this.body = body\n this.args = args\n this.thisVars = thisVars\n this.localVars = localVars\n}\n\nfunction isGlobal(identifier) {\n if(identifier === \"eval\") {\n throw new Error(\"cwise-parser: eval() not allowed\")\n }\n if(typeof window !== \"undefined\") {\n return identifier in window\n } else if(typeof global !== \"undefined\") {\n return identifier in global\n } else if(typeof self !== \"undefined\") {\n return identifier in self\n } else {\n return false\n }\n}\n\nfunction getArgNames(ast) {\n var params = ast.body[0].expression.callee.params\n var names = new Array(params.length)\n for(var i=0; i= 0) {\n var carg = compiledArgs[argNo]\n var usage = getUsage(node)\n if(usage & LVALUE) {\n carg.lvalue = true\n }\n if(usage & RVALUE) {\n carg.rvalue = true\n }\n ++carg.count\n rewrite(node, carg.name)\n } else if(isGlobal(name)) {\n //Don't rewrite globals\n } else {\n rewrite(node, createLocal(name))\n }\n } else if(node.type === \"Literal\") {\n if(typeof node.value === \"string\") {\n rewrite(node, escapeString(node.value))\n }\n } else if(node.type === \"WithStatement\") {\n throw new Error(\"cwise-parser: with() statements not allowed\")\n } else {\n //Visit all children\n var keys = Object.keys(node)\n for(var i=0, n=keys.length; i length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nmodule.exports = baseSlice;\n","var baseSlice = require('./_baseSlice'),\n toInteger = require('./toInteger');\n\n/**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\nfunction take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n}\n\nmodule.exports = take;\n","/**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\nfunction baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n}\n\nmodule.exports = baseSum;\n","var baseSum = require('./_baseSum'),\n identity = require('./identity');\n\n/**\n * Computes the sum of the values in `array`.\n *\n * @static\n * @memberOf _\n * @since 3.4.0\n * @category Math\n * @param {Array} array The array to iterate over.\n * @returns {number} Returns the sum.\n * @example\n *\n * _.sum([4, 2, 8, 6]);\n * // => 20\n */\nfunction sum(array) {\n return (array && array.length)\n ? baseSum(array, identity)\n : 0;\n}\n\nmodule.exports = sum;\n","\"use strict\"\n\nmodule.exports = generateMatrixProduct\n\nvar BLOCK_SIZE = 32\n\nfunction unpackOrder(order) {\n return order === \"r\" ? [1,0] : [0,1]\n}\n\nfunction unpackShape(name, type) {\n if(type[1] === \"native\") {\n return [\n name, \"d0=\", name, \".length,\",\n name, \"d1=\", name, \"[0].length,\"\n ].join(\"\")\n } else {\n return [\n name, \"d0=\", name, \".shape[0],\",\n name, \"d1=\", name, \".shape[1],\",\n name, \"s0=\", name, \".stride[0],\",\n name, \"s1=\", name, \".stride[1],\",\n name, \"o=\", name, \".offset,\",\n name, \"d=\", name, \".data,\"\n ].join(\"\")\n }\n}\n\nfunction start(order, name, type, i, j, w) {\n var code = []\n if(type[1] === \"native\") {\n if(order[0]) {\n if(i) {\n code.push(\"var \", name, \"p=\", name, \"[\", i, \"];\")\n } else {\n code.push(\"var \", name, \"p=\", name, \"[0];\")\n }\n }\n } else {\n if(i && j) {\n if(w) {\n code.push(\n \"var \", name, \"t0=\", name, \"s\", order[0], \",\",\n name, \"t1=\", name, \"s\", order[1], \"-\", name, \"s\", order[0], \"*\", w, \",\",\n name, \"p=\", name, \"o+\", i, \"*\", name, \"s0+\", j, \"*\", name, \"s1;\")\n } else {\n code.push(\n \"var \", name, \"t0=\", name, \"s\", order[0], \",\",\n name, \"p=\", name, \"o+\", i, \"*\", name, \"s0+\", j, \"*\", name, \"s1;\")\n }\n } else if(i) {\n code.push(\n \"var \", name, \"t0=\", name, \"s\", order[0], \",\",\n name, \"p=\", name, \"o+\", i, \"*\", name, \"s0;\")\n } else if(j) {\n code.push(\n \"var \", name, \"t0=\", name, \"s\", order[0], \",\",\n name, \"p=\", name, \"o+\", j, \"*\", name, \"s1;\")\n } else {\n code.push(\n \"var \", name, \"t0=\", name, \"s\", order[0], \",\",\n name, \"t1=\", name, \"s\", order[1], \"-\", name, \"s\", order[0], \"*\", name, \"d\", order[0], \",\",\n name, \"p=\", name, \"o;\")\n }\n }\n return code\n}\n\nfunction walk(order, name, type, d, i) {\n var code = []\n if(type[1] === \"native\") {\n if(order[0] && d === 1) {\n code.push(name, \"p=\", name, \"[\", i, \"+1]\")\n }\n } else {\n code.push(name, \"p+=\", name, \"t\", d, \";\")\n }\n return code\n}\n\nfunction write(order, name, type, i, j, w) {\n var code = []\n if(type[1] === \"native\") {\n if(order[0]) {\n code.push(name, \"p[\", j, \"]=\", w, \";\")\n } else {\n code.push(name, \"[\", i, \"][\", j, \"]=\", w, \";\")\n }\n } else if(type[1] === \"generic\") {\n code.push(name, \"d.set(\", name, \"p,\", w, \");\")\n } else {\n code.push(name, \"d[\", name, \"p]=\", w, \";\")\n }\n return code\n}\n\nfunction read(order, name, type, i, j) {\n var code = []\n if(type[1] === \"native\") {\n if(order[0]) {\n code.push(name, \"p[\", j, \"]\")\n } else {\n code.push(name, \"[\", i, \"][\", j, \"]\")\n }\n } else if(type[1] === \"generic\") {\n code.push(name, \"d.get(\", name, \"p)\")\n } else {\n code.push(name, \"d[\", name, \"p]\")\n }\n return code.join(\"\")\n}\n\nfunction generateRowColumnLoop(oType, aType, bType, useAlpha, useBeta) {\n var code = []\n var oOrd = oType[0] === \"r\" ? [1,0] : [0,1], aOrd = [1, 0], bOrd = [0, 1]\n var symbols = [\"i\", \"j\"]\n\n code.push.apply(code, start(oOrd, \"o\", oType))\n \n if(oOrd[1]) {\n code.push(\"for(j=0;j0;){\",\n \"var w\", i, \"=\", BLOCK_SIZE, \";\",\n \"if(i\", i, \"<\", BLOCK_SIZE, \"){\",\n \"w\", i, \"=i\", i, \";\",\n \"i\", i, \"=0;\",\n \"}else{\",\n \"i\", i, \"-=\", BLOCK_SIZE, \";\",\n \"}\")\n }\n\n code.push.apply(code, start(oOrd, \"o\", oType, \"i0\", \"i1\", \"w1\"))\n \n code.push(\"for(i=0;i= 0; i--) {\n y.set(i, y.get(i) * beta + alpha * dot(A.pick(i, null), x));\n }\n return true;\n}\n","'use strict';\n\nmodule.exports = gbmv;\n\nfunction gbmv (A, kl, ku, x, y, alpha, beta) {\n var r = 0;\n var i = 0;\n var c = 0;\n var sum = 0;\n var idx = 0;\n var m = A.shape[0];\n var n = A.shape[1];\n var Kl = Math.min(kl, m - 1);\n var Ku = Math.min(ku, n - 1);\n\n var alpha0 = alpha === undefined ? 1 : alpha;\n var beta0 = beta === undefined ? 0 : beta;\n\n while (r <= Kl) {\n sum = 0;\n var max = Math.min(r + Ku, n - 1);\n for (c = 0; c <= max; c++) {\n sum += A.get(r, c) * x.get(c);\n }\n y.set(r, sum * alpha0 + beta0 * y.get(r));\n r++;\n }\n if (r < m) {\n i = 0;\n while (r + Ku < n) {\n sum = 0;\n for (c = 0; c <= Kl + Ku; c++) {\n idx = i + c + 1;\n sum += A.get(r, idx) * x.get(idx);\n }\n y.set(r, sum * alpha0 + beta0 * y.get(r));\n r++;\n i++;\n if (r === m) {\n break;\n }\n }\n }\n if (r < m) {\n i++;\n while (r - Kl < n) {\n sum = 0;\n for (c = i; c < n; c++) {\n sum += A.get(r, c) * x.get(c);\n }\n y.set(r, sum * alpha0 + beta0 * y.get(r));\n r++;\n i++;\n if (r === m) {\n break;\n }\n }\n }\n return true;\n}\n","'use strict';\n\nvar blas1 = require('ndarray-blas-level1');\n\nmodule.exports = symv;\n\nfunction symv (A, x, y, fromLower, alpha, beta) {\n var n = A.shape[0];\n\n var lower = fromLower || true;\n var alpha0 = alpha === undefined ? 1 : alpha;\n var beta0 = beta === undefined ? 0 : beta;\n\n var i = 0;\n var j = 0;\n var t1 = 0;\n var t2 = 0;\n\n if (beta0 === 0) {\n for (i = 0; i < y.shape[0]; ++i) {\n y.set(i, 0);\n }\n } else if (beta0 !== 1) {\n blas1.scal(beta0, y);\n }\n if (alpha0 === 0) {\n return true;\n } else if (alpha0 === 1) {\n if (lower) {\n for (j = 0; j < n; ++j) {\n t1 = x.get(j);\n t2 = 0;\n y.set(j, y.get(j) + t1 * A.get(j, j));\n for (i = j + 1; i < n; ++i) {\n y.set(i, y.get(i) + t1 * A.get(i, j));\n t2 = t2 + A.get(i, j) * x.get(i);\n }\n y.set(j, y.get(j) + t2);\n }\n } else {\n for (j = 0; j < n; ++j) {\n t1 = x.get(j);\n t2 = 0;\n for (i = 0; i <= j - 1; ++i) {\n y.set(i, y.get(i) + t1 * A.get(i, j));\n t2 = t2 + A.get(i, j) * x.get(i);\n }\n y.set(j, y.get(j) + t1 * A.get(j, j) + t2);\n }\n }\n } else {\n if (lower) {\n for (j = 0; j < n; ++j) {\n t1 = alpha0 * x.get(j);\n t2 = 0;\n y.set(j, y.get(j) + t1 * A.get(j, j));\n for (i = j + 1; i < n; ++i) {\n y.set(i, y.get(i) + t1 * A.get(i, j));\n t2 = t2 + A.get(i, j) * x.get(i);\n }\n y.set(j, y.get(j) + alpha0 * t2);\n }\n } else {\n for (j = 0; j < n; ++j) {\n t1 = alpha0 * x.get(j);\n t2 = 0;\n for (i = 0; i <= j - 1; ++i) {\n y.set(i, y.get(i) + t1 * A.get(i, j));\n t2 = t2 + A.get(i, j) * x.get(i);\n }\n y.set(j, y.get(j) + t1 * A.get(j, j) + alpha0 * t2);\n }\n }\n }\n\n return true;\n}\n","'use strict';\n\nmodule.exports = sbmv;\n\nfunction sbmv () {\n console.error('SBMV (symmetric banded matrix vector multiply) not yet implemented');\n}\n","'use strict';\n\nvar blas1 = require('ndarray-blas-level1');\n\nmodule.exports = trmv;\n\n// Compute the product of an upper triangular matrix with a vector\nfunction trmv (A, x, isLower) {\n var dot = blas1.dot;\n var n = A.shape[1];\n var i = 0;\n if (isLower) {\n for (i = n - 1; i >= 0; i--) {\n x.set(i, dot(A.pick(i, null).hi(i + 1), x.hi(i + 1)));\n }\n } else {\n for (i = 0; i < n; i++) {\n x.set(i, dot(A.pick(i, null).lo(i), x.lo(i)));\n }\n }\n return true;\n}\n","'use strict';\n\nmodule.exports = tbmv;\n\nfunction tbmv () {\n console.error('TBMV (triangular banded matrix vector multiply) not yet implemented');\n}\n","'use strict';\n\nvar blas1 = require('ndarray-blas-level1');\n\nmodule.exports = trsv;\n\n// Solve Ax=b where A is upper triangular\nfunction trsv (A, x, isLower) {\n var dot = blas1.dot;\n var n = A.shape[1];\n var i = 0;\n if (isLower) {\n x.set(0, x.get(0) / A.get(0, 0));\n for (i = 1; i < n; i++) {\n x.set(i, (x.get(i) - dot(A.pick(i, null).hi(i), x.hi(i))) / A.get(i, i));\n }\n } else {\n x.set(n - 1, x.get(n - 1) / A.get(n - 1, n - 1));\n for (i = n - 2; i >= 0; i--) {\n x.set(i, (x.get(i) - dot(A.pick(i, null).lo(i + 1), x.lo(i + 1))) / A.get(i, i));\n }\n }\n return true;\n}\n","'use strict';\n\nmodule.exports = tpsv;\n\nfunction tpsv () {\n console.error('TPSV (triangular packed matrix solver) not yet implemented');\n}\n","'use strict';\n\nmodule.exports = ger;\n\nfunction ger () {\n console.error('GER (rank 1 operation A := alpha*x*y\\' + A) not yet implemented');\n}\n","'use strict';\n\nmodule.exports = syr;\n\nfunction syr () {\n console.error('SYR (symmetric rank 1 operation A := alpha*x*y\\' + A) not yet implemented');\n}\n","'use strict';\n\nmodule.exports = spr;\n\nfunction spr () {\n console.error('SPR (symmetric packed rank 1 operation A := alpha*x*y\\' + A) not yet implemented');\n}\n","'use strict';\n\nmodule.exports = syr2;\n\nfunction syr2 () {\n console.error('SYR (symmetric rank 2 operation A := alpha*x*y\\' + alpha*y*x\\' + A) not yet implemented');\n}\n","'use strict';\n\nmodule.exports = spr2;\n\nfunction spr2 () {\n console.error('SPR (symmetric packed rank 2 operation A := alpha*x*y\\' + alpha*y*x\\' + A) not yet implemented');\n}\n","/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nmodule.exports = last;\n","/**\n * Bit twiddling hacks for JavaScript.\n *\n * Author: Mikola Lysenko\n *\n * Ported from Stanford bit twiddling hack library:\n * http://graphics.stanford.edu/~seander/bithacks.html\n */\n\n\"use strict\"; \"use restrict\";\n\n//Number of bits in an integer\nvar INT_BITS = 32;\n\n//Constants\nexports.INT_BITS = INT_BITS;\nexports.INT_MAX = 0x7fffffff;\nexports.INT_MIN = -1<<(INT_BITS-1);\n\n//Returns -1, 0, +1 depending on sign of x\nexports.sign = function(v) {\n return (v > 0) - (v < 0);\n}\n\n//Computes absolute value of integer\nexports.abs = function(v) {\n var mask = v >> (INT_BITS-1);\n return (v ^ mask) - mask;\n}\n\n//Computes minimum of integers x and y\nexports.min = function(x, y) {\n return y ^ ((x ^ y) & -(x < y));\n}\n\n//Computes maximum of integers x and y\nexports.max = function(x, y) {\n return x ^ ((x ^ y) & -(x < y));\n}\n\n//Checks if a number is a power of two\nexports.isPow2 = function(v) {\n return !(v & (v-1)) && (!!v);\n}\n\n//Computes log base 2 of v\nexports.log2 = function(v) {\n var r, shift;\n r = (v > 0xFFFF) << 4; v >>>= r;\n shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift;\n shift = (v > 0xF ) << 2; v >>>= shift; r |= shift;\n shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift;\n return r | (v >> 1);\n}\n\n//Computes log base 10 of v\nexports.log10 = function(v) {\n return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :\n (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :\n (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;\n}\n\n//Counts number of bits\nexports.popCount = function(v) {\n v = v - ((v >>> 1) & 0x55555555);\n v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);\n return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;\n}\n\n//Counts number of trailing zeros\nfunction countTrailingZeros(v) {\n var c = 32;\n v &= -v;\n if (v) c--;\n if (v & 0x0000FFFF) c -= 16;\n if (v & 0x00FF00FF) c -= 8;\n if (v & 0x0F0F0F0F) c -= 4;\n if (v & 0x33333333) c -= 2;\n if (v & 0x55555555) c -= 1;\n return c;\n}\nexports.countTrailingZeros = countTrailingZeros;\n\n//Rounds to next power of 2\nexports.nextPow2 = function(v) {\n v += v === 0;\n --v;\n v |= v >>> 1;\n v |= v >>> 2;\n v |= v >>> 4;\n v |= v >>> 8;\n v |= v >>> 16;\n return v + 1;\n}\n\n//Rounds down to previous power of 2\nexports.prevPow2 = function(v) {\n v |= v >>> 1;\n v |= v >>> 2;\n v |= v >>> 4;\n v |= v >>> 8;\n v |= v >>> 16;\n return v - (v>>>1);\n}\n\n//Computes parity of word\nexports.parity = function(v) {\n v ^= v >>> 16;\n v ^= v >>> 8;\n v ^= v >>> 4;\n v &= 0xf;\n return (0x6996 >>> v) & 1;\n}\n\nvar REVERSE_TABLE = new Array(256);\n\n(function(tab) {\n for(var i=0; i<256; ++i) {\n var v = i, r = i, s = 7;\n for (v >>>= 1; v; v >>>= 1) {\n r <<= 1;\n r |= v & 1;\n --s;\n }\n tab[i] = (r << s) & 0xff;\n }\n})(REVERSE_TABLE);\n\n//Reverse bits in a 32 bit word\nexports.reverse = function(v) {\n return (REVERSE_TABLE[ v & 0xff] << 24) |\n (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) |\n (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) |\n REVERSE_TABLE[(v >>> 24) & 0xff];\n}\n\n//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes\nexports.interleave2 = function(x, y) {\n x &= 0xFFFF;\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y &= 0xFFFF;\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n//Extracts the nth interleaved component\nexports.deinterleave2 = function(v, n) {\n v = (v >>> n) & 0x55555555;\n v = (v | (v >>> 1)) & 0x33333333;\n v = (v | (v >>> 2)) & 0x0F0F0F0F;\n v = (v | (v >>> 4)) & 0x00FF00FF;\n v = (v | (v >>> 16)) & 0x000FFFF;\n return (v << 16) >> 16;\n}\n\n\n//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes\nexports.interleave3 = function(x, y, z) {\n x &= 0x3FF;\n x = (x | (x<<16)) & 4278190335;\n x = (x | (x<<8)) & 251719695;\n x = (x | (x<<4)) & 3272356035;\n x = (x | (x<<2)) & 1227133513;\n\n y &= 0x3FF;\n y = (y | (y<<16)) & 4278190335;\n y = (y | (y<<8)) & 251719695;\n y = (y | (y<<4)) & 3272356035;\n y = (y | (y<<2)) & 1227133513;\n x |= (y << 1);\n \n z &= 0x3FF;\n z = (z | (z<<16)) & 4278190335;\n z = (z | (z<<8)) & 251719695;\n z = (z | (z<<4)) & 3272356035;\n z = (z | (z<<2)) & 1227133513;\n \n return x | (z << 2);\n}\n\n//Extracts nth interleaved component of a 3-tuple\nexports.deinterleave3 = function(v, n) {\n v = (v >>> n) & 1227133513;\n v = (v | (v>>>2)) & 3272356035;\n v = (v | (v>>>4)) & 251719695;\n v = (v | (v>>>8)) & 4278190335;\n v = (v | (v>>>16)) & 0x3FF;\n return (v<<22)>>22;\n}\n\n//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)\nexports.nextCombination = function(v) {\n var t = v | (v - 1);\n return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));\n}\n\n","\"use strict\"\n\nfunction dupe_array(count, value, i) {\n var c = count[i]|0\n if(c <= 0) {\n return []\n }\n var result = new Array(c), j\n if(i === count.length-1) {\n for(j=0; j 0) {\n return dupe_number(count|0, value)\n }\n break\n case \"object\":\n if(typeof (count.length) === \"number\") {\n return dupe_array(count, value, 0)\n }\n break\n }\n return []\n}\n\nmodule.exports = dupe","\"use strict\"\n\nvar ndarray = require(\"ndarray\")\nvar ops = require(\"ndarray-ops\")\nvar pool = require(\"typedarray-pool\")\n\nfunction clone(array) {\n var dtype = array.dtype\n if(dtype === \"generic\" || dtype === \"array\") {\n dtype = \"double\"\n }\n var data = pool.malloc(array.size, dtype)\n var result = ndarray(data, array.shape)\n ops.assign(result, array)\n return result\n}\nexports.clone = clone\n\nfunction malloc(shape, dtype) {\n if(!dtype) {\n dtype = \"double\"\n }\n var sz = 1\n var stride = new Array(shape.length)\n for(var i=shape.length-1; i>=0; --i) {\n stride[i] = sz\n sz *= shape[i]\n }\n return ndarray(pool.malloc(sz, dtype), shape, stride, 0)\n}\nexports.malloc = malloc\n\nfunction free(array) {\n if(array.dtype === \"generic\" || array.dtype === \"array\") {\n return\n }\n pool.free(array.data)\n}\nexports.free = free\n\nfunction zeros(shape, dtype) {\n if(!dtype) {\n dtype = \"double\"\n }\n\n var sz = 1\n var stride = new Array(shape.length)\n for(var i=shape.length-1; i>=0; --i) {\n stride[i] = sz\n sz *= shape[i]\n }\n var buf = pool.malloc(sz, dtype)\n for(var i=0; i=0; --i) {\n stride[i] = sz\n sz *= shape[i]\n }\n var buf = pool.malloc(sz, dtype)\n for(var i=0; i=0; --i) {\n stride[i] = sz\n sz *= shape[i]\n }\n var buf = pool.malloc(sz, dtype)\n for(i=0; i=0; i--) {\n offsum += stride[i]\n mindim = Math.min(mindim,shape[i])\n }\n for(i=0,offset=0; i= 0) {\n origin[d] += inputShape[d]\n if (origin[d] === newShape[d]) {\n origin[d] = 0\n d--\n } else break\n }\n }\n\n return output\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = extend;\nfunction extend(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || typeof add !== 'object') return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n}\n","'use strict'\n\nmodule.exports = concatRows\nvar extend = require('util-extend')\nvar ops = require('ndarray-ops')\nvar pool = require('ndarray-scratch')\n\nvar defaults = {\n dtype: 'double'\n}\n\nfunction concatRows () {\n var output, input, inputs, options, d, i, shape, idx, l, slice\n\n options = extend({}, defaults)\n\n if (arguments.length === 0) {\n throw new Error('Array of ndarrays to concatenate must not be empty')\n }\n\n if (Array.isArray(arguments[0])) {\n // If the first argument is an array, then assume it's the list\n // of arrays to concatenate:\n inputs = arguments[0]\n extend(options, arguments[1] || {})\n } else if (arguments.length === 2) {\n // Otherwise assume the first argument is the output array:\n inputs = arguments[1]\n output = arguments[0]\n extend(options, arguments[2] || {})\n }\n\n if (inputs.length === 0) {\n throw new Error('Array of ndarrays to concatenate must not be empty')\n }\n\n for (d = 0; d < inputs.length; d++) {\n // Verify the other dimensions:\n if (!shape) {\n // If no shape is set, set it:\n shape = inputs[d].shape.slice(0)\n } else {\n // At the very least, all arrays must share teh same dimensionality:\n if (inputs[d].dimension !== shape.length) {\n throw new Error('all arrays must have the same dimensionality')\n }\n // If shape is set, then this shape must match:\n for (i = 1; i < inputs[d].shape.length; i++) {\n if (inputs[d].shape[i] !== shape[i]) {\n throw new Error('last n-1 dimensions of concatenated rows must have the same size')\n }\n }\n\n // Add to the size of the concatenated dimension:\n shape[0] += inputs[d].shape[0]\n }\n }\n\n if (output) {\n if (shape[0] !== output.shape[0]) {\n throw new Error('first dimension of output array must match the total number of concatenated rows')\n }\n } else {\n // NB: Nothing after this can fail, otherwise we leak memory. So all\n // assertions MUST happen before this.\n output = pool.zeros(shape, options.dtype)\n }\n\n for (i = 0, idx = 0; i < inputs.length; i++) {\n input = inputs[i]\n l = input.shape[0]\n slice = output.lo(idx).hi(l)\n ops.assign(slice, input)\n idx += l\n }\n\n return output\n}\n","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\nmodule.exports = LongBits;\r\n\r\nvar util = require(\"../util/minimal\");\r\n\r\n/**\r\n * Constructs new long bits.\r\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\r\n * @memberof util\r\n * @constructor\r\n * @param {number} lo Low 32 bits, unsigned\r\n * @param {number} hi High 32 bits, unsigned\r\n */\r\nfunction LongBits(lo, hi) {\r\n\r\n // note that the casts below are theoretically unnecessary as of today, but older statically\r\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\r\n\r\n /**\r\n * Low bits.\r\n * @type {number}\r\n */\r\n this.lo = lo >>> 0;\r\n\r\n /**\r\n * High bits.\r\n * @type {number}\r\n */\r\n this.hi = hi >>> 0;\r\n}\r\n\r\n/**\r\n * Zero bits.\r\n * @memberof util.LongBits\r\n * @type {util.LongBits}\r\n */\r\nvar zero = LongBits.zero = new LongBits(0, 0);\r\n\r\nzero.toNumber = function() { return 0; };\r\nzero.zzEncode = zero.zzDecode = function() { return this; };\r\nzero.length = function() { return 1; };\r\n\r\n/**\r\n * Zero hash.\r\n * @memberof util.LongBits\r\n * @type {string}\r\n */\r\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\r\n\r\n/**\r\n * Constructs new long bits from the specified number.\r\n * @param {number} value Value\r\n * @returns {util.LongBits} Instance\r\n */\r\nLongBits.fromNumber = function fromNumber(value) {\r\n if (value === 0)\r\n return zero;\r\n var sign = value < 0;\r\n if (sign)\r\n value = -value;\r\n var lo = value >>> 0,\r\n hi = (value - lo) / 4294967296 >>> 0;\r\n if (sign) {\r\n hi = ~hi >>> 0;\r\n lo = ~lo >>> 0;\r\n if (++lo > 4294967295) {\r\n lo = 0;\r\n if (++hi > 4294967295)\r\n hi = 0;\r\n }\r\n }\r\n return new LongBits(lo, hi);\r\n};\r\n\r\n/**\r\n * Constructs new long bits from a number, long or string.\r\n * @param {Long|number|string} value Value\r\n * @returns {util.LongBits} Instance\r\n */\r\nLongBits.from = function from(value) {\r\n if (typeof value === \"number\")\r\n return LongBits.fromNumber(value);\r\n if (util.isString(value)) {\r\n /* istanbul ignore else */\r\n if (util.Long)\r\n value = util.Long.fromString(value);\r\n else\r\n return LongBits.fromNumber(parseInt(value, 10));\r\n }\r\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\r\n};\r\n\r\n/**\r\n * Converts this long bits to a possibly unsafe JavaScript number.\r\n * @param {boolean} [unsigned=false] Whether unsigned or not\r\n * @returns {number} Possibly unsafe number\r\n */\r\nLongBits.prototype.toNumber = function toNumber(unsigned) {\r\n if (!unsigned && this.hi >>> 31) {\r\n var lo = ~this.lo + 1 >>> 0,\r\n hi = ~this.hi >>> 0;\r\n if (!lo)\r\n hi = hi + 1 >>> 0;\r\n return -(lo + hi * 4294967296);\r\n }\r\n return this.lo + this.hi * 4294967296;\r\n};\r\n\r\n/**\r\n * Converts this long bits to a long.\r\n * @param {boolean} [unsigned=false] Whether unsigned or not\r\n * @returns {Long} Long\r\n */\r\nLongBits.prototype.toLong = function toLong(unsigned) {\r\n return util.Long\r\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\r\n /* istanbul ignore next */\r\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\r\n};\r\n\r\nvar charCodeAt = String.prototype.charCodeAt;\r\n\r\n/**\r\n * Constructs new long bits from the specified 8 characters long hash.\r\n * @param {string} hash Hash\r\n * @returns {util.LongBits} Bits\r\n */\r\nLongBits.fromHash = function fromHash(hash) {\r\n if (hash === zeroHash)\r\n return zero;\r\n return new LongBits(\r\n ( charCodeAt.call(hash, 0)\r\n | charCodeAt.call(hash, 1) << 8\r\n | charCodeAt.call(hash, 2) << 16\r\n | charCodeAt.call(hash, 3) << 24) >>> 0\r\n ,\r\n ( charCodeAt.call(hash, 4)\r\n | charCodeAt.call(hash, 5) << 8\r\n | charCodeAt.call(hash, 6) << 16\r\n | charCodeAt.call(hash, 7) << 24) >>> 0\r\n );\r\n};\r\n\r\n/**\r\n * Converts this long bits to a 8 characters long hash.\r\n * @returns {string} Hash\r\n */\r\nLongBits.prototype.toHash = function toHash() {\r\n return String.fromCharCode(\r\n this.lo & 255,\r\n this.lo >>> 8 & 255,\r\n this.lo >>> 16 & 255,\r\n this.lo >>> 24 ,\r\n this.hi & 255,\r\n this.hi >>> 8 & 255,\r\n this.hi >>> 16 & 255,\r\n this.hi >>> 24\r\n );\r\n};\r\n\r\n/**\r\n * Zig-zag encodes this long bits.\r\n * @returns {util.LongBits} `this`\r\n */\r\nLongBits.prototype.zzEncode = function zzEncode() {\r\n var mask = this.hi >> 31;\r\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\r\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Zig-zag decodes this long bits.\r\n * @returns {util.LongBits} `this`\r\n */\r\nLongBits.prototype.zzDecode = function zzDecode() {\r\n var mask = -(this.lo & 1);\r\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\r\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Calculates the length of this longbits when encoded as a varint.\r\n * @returns {number} Length\r\n */\r\nLongBits.prototype.length = function length() {\r\n var part0 = this.lo,\r\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\r\n part2 = this.hi >>> 24;\r\n return part2 === 0\r\n ? part1 === 0\r\n ? part0 < 16384\r\n ? part0 < 128 ? 1 : 2\r\n : part0 < 2097152 ? 3 : 4\r\n : part1 < 16384\r\n ? part1 < 128 ? 5 : 6\r\n : part1 < 2097152 ? 7 : 8\r\n : part2 < 128 ? 9 : 10;\r\n};\r\n","\"use strict\";\r\nmodule.exports = Writer;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\nvar BufferWriter; // cyclic\r\n\r\nvar LongBits = util.LongBits,\r\n base64 = util.base64,\r\n utf8 = util.utf8;\r\n\r\n/**\r\n * Constructs a new writer operation instance.\r\n * @classdesc Scheduled writer operation.\r\n * @constructor\r\n * @param {function(*, Uint8Array, number)} fn Function to call\r\n * @param {number} len Value byte length\r\n * @param {*} val Value to write\r\n * @ignore\r\n */\r\nfunction Op(fn, len, val) {\r\n\r\n /**\r\n * Function to call.\r\n * @type {function(Uint8Array, number, *)}\r\n */\r\n this.fn = fn;\r\n\r\n /**\r\n * Value byte length.\r\n * @type {number}\r\n */\r\n this.len = len;\r\n\r\n /**\r\n * Next operation.\r\n * @type {Writer.Op|undefined}\r\n */\r\n this.next = undefined;\r\n\r\n /**\r\n * Value to write.\r\n * @type {*}\r\n */\r\n this.val = val; // type varies\r\n}\r\n\r\n/* istanbul ignore next */\r\nfunction noop() {} // eslint-disable-line no-empty-function\r\n\r\n/**\r\n * Constructs a new writer state instance.\r\n * @classdesc Copied writer state.\r\n * @memberof Writer\r\n * @constructor\r\n * @param {Writer} writer Writer to copy state from\r\n * @ignore\r\n */\r\nfunction State(writer) {\r\n\r\n /**\r\n * Current head.\r\n * @type {Writer.Op}\r\n */\r\n this.head = writer.head;\r\n\r\n /**\r\n * Current tail.\r\n * @type {Writer.Op}\r\n */\r\n this.tail = writer.tail;\r\n\r\n /**\r\n * Current buffer length.\r\n * @type {number}\r\n */\r\n this.len = writer.len;\r\n\r\n /**\r\n * Next state.\r\n * @type {State|null}\r\n */\r\n this.next = writer.states;\r\n}\r\n\r\n/**\r\n * Constructs a new writer instance.\r\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\r\n * @constructor\r\n */\r\nfunction Writer() {\r\n\r\n /**\r\n * Current length.\r\n * @type {number}\r\n */\r\n this.len = 0;\r\n\r\n /**\r\n * Operations head.\r\n * @type {Object}\r\n */\r\n this.head = new Op(noop, 0, 0);\r\n\r\n /**\r\n * Operations tail\r\n * @type {Object}\r\n */\r\n this.tail = this.head;\r\n\r\n /**\r\n * Linked forked states.\r\n * @type {Object|null}\r\n */\r\n this.states = null;\r\n\r\n // When a value is written, the writer calculates its byte length and puts it into a linked\r\n // list of operations to perform when finish() is called. This both allows us to allocate\r\n // buffers of the exact required size and reduces the amount of work we have to do compared\r\n // to first calculating over objects and then encoding over objects. In our case, the encoding\r\n // part is just a linked list walk calling operations with already prepared values.\r\n}\r\n\r\n/**\r\n * Creates a new writer.\r\n * @function\r\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\r\n */\r\nWriter.create = util.Buffer\r\n ? function create_buffer_setup() {\r\n return (Writer.create = function create_buffer() {\r\n return new BufferWriter();\r\n })();\r\n }\r\n /* istanbul ignore next */\r\n : function create_array() {\r\n return new Writer();\r\n };\r\n\r\n/**\r\n * Allocates a buffer of the specified size.\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\nWriter.alloc = function alloc(size) {\r\n return new util.Array(size);\r\n};\r\n\r\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\r\n/* istanbul ignore else */\r\nif (util.Array !== Array)\r\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\r\n\r\n/**\r\n * Pushes a new operation to the queue.\r\n * @param {function(Uint8Array, number, *)} fn Function to call\r\n * @param {number} len Value byte length\r\n * @param {number} val Value to write\r\n * @returns {Writer} `this`\r\n * @private\r\n */\r\nWriter.prototype._push = function push(fn, len, val) {\r\n this.tail = this.tail.next = new Op(fn, len, val);\r\n this.len += len;\r\n return this;\r\n};\r\n\r\nfunction writeByte(val, buf, pos) {\r\n buf[pos] = val & 255;\r\n}\r\n\r\nfunction writeVarint32(val, buf, pos) {\r\n while (val > 127) {\r\n buf[pos++] = val & 127 | 128;\r\n val >>>= 7;\r\n }\r\n buf[pos] = val;\r\n}\r\n\r\n/**\r\n * Constructs a new varint writer operation instance.\r\n * @classdesc Scheduled varint writer operation.\r\n * @extends Op\r\n * @constructor\r\n * @param {number} len Value byte length\r\n * @param {number} val Value to write\r\n * @ignore\r\n */\r\nfunction VarintOp(len, val) {\r\n this.len = len;\r\n this.next = undefined;\r\n this.val = val;\r\n}\r\n\r\nVarintOp.prototype = Object.create(Op.prototype);\r\nVarintOp.prototype.fn = writeVarint32;\r\n\r\n/**\r\n * Writes an unsigned 32 bit value as a varint.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.uint32 = function write_uint32(value) {\r\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\r\n // uint32 is by far the most frequently used operation and benefits significantly from this.\r\n this.len += (this.tail = this.tail.next = new VarintOp(\r\n (value = value >>> 0)\r\n < 128 ? 1\r\n : value < 16384 ? 2\r\n : value < 2097152 ? 3\r\n : value < 268435456 ? 4\r\n : 5,\r\n value)).len;\r\n return this;\r\n};\r\n\r\n/**\r\n * Writes a signed 32 bit value as a varint.\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.int32 = function write_int32(value) {\r\n return value < 0\r\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\r\n : this.uint32(value);\r\n};\r\n\r\n/**\r\n * Writes a 32 bit value as a varint, zig-zag encoded.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.sint32 = function write_sint32(value) {\r\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\r\n};\r\n\r\nfunction writeVarint64(val, buf, pos) {\r\n while (val.hi) {\r\n buf[pos++] = val.lo & 127 | 128;\r\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\r\n val.hi >>>= 7;\r\n }\r\n while (val.lo > 127) {\r\n buf[pos++] = val.lo & 127 | 128;\r\n val.lo = val.lo >>> 7;\r\n }\r\n buf[pos++] = val.lo;\r\n}\r\n\r\n/**\r\n * Writes an unsigned 64 bit value as a varint.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.uint64 = function write_uint64(value) {\r\n var bits = LongBits.from(value);\r\n return this._push(writeVarint64, bits.length(), bits);\r\n};\r\n\r\n/**\r\n * Writes a signed 64 bit value as a varint.\r\n * @function\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.int64 = Writer.prototype.uint64;\r\n\r\n/**\r\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.sint64 = function write_sint64(value) {\r\n var bits = LongBits.from(value).zzEncode();\r\n return this._push(writeVarint64, bits.length(), bits);\r\n};\r\n\r\n/**\r\n * Writes a boolish value as a varint.\r\n * @param {boolean} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.bool = function write_bool(value) {\r\n return this._push(writeByte, 1, value ? 1 : 0);\r\n};\r\n\r\nfunction writeFixed32(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\n/**\r\n * Writes an unsigned 32 bit value as fixed 32 bits.\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.fixed32 = function write_fixed32(value) {\r\n return this._push(writeFixed32, 4, value >>> 0);\r\n};\r\n\r\n/**\r\n * Writes a signed 32 bit value as fixed 32 bits.\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\r\n\r\n/**\r\n * Writes an unsigned 64 bit value as fixed 64 bits.\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.fixed64 = function write_fixed64(value) {\r\n var bits = LongBits.from(value);\r\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\r\n};\r\n\r\n/**\r\n * Writes a signed 64 bit value as fixed 64 bits.\r\n * @function\r\n * @param {Long|number|string} value Value to write\r\n * @returns {Writer} `this`\r\n * @throws {TypeError} If `value` is a string and no long library is present.\r\n */\r\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\r\n\r\n/**\r\n * Writes a float (32 bit).\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.float = function write_float(value) {\r\n return this._push(util.float.writeFloatLE, 4, value);\r\n};\r\n\r\n/**\r\n * Writes a double (64 bit float).\r\n * @function\r\n * @param {number} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.double = function write_double(value) {\r\n return this._push(util.float.writeDoubleLE, 8, value);\r\n};\r\n\r\nvar writeBytes = util.Array.prototype.set\r\n ? function writeBytes_set(val, buf, pos) {\r\n buf.set(val, pos); // also works for plain array values\r\n }\r\n /* istanbul ignore next */\r\n : function writeBytes_for(val, buf, pos) {\r\n for (var i = 0; i < val.length; ++i)\r\n buf[pos + i] = val[i];\r\n };\r\n\r\n/**\r\n * Writes a sequence of bytes.\r\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.bytes = function write_bytes(value) {\r\n var len = value.length >>> 0;\r\n if (!len)\r\n return this._push(writeByte, 1, 0);\r\n if (util.isString(value)) {\r\n var buf = Writer.alloc(len = base64.length(value));\r\n base64.decode(value, buf, 0);\r\n value = buf;\r\n }\r\n return this.uint32(len)._push(writeBytes, len, value);\r\n};\r\n\r\n/**\r\n * Writes a string.\r\n * @param {string} value Value to write\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.string = function write_string(value) {\r\n var len = utf8.length(value);\r\n return len\r\n ? this.uint32(len)._push(utf8.write, len, value)\r\n : this._push(writeByte, 1, 0);\r\n};\r\n\r\n/**\r\n * Forks this writer's state by pushing it to a stack.\r\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.fork = function fork() {\r\n this.states = new State(this);\r\n this.head = this.tail = new Op(noop, 0, 0);\r\n this.len = 0;\r\n return this;\r\n};\r\n\r\n/**\r\n * Resets this instance to the last state.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.reset = function reset() {\r\n if (this.states) {\r\n this.head = this.states.head;\r\n this.tail = this.states.tail;\r\n this.len = this.states.len;\r\n this.states = this.states.next;\r\n } else {\r\n this.head = this.tail = new Op(noop, 0, 0);\r\n this.len = 0;\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\r\n * @returns {Writer} `this`\r\n */\r\nWriter.prototype.ldelim = function ldelim() {\r\n var head = this.head,\r\n tail = this.tail,\r\n len = this.len;\r\n this.reset().uint32(len);\r\n if (len) {\r\n this.tail.next = head.next; // skip noop\r\n this.tail = tail;\r\n this.len += len;\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Finishes the write operation.\r\n * @returns {Uint8Array} Finished buffer\r\n */\r\nWriter.prototype.finish = function finish() {\r\n var head = this.head.next, // skip noop\r\n buf = this.constructor.alloc(this.len),\r\n pos = 0;\r\n while (head) {\r\n head.fn(head.val, buf, pos);\r\n pos += head.len;\r\n head = head.next;\r\n }\r\n // this.head = this.tail = null;\r\n return buf;\r\n};\r\n\r\nWriter._configure = function(BufferWriter_) {\r\n BufferWriter = BufferWriter_;\r\n};\r\n","\"use strict\";\r\nmodule.exports = BufferWriter;\r\n\r\n// extends Writer\r\nvar Writer = require(\"./writer\");\r\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\nvar Buffer = util.Buffer;\r\n\r\n/**\r\n * Constructs a new buffer writer instance.\r\n * @classdesc Wire format writer using node buffers.\r\n * @extends Writer\r\n * @constructor\r\n */\r\nfunction BufferWriter() {\r\n Writer.call(this);\r\n}\r\n\r\n/**\r\n * Allocates a buffer of the specified size.\r\n * @param {number} size Buffer size\r\n * @returns {Buffer} Buffer\r\n */\r\nBufferWriter.alloc = function alloc_buffer(size) {\r\n return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);\r\n};\r\n\r\nvar writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === \"set\"\r\n ? function writeBytesBuffer_set(val, buf, pos) {\r\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\r\n // also works for plain array values\r\n }\r\n /* istanbul ignore next */\r\n : function writeBytesBuffer_copy(val, buf, pos) {\r\n if (val.copy) // Buffer values\r\n val.copy(buf, pos, 0, val.length);\r\n else for (var i = 0; i < val.length;) // plain array values\r\n buf[pos++] = val[i++];\r\n };\r\n\r\n/**\r\n * @override\r\n */\r\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\r\n if (util.isString(value))\r\n value = util._Buffer_from(value, \"base64\");\r\n var len = value.length >>> 0;\r\n this.uint32(len);\r\n if (len)\r\n this._push(writeBytesBuffer, len, value);\r\n return this;\r\n};\r\n\r\nfunction writeStringBuffer(val, buf, pos) {\r\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\r\n util.utf8.write(val, buf, pos);\r\n else\r\n buf.utf8Write(val, pos);\r\n}\r\n\r\n/**\r\n * @override\r\n */\r\nBufferWriter.prototype.string = function write_string_buffer(value) {\r\n var len = Buffer.byteLength(value);\r\n this.uint32(len);\r\n if (len)\r\n this._push(writeStringBuffer, len, value);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Finishes the write operation.\r\n * @name BufferWriter#finish\r\n * @function\r\n * @returns {Buffer} Finished buffer\r\n */\r\n","\"use strict\";\r\nmodule.exports = Reader;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\nvar BufferReader; // cyclic\r\n\r\nvar LongBits = util.LongBits,\r\n utf8 = util.utf8;\r\n\r\n/* istanbul ignore next */\r\nfunction indexOutOfRange(reader, writeLength) {\r\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\r\n}\r\n\r\n/**\r\n * Constructs a new reader instance using the specified buffer.\r\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\r\n * @constructor\r\n * @param {Uint8Array} buffer Buffer to read from\r\n */\r\nfunction Reader(buffer) {\r\n\r\n /**\r\n * Read buffer.\r\n * @type {Uint8Array}\r\n */\r\n this.buf = buffer;\r\n\r\n /**\r\n * Read buffer position.\r\n * @type {number}\r\n */\r\n this.pos = 0;\r\n\r\n /**\r\n * Read buffer length.\r\n * @type {number}\r\n */\r\n this.len = buffer.length;\r\n}\r\n\r\nvar create_array = typeof Uint8Array !== \"undefined\"\r\n ? function create_typed_array(buffer) {\r\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\r\n return new Reader(buffer);\r\n throw Error(\"illegal buffer\");\r\n }\r\n /* istanbul ignore next */\r\n : function create_array(buffer) {\r\n if (Array.isArray(buffer))\r\n return new Reader(buffer);\r\n throw Error(\"illegal buffer\");\r\n };\r\n\r\n/**\r\n * Creates a new reader using the specified buffer.\r\n * @function\r\n * @param {Uint8Array|Buffer} buffer Buffer to read from\r\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\r\n * @throws {Error} If `buffer` is not a valid buffer\r\n */\r\nReader.create = util.Buffer\r\n ? function create_buffer_setup(buffer) {\r\n return (Reader.create = function create_buffer(buffer) {\r\n return util.Buffer.isBuffer(buffer)\r\n ? new BufferReader(buffer)\r\n /* istanbul ignore next */\r\n : create_array(buffer);\r\n })(buffer);\r\n }\r\n /* istanbul ignore next */\r\n : create_array;\r\n\r\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\r\n\r\n/**\r\n * Reads a varint as an unsigned 32 bit value.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.uint32 = (function read_uint32_setup() {\r\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\r\n return function read_uint32() {\r\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\r\n\r\n /* istanbul ignore if */\r\n if ((this.pos += 5) > this.len) {\r\n this.pos = this.len;\r\n throw indexOutOfRange(this, 10);\r\n }\r\n return value;\r\n };\r\n})();\r\n\r\n/**\r\n * Reads a varint as a signed 32 bit value.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.int32 = function read_int32() {\r\n return this.uint32() | 0;\r\n};\r\n\r\n/**\r\n * Reads a zig-zag encoded varint as a signed 32 bit value.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.sint32 = function read_sint32() {\r\n var value = this.uint32();\r\n return value >>> 1 ^ -(value & 1) | 0;\r\n};\r\n\r\n/* eslint-disable no-invalid-this */\r\n\r\nfunction readLongVarint() {\r\n // tends to deopt with local vars for octet etc.\r\n var bits = new LongBits(0, 0);\r\n var i = 0;\r\n if (this.len - this.pos > 4) { // fast route (lo)\r\n for (; i < 4; ++i) {\r\n // 1st..4th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n // 5th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n i = 0;\r\n } else {\r\n for (; i < 3; ++i) {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n // 1st..3th\r\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n // 4th\r\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\r\n return bits;\r\n }\r\n if (this.len - this.pos > 4) { // fast route (hi)\r\n for (; i < 5; ++i) {\r\n // 6th..10th\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n } else {\r\n for (; i < 5; ++i) {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n // 6th..10th\r\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r\n if (this.buf[this.pos++] < 128)\r\n return bits;\r\n }\r\n }\r\n /* istanbul ignore next */\r\n throw Error(\"invalid varint encoding\");\r\n}\r\n\r\n/* eslint-enable no-invalid-this */\r\n\r\n/**\r\n * Reads a varint as a signed 64 bit value.\r\n * @name Reader#int64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a varint as an unsigned 64 bit value.\r\n * @name Reader#uint64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a zig-zag encoded varint as a signed 64 bit value.\r\n * @name Reader#sint64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a varint as a boolean.\r\n * @returns {boolean} Value read\r\n */\r\nReader.prototype.bool = function read_bool() {\r\n return this.uint32() !== 0;\r\n};\r\n\r\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\r\n return (buf[end - 4]\r\n | buf[end - 3] << 8\r\n | buf[end - 2] << 16\r\n | buf[end - 1] << 24) >>> 0;\r\n}\r\n\r\n/**\r\n * Reads fixed 32 bits as an unsigned 32 bit integer.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.fixed32 = function read_fixed32() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n return readFixed32_end(this.buf, this.pos += 4);\r\n};\r\n\r\n/**\r\n * Reads fixed 32 bits as a signed 32 bit integer.\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.sfixed32 = function read_sfixed32() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n return readFixed32_end(this.buf, this.pos += 4) | 0;\r\n};\r\n\r\n/* eslint-disable no-invalid-this */\r\n\r\nfunction readFixed64(/* this: Reader */) {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 8 > this.len)\r\n throw indexOutOfRange(this, 8);\r\n\r\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\r\n}\r\n\r\n/* eslint-enable no-invalid-this */\r\n\r\n/**\r\n * Reads fixed 64 bits.\r\n * @name Reader#fixed64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads zig-zag encoded fixed 64 bits.\r\n * @name Reader#sfixed64\r\n * @function\r\n * @returns {Long} Value read\r\n */\r\n\r\n/**\r\n * Reads a float (32 bit) as a number.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.float = function read_float() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 4 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n var value = util.float.readFloatLE(this.buf, this.pos);\r\n this.pos += 4;\r\n return value;\r\n};\r\n\r\n/**\r\n * Reads a double (64 bit float) as a number.\r\n * @function\r\n * @returns {number} Value read\r\n */\r\nReader.prototype.double = function read_double() {\r\n\r\n /* istanbul ignore if */\r\n if (this.pos + 8 > this.len)\r\n throw indexOutOfRange(this, 4);\r\n\r\n var value = util.float.readDoubleLE(this.buf, this.pos);\r\n this.pos += 8;\r\n return value;\r\n};\r\n\r\n/**\r\n * Reads a sequence of bytes preceeded by its length as a varint.\r\n * @returns {Uint8Array} Value read\r\n */\r\nReader.prototype.bytes = function read_bytes() {\r\n var length = this.uint32(),\r\n start = this.pos,\r\n end = this.pos + length;\r\n\r\n /* istanbul ignore if */\r\n if (end > this.len)\r\n throw indexOutOfRange(this, length);\r\n\r\n this.pos += length;\r\n if (Array.isArray(this.buf)) // plain array\r\n return this.buf.slice(start, end);\r\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\r\n ? new this.buf.constructor(0)\r\n : this._slice.call(this.buf, start, end);\r\n};\r\n\r\n/**\r\n * Reads a string preceeded by its byte length as a varint.\r\n * @returns {string} Value read\r\n */\r\nReader.prototype.string = function read_string() {\r\n var bytes = this.bytes();\r\n return utf8.read(bytes, 0, bytes.length);\r\n};\r\n\r\n/**\r\n * Skips the specified number of bytes if specified, otherwise skips a varint.\r\n * @param {number} [length] Length if known, otherwise a varint is assumed\r\n * @returns {Reader} `this`\r\n */\r\nReader.prototype.skip = function skip(length) {\r\n if (typeof length === \"number\") {\r\n /* istanbul ignore if */\r\n if (this.pos + length > this.len)\r\n throw indexOutOfRange(this, length);\r\n this.pos += length;\r\n } else {\r\n do {\r\n /* istanbul ignore if */\r\n if (this.pos >= this.len)\r\n throw indexOutOfRange(this);\r\n } while (this.buf[this.pos++] & 128);\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Skips the next element of the specified wire type.\r\n * @param {number} wireType Wire type received\r\n * @returns {Reader} `this`\r\n */\r\nReader.prototype.skipType = function(wireType) {\r\n switch (wireType) {\r\n case 0:\r\n this.skip();\r\n break;\r\n case 1:\r\n this.skip(8);\r\n break;\r\n case 2:\r\n this.skip(this.uint32());\r\n break;\r\n case 3:\r\n do { // eslint-disable-line no-constant-condition\r\n if ((wireType = this.uint32() & 7) === 4)\r\n break;\r\n this.skipType(wireType);\r\n } while (true);\r\n break;\r\n case 5:\r\n this.skip(4);\r\n break;\r\n\r\n /* istanbul ignore next */\r\n default:\r\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\r\n }\r\n return this;\r\n};\r\n\r\nReader._configure = function(BufferReader_) {\r\n BufferReader = BufferReader_;\r\n\r\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\r\n util.merge(Reader.prototype, {\r\n\r\n int64: function read_int64() {\r\n return readLongVarint.call(this)[fn](false);\r\n },\r\n\r\n uint64: function read_uint64() {\r\n return readLongVarint.call(this)[fn](true);\r\n },\r\n\r\n sint64: function read_sint64() {\r\n return readLongVarint.call(this).zzDecode()[fn](false);\r\n },\r\n\r\n fixed64: function read_fixed64() {\r\n return readFixed64.call(this)[fn](true);\r\n },\r\n\r\n sfixed64: function read_sfixed64() {\r\n return readFixed64.call(this)[fn](false);\r\n }\r\n\r\n });\r\n};\r\n","\"use strict\";\r\nmodule.exports = BufferReader;\r\n\r\n// extends Reader\r\nvar Reader = require(\"./reader\");\r\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\r\n\r\nvar util = require(\"./util/minimal\");\r\n\r\n/**\r\n * Constructs a new buffer reader instance.\r\n * @classdesc Wire format reader using node buffers.\r\n * @extends Reader\r\n * @constructor\r\n * @param {Buffer} buffer Buffer to read from\r\n */\r\nfunction BufferReader(buffer) {\r\n Reader.call(this, buffer);\r\n\r\n /**\r\n * Read buffer.\r\n * @name BufferReader#buf\r\n * @type {Buffer}\r\n */\r\n}\r\n\r\n/* istanbul ignore else */\r\nif (util.Buffer)\r\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\r\n\r\n/**\r\n * @override\r\n */\r\nBufferReader.prototype.string = function read_string_buffer() {\r\n var len = this.uint32(); // modifies pos\r\n return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));\r\n};\r\n\r\n/**\r\n * Reads a sequence of bytes preceeded by its length as a varint.\r\n * @name BufferReader#bytes\r\n * @function\r\n * @returns {Buffer} Value read\r\n */\r\n","\"use strict\";\r\nmodule.exports = Service;\r\n\r\nvar util = require(\"../util/minimal\");\r\n\r\n// Extends EventEmitter\r\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\r\n\r\n/**\r\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\r\n *\r\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\r\n * @typedef rpc.ServiceMethodCallback\r\n * @template TRes extends Message\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {TRes} [response] Response message\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\r\n * @typedef rpc.ServiceMethod\r\n * @template TReq extends Message\r\n * @template TRes extends Message\r\n * @type {function}\r\n * @param {TReq|Properties} request Request message or plain object\r\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\r\n * @returns {Promise