var checkSum    = math.checkSum; 
Model uitl

@package     Gina.Utils
@author      Rhinostone <gina@rhinostone.com>
@api public
332746
function ModelUtil() {
    var self        = this;
    var cacheless   = (process.env.IS_CACHELESS == 'false') ? false : true;

    /**
     * Init
     * @contructor
     * */
    var init = function() {

        if ( !ModelUtil.instance && !getContext('modelUtil') ) {
            self.models             = self.models || {}; // used when getModel(modelName) is called
            self.entities           = {};
            self.entitiesCollection = {}; // used when getEntity(entityName) is called - handles entity relations
            self.files              = {};
            ModelUtil.instance      = self;

            setContext('modelUtil', ModelUtil.instance);

            return self
        } else {
            //if (!ModelUtil.instance) {
            //    ModelUtil.instance = getContext('modelUtil')
            //}
            //self = ModelUtil.instance;
            //ModelUtil.instance = getContext('modelUtil');
            //ModelUtil.instance = ModelUtil.instance || getContext('modelUtil');
            //self = merge(self, ModelUtil.instance, true);
            // return self
            return ModelUtil.instance || getContext('modelUtil')
        }
    }

    this.setConnection = function(bundle, name, conn) {
        if (arguments.length > 1) {
            if (!self.models) {
                self.models = {}
            }
            if (!self.entitiesCollection) {
                self.entitiesCollection = {}
            }
            if (!self.models[bundle]) {
                self.models[bundle] = {}
            }
            if (!self.entitiesCollection[bundle]) {
                self.entitiesCollection[bundle] = {}
            }
            if ( typeof(name) == 'undefined' || name == '' ) {
                throw new Error('Connection must have a name !')
            }

            if (typeof(self.models[bundle][name]) == 'undefined') {
                self.models[bundle][name] = {};
                if (!self.files[bundle]) {
                    self.files[bundle] = {}
                }
                self.files[bundle][name] = {}
            }

            if (typeof(self.entitiesCollection[bundle][name]) == 'undefined') {
                self.entitiesCollection[bundle][name] = {};
            }


            self.models[bundle][name]['_connection'] = conn;
            self.entitiesCollection[bundle][name]['_connection'] = conn;
        } else {
            self.models[bundle] = {};
            self.entitiesCollection[bundle] = {}
        }

        //setContext('modelUtil.entitiesCollection', self.entitiesCollection, true)
        ModelUtil.instance.entitiesCollection = self.entitiesCollection;
    }

    /**
    *
    * @param {string} name - Entity name
    * @param {object} module
    *
    * */
    this.setModelEntity = function(bundle, model, name, module) {
        var cacheless   = (process.env.IS_CACHELESS == 'false') ? false : true;
        
        if (arguments.length > 1) {
            if (!self.entities) {
                self.entities = {}
            }

            if (!self.entities[bundle]) {
                self.entities[bundle] = {}
            }

            if ( typeof(name) == 'undefined' || name == '' ) {
                throw new Error('`modelUtil cannot set `modelEntity whitout a name !')
            }

            if( !self.entities[bundle][model] ) {
                self.entities[bundle][model] = {}
            }

            if ( !/Entity$/.test(name) ) {
                name = name + 'Entity'
            }
            self.entities[bundle][model][name] = module

        } else {
            self.entities[bundle][model] = arguments[0]
        }

        setContext('modelUtil.entities', self.entities, true);
        ModelUtil.instance.entities = self.entities;
    }

    this.updateModel = function(bundle, model, name, entityObject) {

        if ( typeof(model) == 'undefined' || model == '' ) {
            throw new Error('`modelUtil` cannot update `entityObject` whitout a connector !')
        }

        if ( typeof(name) == 'undefined' || name == '' ) {
            throw new Error('`modelUtil` cannot set `modelEntity` whitout a name !')
        }

        if (!self.models[bundle][model][name]) {
            self.models[bundle][model][name] = {}
        }

        self.models[bundle][model][name] =  entityObject;


        ModelUtil.instance.models = self.models;
        setContext('modelUtil.models', self.models, true);

        return self.models[bundle][model][name]
    }

    this.updateEntities = function(bundle, model, name, entityObject) {

        if ( typeof(model) == 'undefined' || model == '' ) {
            throw new Error('`modelUtil` cannot update `entityObject` whitout a connector !')
        }

        if ( typeof(name) == 'undefined' || name == '' ) {
            throw new Error('`modelUtil` cannot set `modelEntity` whitout a name !')
        }

        if (!self.entitiesCollection[bundle][model][name]) {
            self.entitiesCollection[bundle][model][name] = {}
        }

        self.entitiesCollection[bundle][model][name] =  entityObject;

        return self.entitiesCollection[bundle][model][name]
    }

    this.setModel = function(bundle, name, obj) {
        if (arguments.length > 2) {
            if ( typeof(name) == 'undefined' || name == '' ) {
                var name = 'global'
            }

            if (!self.models[bundle]) {
                self.models[bundle] = {}
            }
            if (!self.entitiesCollection[bundle]) {
                self.entitiesCollection[bundle] = {}
            }
            //entitiesCollection

            if (!self.models[bundle][name]) {
                self.models[bundle][name] = {}
            }
            if (!self.entitiesCollection[bundle][name]) {
                self.entitiesCollection[bundle][name] = {}
            }

            self.models[bundle][name] = merge(self.models[bundle][name], obj);
            self.entitiesCollection[bundle][name] = merge(self.entitiesCollection[bundle][name], obj)

        } else {
            self.models[bundle][name] = {};
            self.entitiesCollection[bundle][name] = {}
        }
    }


    this.loadAllModels = function(bundles, configuration, env, cb) {

        var loadModel = function(b, bundles, configuration, env, cb) {
            var modelObject     = getContext('modelUtil').entities[bundles[b]] // to check if already laoded
                , bundle        = bundles[b]
                , len           = bundles.length
                , conf          = configuration[bundle][env]
                , connectors    = conf.content['connectors'] || undefined
                , modelConnectors  = {};


            if ( typeof(connectors) != 'undefined' && connectors != null) {
                var Model = require( _( getPath('gina').core + '/model') );
                var mObj = {};

                var models = connectors;

                var t = 0;

                var done = function(connector, modelConnectors) {
                    if ( typeof(models[connector]) != 'undefined' ) {
                        ++t
                    } else {
                        console.error('connector '+ connector +' not found in configuration')
                    }

                    if ( t == models.count() ) {
                        setContext('modelConnectors', modelConnectors);

                        var conn                = null
                            , entitiesManager   = null
                            , modelPath         = null
                            , entitiesPath      = null
                            , entitiesObject    = null
                            , foundInitError    = false;

                        // end - now, loading entities for each `loaded` model
                        for (var bundle in self.models) {

                            for (var name in self.models[bundle]) {//name as connector name
                                conn            = self.models[bundle][name]['_connection'];
                                modelPath       = _(conf.modelsPath + '/' + name);
                                entitiesPath    = _(modelPath + '/entities');
                                //Getting Entities Manager thru connector.
                                entitiesManager = new require( _(conf.modelsPath + '/index.js', true) )(conn)[name](conn, { model: name, bundle: bundle, database: conf.content['connectors'][name].database });

                                self.setConnection(bundle, name, conn);

                                // step 1: creating entities classes in the context
                                // must be done only when all models conn are alive because of `cross models/database use cases`
                                for (var nttClass in entitiesManager) {
                                    if ( !/^[A-Z]/.test( nttClass ) ) {
                                        throw new Error('Entity Class `'+ nttClass +'` should start with an uppercase !');
                                        foundInitError = true
                                    }
                                    self.setModelEntity(bundle, name, nttClass, entitiesManager[nttClass])
                                }

                                // step 2: creating entities instances
                                for (var nttClass in entitiesManager) {
                                    new entitiesManager[nttClass](conn);
                                }

                            }
                        }

                        setContext('modelUtil', ModelUtil.instance, true);
                        if (foundInitError) process.exit(1);


                        cb()
                    }
                }

                for (var c in models) {//c as connector name
                    if ( modelObject && typeof(modelObject[c]) != 'undefined' ) {
                        done(connector, modelConnectors)
                    } else {
                        //e.g. var apiModel    = new Model(config.bundle + "/api");
                        // => var apiModel = getContext('apiModel')
                        console.debug('....model ', conf.bundle + "/"+c + 'Model');
                        mObj[c+'Model'] = new Model(conf.bundle + "/" + c);
                        mObj[c+'Model']
                            .onReady(
                            function onModelReady( err, bundle, connector, conn) {
                                if (err) {
                                    console.error('found error ...');
                                    console.error(err.stack||err.message||err);
                                } else {

                                    if (!modelConnectors[bundle]) {
                                        modelConnectors[bundle] = {}
                                    }
                                    if (!modelConnectors[bundle][connector]) {
                                        modelConnectors[bundle][connector] = {
                                            conn: conn
                                        }
                                    }

                                    if ( typeof(self.models[bundle]) == 'undefined') {
                                        self.models[bundle] = {}
                                    }

                                    if ( typeof(self.models[bundle][connector]) == 'undefined') {
                                        self.models[bundle][connector] = {}
                                    }

                                    if ( typeof(self.models[bundle][connector]['_connection']) == 'undefined' ) {
                                        self.models[bundle][connector]['_connection'] = conn
                                    }

                                    if ( typeof(self.models[bundle][connector]['getConnection']) == 'undefined' ) {// only used when tryin to import multiple models into the same entity
                                        self.models[bundle][connector]['getConnection'] = function() {
                                            return self.models[bundle][connector]['_connection']
                                        }
                                    }
                                }

                                done(connector, modelConnectors)
                            })
                   }

                }


            } else {
                //throw new Error('no connector found for bundle [ '+ bundle +' ]');
                // this is normal if there is no connector.json found in the source
                if (b < bundles.length-1) {
                    loadModel(b+1, bundles, configuration, env, cb)
                } else {
                    cb()
                }

            }
        };

        loadModel(0, bundles, configuration, env, cb)
    }


    /**
     * Reload modes
     * cacheless mode only
     *
     * @param {obj} conf
     * @callback cb
     * */
    this.reloadModels = function(conf, cb) {

        if ( typeof(conf.content['connectors']) != 'undefined' && conf.content['connectors'] != null ) {

            var models              = conf.content.connectors
                , conn              = null
                , foundInitError    = false
                , entitiesManager   = null
                , modelPath         = null
                , entitiesPath      = null
                , modelConnectors   = null;


            // end - now, loading entities for each `loaded` model
            for (var bundle in self.models) {

                for (var name in self.models[bundle]) { //name as connector name
                    
                    self.models[bundle][name] = {};

                    if ( typeof(self.models[bundle][name]['_connection']) == 'undefined' ) {
                        self.models[bundle][name]['_connection'] = getContext('modelConnectors')[bundle][name].conn
                    }

                    if ( typeof(self.models[bundle][name]['getConnection']) == 'undefined' ) {// only used when tryin to import multiple models into the same entity
                        self.models[bundle][name]['getConnection'] = function() {
                            return self.models[bundle][name]['_connection']
                        }
                    }

                    conn            = getContext('modelConnectors')[bundle][name].conn;

                    modelPath       = _(conf.modelsPath + '/' + name);
                    entitiesPath    = _(modelPath + '/entities');

                    //Getting Entities Manager thru connector.
                    delete require.cache[_(conf.modelsPath + '/index.js', true)];//child
                    try {
                        entitiesManager = new require( _(conf.modelsPath + '/index.js', true) )(conn)[name](conn, { model: name, bundle: bundle, database: conf.content['connectors'][name].database });
                    } catch (err) {
                        cb(err)
                    }

                    self.setConnection(bundle, name, conn);
                    // creating entities instances
                    // must be done only when all models conn are alive because of `cross models/database use cases`
                    for (var nttClass in entitiesManager) {
                        if ( !/^[A-Z]/.test( nttClass ) ) {
                            throw new Error('Entity Class `'+ nttClass +'` should start with an uppercase ?');
                            foundInitError = true
                        }
                        self.setModelEntity(bundle, name, nttClass, entitiesManager[nttClass])
                    }

                    for (var nttClass in entitiesManager) {
                        // will force updates on self.models
                        new entitiesManager[nttClass](conn);
                    }

                    console.log('loaded model ', bundle+'/'+name);
                }
            }


            setContext('modelUtil', self, true);
            ModelUtil.instance = self;

            cb(false)

        } else {
            cb(new Error('[ '+ conf.bundle+' ] no connector found !'))
        }
    }


    /**
     * Get Model by [ bundleName ] & modelName
     *
     * @param {string} [ bundle ] - Bundle name
     * @param {string} model - Model name
     *
     * @return {object} model - Model entities
     * */
    getModel = function(bundle, model) {

        var ctx       = getContext();

        if (arguments.length == 1 || !bundle) {
            //console.debug(
            //    '\n[ 0 ] = '+ __stack[0].getFileName(),
            //    '\n[ 1 ] = '+ __stack[1].getFileName(),
            //    '\n[ 2 ] = '+ __stack[2].getFileName(),
            //    '\n[ 3 ] = '+ __stack[3].getFileName(),
            //    '\n[ 4 ] = '+ __stack[4].getFileName(),
            //    '\n[ 5 ] = '+ __stack[5].getFileName(),
            //    '\n[ 6 ] = '+ __stack[6].getFileName()
            //);


            // var model       = (arguments.length == 1) ? bundle : model
            //     , file      = ( !/node_modules/.test(__stack[1].getFileName()) ) ?  __stack[1].getFileName() : __stack[2].getFileName()
            //     , a         = file.replace('.js', '').split('/')
            //     , i         = a.length-1
            //     , bundle    = null;
            //
            // var conf        = getContext('gina').config || null;
            // if (conf) {
            //     var bundles     = conf.bundles
            //         , index     = 0;
            //
            //     for (; i >= 0; --i) {
            //         index = bundles.indexOf(a[i]);
            //         if ( index > -1 ) {
            //             bundle = bundles[index];
            //             break
            //         }
            //     }
            // } else {
            //     conf    = getContext();
            //     bundle  = conf.bundle;
            // }




            var model         = (arguments.length == 1) ? bundle : model
                , bundle    = null
                , modelPath   = null
                , file      = null
                , stackFileName = null;
            //, file      = ( !/node_modules/.test(__stack[1].getFileName()) ) ?  __stack[1].getFileName() : __stack[2].getFileName()
            for (var i = 1, len = 10; i<len; ++i) {
                stackFileName = __stack[i].getFileName();
                if ( stackFileName && !/node_modules/.test(stackFileName) ) {
                    file = stackFileName;
                    break;
                }
            }
            var a           = file.replace('.js', '').split('/')
                , i         = a.length-1;

            if (bundle == model) {
                bundle = ctx.bundle
            } else {

                if (ctx.bundles) {
                    for (; i >= 0; --i) {
                        index = ctx.bundles.indexOf(a[i]);
                        if ( index > -1 ) {
                            ctx.bundle = bundle = ctx.bundles[index];

                            break
                        }
                    }
                } else if (ctx.bundle) {
                    bundle = ctx.bundle
                }

            }
        }

        //if (!self.models) {
            self.models = ModelUtil.instance.models
        //}

        if ( typeof(model) != 'undefined' && typeof(self.models[bundle]) != 'undefined' ) {

            try {

                if ( typeof(self.models[bundle][model]['getConnection']) == 'undefined' ) {
                    self.models[bundle][model]['getConnection'] = function() {
                        return self.models[bundle][model]['_connection']
                    }
                }

                return self.models[bundle][model]
            } catch (err) {
                return undefined
            }
        }
    }

    /**
     * Get Model Entity
     *
     * @param {string} model
     * @param {string} entityName
     * @param {object} conn
     *
     * @return {object} entity
     * */
    getModelEntity = function(bundle, model, entityClassName, conn) {
        if ( typeof(entityClassName) != 'undefined' ) {
            var cacheless   = (process.env.IS_CACHELESS == 'false') ? false : true;
            try {
                var shortName = entityClassName.substr(0, 1).toLowerCase() + entityClassName.substr(1);

                if (!self.entities) {
                    if (!ModelUtil.instance) {
                        ModelUtil.instance = getContext('modelUtil')
                    }
                    self.entities           = ModelUtil.instance.entities;
                    self.entitiesCollection = ModelUtil.instance.entitiesCollection;
                    self.models             = ModelUtil.instance.models;

                    if (typeof(self.models) == 'function' ) {
                        self.models                 = {};
                        self.models[bundle]         = {};
                        self.models[bundle][model]  = {}
                    }

                }

                //console.debug(parent+'->getEntity('+shortName+')');
                if ( self.models[bundle][model][shortName] /**&& !cacheless*/) { // cacheless is filtered thanks to self.reloadModels(...)
                    //return self.models[bundle][model][shortName]
                    return self.entitiesCollection[bundle][model][shortName]
                } else {
                    var entityObject = new self.entities[bundle][model][entityClassName](conn)
                    self.entitiesCollection[bundle][model][shortName] = entityObject;

                    //setContext('modelUtil.entitiesCollection', self.entitiesCollection, true);
                    ModelUtil.instance.entitiesCollection = self.entitiesCollection;

                    return entityObject;
                }

            } catch (err) {
                throw err;
                return undefined
            }
        } else {
            return self.entities[bundle][model]
        }
    }


    return init()
}
754472
def checksum(string):
    
    digits = list(map(int, string))
    odd_sum = sum(digits[-1::-2])
    even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
    return (odd_sum + even_sum) % 10
221789
function checksum$4(data) {
	var result = 0;

	for (var i = 0; i < 13; i++) {
		result += parseInt(data[i]) * (3 - i % 2 * 2);
	}

	return Math.ceil(result / 10) * 10 - result;
}
179641
public function checksum($value)
    {
        $checksum = $this->getChecksum();
        if (!empty($checksum)) {
            if (method_exists($this, $checksum)) {
                return call_user_func(array($this, $checksum), $value);
            }
        }

        return false;
    }
444803
function getChecksum(fs, path, callback) {
  fs.readFile(path, function(err, data) {
    if(!err) {
      callback(null, md5sum(data));
    } else if(err.code === 'ENOENT') {
      // File does not exist so the checksum is an empty string
      callback(null, "");
    } else {
      callback(err);
    }
  });
}
1172632
function( object ) {
		var keys = Object.keys(object), k, v, lookupString,
			lVals = [], lArrays = [], lObjects = [];

		// Sort to values, arrays and objects
		lookupString = "";
		for (var i=0; i<keys.length; ++i) {
			k = keys[i]; v = object[k];
			if ((v instanceof Uint8Array) || (v instanceof Int8Array) ||
				(v instanceof Uint16Array) || (v instanceof Int16Array) ||
				(v instanceof Uint32Array) || (v instanceof Int32Array) ||
				(v instanceof Float32Array) || (v instanceof Float64Array) ||
				(v instanceof Array) ) {
				lArrays.push(k);
				lookupString += "@"+k;
			} else if (v.constructor === ({}).constructor) {
				lObjects.push(k);
				lookupString += "%"+k;
			} else {
				lVals.push(k);
				lookupString += "$"+k;
			}
		}

		// Lookup or create signature
		i = this.plainObjectSignatureLookup[lookupString];
		if (i === undefined) {

			// Compile signature
			var sigbuf = [];
			sigbuf.push( pack2b( lVals.length ) );
			for (var i=0; i<lVals.length; ++i) {
				sigbuf.push( pack2b( this.stringID(lVals[i]) ) );
			}
			sigbuf.push( pack2b( lArrays.length ) );
			for (var i=0; i<lArrays.length; ++i) {
				sigbuf.push( pack2b( this.stringID(lArrays[i]) ) );
			}
			sigbuf.push( pack2b( lObjects.length ) );
			for (var i=0; i<lObjects.length; ++i) {
				sigbuf.push( pack2b( this.stringID(lObjects[i]) ) );
			}

			// Encode to the 16-bit stream
			this.plainObjectSignatureTable.push( Buffer.concat( sigbuf ) );
			this.plainObjectSignatureLookup[lookupString] 
				= i = this.plainObjectSignatureTable.length - 1;
		}

		// Return index
		return [i, lVals, lArrays, lObjects];
	}
340220
def _checksum(cls, line):
        
        tr_table = str.maketrans({c: None for c in ascii_uppercase + "+ ."})
        no_letters = line[:68].translate(tr_table).replace("-", "1")
        return sum([int(l) for l in no_letters]) % 10
1141505
function createOneOfChecker(expectedEnumValues) {

    return createChainableChecker(function (data, dataName, componentName, fullDataName) {

        if (getDataType(expectedEnumValues) !== 'array') {
            throw new Error('[SAN ERROR] '
                + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
                + 'DataType notation inside `oneOf`, array is expected.'
            );
        }

        var dataValue = data[dataName];

        for (var i = 0, len = expectedEnumValues.length; i < len; i++) {
            if (dataValue === expectedEnumValues[i]) {
                return;
            }
        }

        throw new Error('[SAN ERROR] '
            + 'Invalid ' + componentName + ' data `' + fullDataName + '` of value'
            + '(`' + dataValue + '` supplied to ' + componentName + ', '
            + 'expected one of ' + expectedEnumValues.join(',') + ')'
        );

    });

}
491103
function( value ) {

    var lines = TLE.trim( value + '' ).split( /\r?\n/g )
    var line, checksum

    // Line 0
    if (lines.length === 3) {
      this.name = TLE.trim( lines.shift() )
    }

    // Line 1
    line = lines.shift()
    checksum = TLE.check( line )

    if( checksum != line.substring( 68, 69 ) ) {
      throw new Error(
        'Line 1 checksum mismatch: ' + checksum + ' != ' +
        line.substring( 68, 69 ) + ': ' + line
      )
    }

    this.number = TLE.parseFloat( line.substring( 2, 7 ) )
    this.class = TLE.trim( line.substring( 7, 9 ) )
    this.id = TLE.trim( line.substring( 9, 18 ) )
    this.date = TLE.parseDate( line.substring( 18, 33 ) )
    this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) )
    this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) )
    this.drag = TLE.parseDrag( line.substring( 53, 62 ) )
    this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) )
    this.esn = TLE.parseFloat( line.substring( 64, 68 ) )

    // Line 2
    line = lines.shift()
    checksum = TLE.check( line )

    if( checksum != line.substring( 68, 69 ) ) {
      throw new Error(
        'Line 2 checksum mismatch: ' + checksum + ' != ' +
        line.substring( 68, 69 ) + ': ' + line
      )
    }

    this.inclination = TLE.parseFloat( line.substring( 8, 17 ) )
    this.ascension = TLE.parseFloat( line.substring( 17, 26 ) )
    this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) )
    this.perigee = TLE.parseFloat( line.substring( 34, 43 ) )
    this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) )
    this.motion = TLE.parseFloat( line.substring( 52, 64 ) )
    this.revolution = TLE.parseFloat( line.substring( 64, 68 ) )

    return this

  }
992712
function (scope, iAttrs, newValue) {
    'use strict';
    var ngModelArr = iAttrs.ngModel.split('.');
    // console.log(JSON.stringify(ngModelArr, null, 2));


    switch (ngModelArr.length) {
    case 1:
        scope.$apply(function () {scope[ngModelArr[0]] = newValue;});
        break;
    case 2:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]] = newValue;});
        break;
    case 3:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]] = newValue;});
        break;
    case 4:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]] = newValue;});
        break;
    case 5:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]][ngModelArr[4]] = newValue;});
        break;
    default:
        scope.$apply(function () {scope[iAttrs.ngModel] = newValue;});
    }

}
1227513
function roll(data, checksums, blockSize) {
  var results = [];
  var hashtable = createHashtable(checksums);
  var length = data.length;
  var start = 0;
  var end = blockSize > length ? length : blockSize;
  // Updated when a block matches
  var lastMatchedEnd = 0;
  // This gets updated every iteration with the previous weak 32bit hash
  var prevRollingWeak = null;
  var weak;
  var weak16;
  var match;
  var d;
  var len;
  var mightMatch;
  var chunk;
  var strong;
  var hashtable_weak16;
  var hashtable_weak16i;

  for (; end <= length; start++, end++) {
    weak = calcWeak32(data, prevRollingWeak, start, end);
    weak16 = calcWeak16(weak.sum);
    match = false;
    d = null;
    prevRollingWeak = weak;
    hashtable_weak16 = hashtable[weak16];

    if (hashtable_weak16) {
      len = hashtable_weak16.length;
      for (var i = 0; i < len; i++) {
        hashtable_weak16i = hashtable_weak16[i];
        if (hashtable_weak16i.weak === weak.sum) {
          mightMatch = hashtable_weak16i;
          chunk = data.slice(start, end);
          strong = md5sum(chunk);

          if (mightMatch.strong === strong) {
            match = mightMatch;
            break;
          }
        }
      }
    }
    if (match) {
      if(start < lastMatchedEnd) {
        d = data.slice(lastMatchedEnd - 1, end);
        results.push({
          data: d,
          index: match.index
        });
      } else if (start - lastMatchedEnd > 0) {
        d = data.slice(lastMatchedEnd, start);
        results.push({
          data: d,
          index: match.index
        });
      } else {
        results.push({
          index: match.index
        });
      }
      lastMatchedEnd = end;
    } else if (end === length) {
      // No match and last block
      d = data.slice(lastMatchedEnd);
      results.push({
        data: d
      });
    }
  }
  return results;
}
667160
function verify (v, h, P) {
        /* Y = v abs(P) + h G  */
        var d = new Array(32);
        var p = [createUnpackedArray(), createUnpackedArray()];
        var s = [createUnpackedArray(), createUnpackedArray()];
        var yx = [createUnpackedArray(), createUnpackedArray(), createUnpackedArray()];
        var yz = [createUnpackedArray(), createUnpackedArray(), createUnpackedArray()];
        var t1 = [createUnpackedArray(), createUnpackedArray(), createUnpackedArray()];
        var t2 = [createUnpackedArray(), createUnpackedArray(), createUnpackedArray()];

        var vi = 0, hi = 0, di = 0, nvh = 0, i, j, k;

        /* set p[0] to G and p[1] to P  */

        set(p[0], 9);
        unpack(p[1], P);

        /* set s[0] to P+G and s[1] to P-G  */

        /* s[0] = (Py^2 + Gy^2 - 2 Py Gy)/(Px - Gx)^2 - Px - Gx - 486662  */
        /* s[1] = (Py^2 + Gy^2 + 2 Py Gy)/(Px - Gx)^2 - Px - Gx - 486662  */

        x_to_y2(t1[0], t2[0], p[1]); /* t2[0] = Py^2  */
        sqrt(t1[0], t2[0]); /* t1[0] = Py or -Py  */
        j = is_negative(t1[0]); /*      ... check which  */
        add(t2[0], t2[0], C39420360); /* t2[0] = Py^2 + Gy^2  */
        mul(t2[1], BASE_2Y, t1[0]); /* t2[1] = 2 Py Gy or -2 Py Gy  */
        sub(t1[j], t2[0], t2[1]); /* t1[0] = Py^2 + Gy^2 - 2 Py Gy  */
        add(t1[1 - j], t2[0], t2[1]); /* t1[1] = Py^2 + Gy^2 + 2 Py Gy  */
        cpy(t2[0], p[1]); /* t2[0] = Px  */
        sub(t2[0], t2[0], C9); /* t2[0] = Px - Gx  */
        sqr(t2[1], t2[0]); /* t2[1] = (Px - Gx)^2  */
        recip(t2[0], t2[1], 0); /* t2[0] = 1/(Px - Gx)^2  */
        mul(s[0], t1[0], t2[0]); /* s[0] = t1[0]/(Px - Gx)^2  */
        sub(s[0], s[0], p[1]); /* s[0] = t1[0]/(Px - Gx)^2 - Px  */
        sub(s[0], s[0], C486671); /* s[0] = X(P+G)  */
        mul(s[1], t1[1], t2[0]); /* s[1] = t1[1]/(Px - Gx)^2  */
        sub(s[1], s[1], p[1]); /* s[1] = t1[1]/(Px - Gx)^2 - Px  */
        sub(s[1], s[1], C486671); /* s[1] = X(P-G)  */
        mul_small(s[0], s[0], 1); /* reduce s[0] */
        mul_small(s[1], s[1], 1); /* reduce s[1] */

        /* prepare the chain  */
        for (i = 0; i < 32; i++) {
            vi = (vi >> 8) ^ (v[i] & 0xFF) ^ ((v[i] & 0xFF) << 1);
            hi = (hi >> 8) ^ (h[i] & 0xFF) ^ ((h[i] & 0xFF) << 1);
            nvh = ~(vi ^ hi);
            di = (nvh & (di & 0x80) >> 7) ^ vi;
            di ^= nvh & (di & 0x01) << 1;
            di ^= nvh & (di & 0x02) << 1;
            di ^= nvh & (di & 0x04) << 1;
            di ^= nvh & (di & 0x08) << 1;
            di ^= nvh & (di & 0x10) << 1;
            di ^= nvh & (di & 0x20) << 1;
            di ^= nvh & (di & 0x40) << 1;
            d[i] = di & 0xFF;
        }

        di = ((nvh & (di & 0x80) << 1) ^ vi) >> 8;

        /* initialize state */
        set(yx[0], 1);
        cpy(yx[1], p[di]);
        cpy(yx[2], s[0]);
        set(yz[0], 0);
        set(yz[1], 1);
        set(yz[2], 1);

        /* y[0] is (even)P + (even)G
         * y[1] is (even)P + (odd)G  if current d-bit is 0
         * y[1] is (odd)P + (even)G  if current d-bit is 1
         * y[2] is (odd)P + (odd)G
         */

        vi = 0;
        hi = 0;

        /* and go for it! */
        for (i = 32; i-- !== 0;) {
            vi = (vi << 8) | (v[i] & 0xFF);
            hi = (hi << 8) | (h[i] & 0xFF);
            di = (di << 8) | (d[i] & 0xFF);

            for (j = 8; j-- !== 0;) {
                mont_prep(t1[0], t2[0], yx[0], yz[0]);
                mont_prep(t1[1], t2[1], yx[1], yz[1]);
                mont_prep(t1[2], t2[2], yx[2], yz[2]);

                k = ((vi ^ vi >> 1) >> j & 1)
                    + ((hi ^ hi >> 1) >> j & 1);
                mont_dbl(yx[2], yz[2], t1[k], t2[k], yx[0], yz[0]);

                k = (di >> j & 2) ^ ((di >> j & 1) << 1);
                mont_add(t1[1], t2[1], t1[k], t2[k], yx[1], yz[1],
                    p[di >> j & 1]);

                mont_add(t1[2], t2[2], t1[0], t2[0], yx[2], yz[2],
                    s[((vi ^ hi) >> j & 2) >> 1]);
            }
        }

        k = (vi & 1) + (hi & 1);
        recip(t1[0], yz[k], 0);
        mul(t1[1], yx[k], t1[0]);

        var Y = [];
        pack(t1[1], Y);
        return Y;
    }
1231028
private static String calculateChecksum(String string) {
        byte[] bytes = string.getBytes(UTF_8);
        Checksum checksum = new CRC32();
        checksum.update(bytes, 0, bytes.length);
        return Long.toHexString(checksum.getValue()).toUpperCase();
    }
225528
function validateChecksum(requester, params) {
        params = params || {
            filePath: installerPath,
            expectedChecksum: _updateParams.checksum
        };

        var hash = crypto.createHash('sha256'),
            currentRequester = requester || "";

        if (fs.existsSync(params.filePath)) {
            var stream = fs.createReadStream(params.filePath);

            stream.on('data', function (data) {
                hash.update(data);
            });

            stream.on('end', function () {
                var calculatedChecksum = hash.digest('hex'),
                    isValidChecksum = (params.expectedChecksum === calculatedChecksum),
                    status;

                if (isValidChecksum) {
                    if (process.platform === "darwin") {
                        status = {
                            valid: true,
                            installerPath: installerPath,
                            logFilePath: logFilePath,
                            installStatusFilePath: installStatusFilePath
                        };
                    } else if (process.platform === "win32") {
                        status = {
                            valid: true,
                            installerPath: quoteAndConvert(installerPath, true),
                            logFilePath: quoteAndConvert(logFilePath, true),
                            installStatusFilePath: installStatusFilePath
                        };
                    }
                } else {
                    status = {
                        valid: false,
                        err: nodeErrorMessages.CHECKSUM_DID_NOT_MATCH
                    };
                }
                postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status);
            });
        } else {
            var status = {
                valid: false,
                err: nodeErrorMessages.INSTALLER_NOT_FOUND
            };
            postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status);
        }
    }
1254296
function validateDV(value, options) {
	var steps = options.algorithmSteps;

	// Step 01: Handle String
	var handledStr = algorithmSteps.handleStr[steps[0]](value);

	// Step 02: Sum chars
	var sum = algorithmSteps.sum[steps[1]](handledStr, options.pesos);

	// Step 03: Rest calculation
	var rest = algorithmSteps.rest[steps[2]](sum);

	// Fixed Step: Get current DV
	var currentDV = parseInt(handledStr[options.dvpos]);

	// Step 04: Expected DV calculation
	var expectedDV = algorithmSteps.expectedDV[steps[3]](rest, handledStr);

	// Fixed step: DV verification
	return currentDV === expectedDV;
}
651071
function checksum(number) {
	var res = number.substr(0, 7).split('').map(function (n) {
		return +n;
	}).reduce(function (sum, a, idx) {
		return idx % 2 ? sum + a : sum + a * 3;
	}, 0);

	return (10 - res % 10) % 10;
}
103570
function checkSum(buffer, offset, length) {
            if (buffer instanceof ArrayBuffer) {
                return checkSumArrayBuffer(buffer, offset, length);
            }
            else if (buffer instanceof Array) {
                return checkSumArray(buffer, offset, length);
            }

            throw new Error('not support checksum buffer type');
        }