/* 18.6 Calculation Chain
764719
function parse_cc_xml(data, opts) {
	var d = [];
	if(!data) return d;
	var l = 0, i = 1;
	(data.match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(y[0]) {
			case '<?xml': break;
			/* 18.6.2  calcChain CT_CalcChain 1 */
			case '<calcChain': case '<calcChain>': case '</calcChain>': break;
			/* 18.6.1  c CT_CalcCell 1 */
			case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
		}
	});
	return d;
}
853164
static int calculateBCHCode(int value, int poly) {
    if (poly == 0) {
      throw new IllegalArgumentException("0 polynomial");
    }
    // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
    // from 13 to make it 12.
    int msbSetInPoly = findMSBSet(poly);
    value <<= msbSetInPoly - 1;
    // Do the division business using exclusive-or operations.
    while (findMSBSet(value) >= msbSetInPoly) {
      value ^= poly << (findMSBSet(value) - msbSetInPoly);
    }
    // Now the "value" is the remainder (i.e. the BCH code)
    return value;
  }
1308920
function calculatorDirective() {

    return {
        controller: Controller,
        controllerAs: 'ctrl',
        restrict: 'EA',
        scope: {},
        template: HTML
    };

    function Controller() {
        this.operand1 = null;
        this.operand2 = null;
        this.result = null;

        this.add = function() {
            this.result = parseInt(this.operand1) + parseInt(this.operand2);
        };

        this.isAddDisabled = function() {
            return isNaN(parseInt(this.operand1)) || isNaN(parseInt(this.operand2));
        };
    }
}
1063746
function _calcSize(&$raList) 
    {
        // Calculate Basic Setting
        list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0);
        $iSmallLen = 0;
        $iSBcnt = 0;
        for ($i = 0; $i < count($raList); $i++) {
            if ($raList[$i]->Type == OLE_PPS_TYPE_FILE) {
                $raList[$i]->Size = $raList[$i]->_DataLen();
                if ($raList[$i]->Size < OLE_DATA_SIZE_SMALL) {
                    $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE)
                                  + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0);
                } else {
                    $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) +
                        (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0));
                }
            }
        }
        $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE;
        $iSlCnt = floor($this->_BIG_BLOCK_SIZE / OLE_LONG_INT_SIZE);
        $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0);
        $iBBcnt +=  (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) +
                      (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0));
        $iCnt = count($raList);
        $iBdCnt = $this->_BIG_BLOCK_SIZE / OLE_PPS_SIZE;
        $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0));
   
        return array($iSBDcnt, $iBBcnt, $iPPScnt);
    }
847293
function stepThrough(node, debug=false) {
  if (debug) {
    // eslint-disable-next-line
    console.log('\n\nSimplifying: ' + print(node, false, true));
  }

  if(checks.hasUnsupportedNodes(node)) {
    return [];
  }

  let nodeStatus;
  const steps = [];

  const originalExpressionStr = print(node);
  const MAX_STEP_COUNT = 20;
  let iters = 0;

  // Now, step through the math expression until nothing changes
  nodeStatus = step(node);
  while (nodeStatus.hasChanged()) {
    if (debug) {
      logSteps(nodeStatus);
    }
    steps.push(removeUnnecessaryParensInStep(nodeStatus));
    const nextNode = Status.resetChangeGroups(nodeStatus.newNode);
    nodeStatus = step(nextNode);
    if (iters++ === MAX_STEP_COUNT) {
      // eslint-disable-next-line
      console.error('Math error: Potential infinite loop for expression: ' +
                    originalExpressionStr + ', returning no steps');
      return [];
    }
  }

  return steps;
}
194388
function multiplier(x) {
    var parts = x.toString().split('.');
    if (parts.length < 2) {
      return 1;
    }
    return Math.pow(10, parts[1].length);
  }
654245
function parseFunctionSourceElements() {
        var statement, body = [], token, directive, firstRestricted,
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
            node = new Node();

        expect('{');

        while (startIndex < length) {
            if (lookahead.type !== Token.StringLiteral) {
                break;
            }
            token = lookahead;

            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        oldLabelSet = state.labelSet;
        oldInIteration = state.inIteration;
        oldInSwitch = state.inSwitch;
        oldInFunctionBody = state.inFunctionBody;
        oldParenthesisCount = state.parenthesizedCount;

        state.labelSet = {};
        state.inIteration = false;
        state.inSwitch = false;
        state.inFunctionBody = true;
        state.parenthesizedCount = 0;

        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            body.push(parseStatementListItem());
        }

        expect('}');

        state.labelSet = oldLabelSet;
        state.inIteration = oldInIteration;
        state.inSwitch = oldInSwitch;
        state.inFunctionBody = oldInFunctionBody;
        state.parenthesizedCount = oldParenthesisCount;

        return node.finishBlockStatement(body);
    }
774632
private double computeDistUsingStrArray(InfoTree it1, InfoTree it2) {

		int postorder1 = it1.getCurrentNode();
		int postorder2 = it2.getCurrentNode();

		int stepStrategy = str[postorder1][postorder2];

		int tmpPostorder;

		int[] stepPath;
		int[] stepRelSubtrees;
		ArrayList<Integer> heavyPath;
		switch (stepStrategy) {
		case LEFT:
			tmpPostorder = postorder1;
			stepPath = it1.getPath(LEFT);
			// go along the path
			while (stepPath[postorder1] > -1) {
				stepRelSubtrees = it1.getNodeRelSubtrees(LEFT, postorder1);
				if (stepRelSubtrees != null) {
					// iterate over rel subtrees for a specific node on the path
					for (int rs : stepRelSubtrees) {
						it1.setCurrentNode(rs);
						// make the recursion
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder1 = stepPath[postorder1];
			}
			// set current node
			it1.setCurrentNode(tmpPostorder);
			it1.setSwitched(false);
			it2.setSwitched(false);
			// count the distance using a single-path function
			strStat[3]++;
			strStat[LEFT]++;
			return spfL(it1, it2);
		case RIGHT:
			tmpPostorder = postorder1;
			stepPath = it1.getPath(RIGHT);
			while (stepPath[postorder1] > -1) {
				stepRelSubtrees = it1.getNodeRelSubtrees(RIGHT, postorder1);
				if (stepRelSubtrees != null) {
					for (int rs : stepRelSubtrees) {
						it1.setCurrentNode(rs);
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder1 = stepPath[postorder1];
			}
			it1.setCurrentNode(tmpPostorder);
			it1.setSwitched(false);
			it2.setSwitched(false);
			strStat[3]++;
			strStat[RIGHT]++;
			return spfR(it1, it2);
		case HEAVY:
			tmpPostorder = postorder1;
			stepPath = it1.getPath(HEAVY);
			heavyPath = new ArrayList<Integer>();
			heavyPath.add(postorder1);
			while (stepPath[postorder1] > -1) {
				stepRelSubtrees = it1.getNodeRelSubtrees(HEAVY, postorder1);
				if (stepRelSubtrees != null) {
					for (int rs : stepRelSubtrees) {
						it1.setCurrentNode(rs);
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder1 = stepPath[postorder1];
				heavyPath.add(postorder1);
			}
			it1.setCurrentNode(tmpPostorder);
			it1.setSwitched(false);
			it2.setSwitched(false);
			strStat[3]++;
			strStat[HEAVY]++;
			return spfH(it1, it2, InfoTree.toIntArray(heavyPath));
		case REVLEFT:
			tmpPostorder = postorder2;
			stepPath = it2.getPath(LEFT);
			while (stepPath[postorder2] > -1) {
				stepRelSubtrees = it2.getNodeRelSubtrees(LEFT, postorder2);
				if (stepRelSubtrees != null) {
					for (int rs : stepRelSubtrees) {
						it2.setCurrentNode(rs);
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder2 = stepPath[postorder2];
			}
			it2.setCurrentNode(tmpPostorder);
			it1.setSwitched(true);
			it2.setSwitched(true);
			strStat[3]++;
			strStat[LEFT]++;
			return spfL(it2, it1);
		case REVRIGHT:
			tmpPostorder = postorder2;
			stepPath = it2.getPath(RIGHT);
			while (stepPath[postorder2] > -1) {
				stepRelSubtrees = it2.getNodeRelSubtrees(RIGHT, postorder2);
				if (stepRelSubtrees != null) {
					for (int rs : stepRelSubtrees) {
						it2.setCurrentNode(rs);
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder2 = stepPath[postorder2];
			}
			it2.setCurrentNode(tmpPostorder);
			it1.setSwitched(true);
			it2.setSwitched(true);
			strStat[3]++;
			strStat[RIGHT]++;
			return spfR(it2, it1);
		case REVHEAVY:
			tmpPostorder = postorder2;
			stepPath = it2.getPath(HEAVY);
			heavyPath = new ArrayList<Integer>();
			heavyPath.add(postorder2);
			while (stepPath[postorder2] > -1) {
				stepRelSubtrees = it2.getNodeRelSubtrees(HEAVY, postorder2);
				if (stepRelSubtrees != null) {
					for (int rs : stepRelSubtrees) {
						it2.setCurrentNode(rs);
						computeDistUsingStrArray(it1, it2);
					}
				}
				postorder2 = stepPath[postorder2];
				heavyPath.add(postorder2);
			}
			it2.setCurrentNode(tmpPostorder);
			it1.setSwitched(true);
			it2.setSwitched(true);
			strStat[3]++;
			strStat[HEAVY]++;
			return spfH(it2, it1, InfoTree.toIntArray(heavyPath));
		default:
			return -1;
		}
	}
112300
function calcSteps (min, max, room, width) {
  var range = max - min
  var i = 0, e

  while(true) {
    var e = Math.pow(10, i++)
    if(e > 10000000000)
      throw new Error('oops')

    var re = range/e
    var space = width*1.25

    if(room     / (re) > space) return e
    if(room*2   / (re) > space) return e*2
    if(room*2.5 / (re) > space) return e*2.5
    if(room*5   / (re) > space) return e*5
  }
}
360880
function calculProgress(navigation, current) {
    var n = _.size(navigation);
    var percent = 0, prevPercent = 0, currentChapter = null;
    var done = true;

    var chapters = _.chain(navigation)

    // Transform as array
    .map(function(nav, path) {
        nav.path = path;
        return nav;
    })

    // Sort entries
    .sortBy(function(nav) {
        return nav.index;
    })

    .map(function(nav, i) {
        // Calcul percent
        nav.percent = (i * 100) / Math.max((n - 1), 1);

        // Is it done
        nav.done = done;
        if (nav.path == current) {
            currentChapter = nav;
            percent = nav.percent;
            done = false;
        } else if (done) {
            prevPercent = nav.percent;
        }

        return nav;
    })
    .value();

    return {
        // Previous percent
        prevPercent: prevPercent,

        // Current percent
        percent: percent,

        // List of chapter with progress
        chapters: chapters,

        // Current chapter
        current: currentChapter
    };
}
514009
function promiseChain (cb) {
  var steps = []
    , vals = []
    , context = this
  function go () {
    var step = steps.shift()
    if (!step) return cb()
    try { step[0].apply(context, step[1]) }
    catch (ex) { cb(ex) }
  }
  return function pc (fn, args, success) {
    if (arguments.length === 0) return go()
    // add the step
    steps.push
      ( [ fn
        , (args || []).concat([ function (er) {
            if (er) return cb(er)
            var a = Array.prototype.slice.call(arguments, 1)
            try { success && success.apply(context, a) }
            catch (ex) { return cb(ex) }
            go()
          }])
        ]
      )
    return pc
  }
}
1197886
function checkNumberOrInterpolation(i) {
  const start = i;
  let l;

  while (i < tokensLength) {
    if (l = checkInterpolation(i) || checkNumber(i)) i += l;
    else break;
  }

  return i - start;
}
775745
private static Group[] chainAfp(FatCatParameters params,AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws StructureException{

		// we don;t want to rotate input atoms, do we?
		Atom[] ca2clone = StructureTools.cloneAtomArray(ca2);

		List<AFP> afpSet = afpChain.getAfpSet();

		if (debug)
			System.out.println("entering chainAfp");
		int afpNum = afpSet.size();

		if ( afpNum < 1)
			return new Group[0];

		long bgtime = System.currentTimeMillis();
		if(debug)    {
			System.out.println(String.format("total AFP %d\n", afpNum));
		}

		//run AFP chaining

		AFPChainer.doChainAfp(params,afpChain ,ca1,ca2);

		int afpChainLen = afpChain.getAfpChainLen();

		if(afpChainLen < 1)     {

			afpChain.setShortAlign(true);
			return new Group[0];
		} //very short alignment

		long chaintime = System.currentTimeMillis();
		if(debug)    {

			System.out.println("Afp chaining: time " + (chaintime-bgtime));
		}

		// do post processing

		AFPPostProcessor.postProcess(params, afpChain,ca1,ca2);

		// Optimize the final alignment

		AFPOptimizer.optimizeAln(params, afpChain,ca1,ca2);

		AFPOptimizer.blockInfo( afpChain);

		AFPOptimizer.updateScore(params,afpChain);

		AFPAlignmentDisplay.getAlign(afpChain,ca1,ca2);

		Group[] twistedPDB = AFPTwister.twistPDB(afpChain, ca1, ca2clone);

		SigEva sig =  new SigEva();
		double probability = sig.calSigAll(params, afpChain);
		afpChain.setProbability(probability);
		double normAlignScore = sig.calNS(params,afpChain);
		afpChain.setNormAlignScore(normAlignScore);
		double tmScore = AFPChainScorer.getTMScore(afpChain, ca1, ca2,false);
		afpChain.setTMScore(tmScore);

		/*

		SIGEVA  sig;
		probability = sig.calSigAll(maxTra, sparse, pro1Len, pro2Len, alignScore, totalRmsdOpt, optLength, blockNum - 1);
		normAlignScore = sig.calNS(pro1Len, pro2Len, alignScore, totalRmsdOpt, optLength, blockNum - 1);

		 */

		//if(maxTra == 0)       probability = sig.calSigRigid(pro1Len, pro2Len, alignScore, totalRmsdOpt, optLength);
		//else  probability = sig.calSigFlexi(pro1Len, pro2Len, alignScore, totalRmsdOpt, optLength, blockNum - 1);

		if(debug)    {

			long nowtime = System.currentTimeMillis();
			long diff = nowtime - chaintime;
			System.out.println("Alignment optimization: time "+ diff);

			System.out.println("score:      " + afpChain.getAlignScore());
			System.out.println("opt length: " + afpChain.getOptLength());
			System.out.println("opt rmsd:   "+ afpChain.getTotalRmsdOpt());

		}
		return twistedPDB;

	}
1105995
function(n){

    	if(!_.isNumber(n)){
            return;
	    }

        // Avoid stepping over
        if(this._data[this._itr + n] === undefined){
            return;
        }

        // Advance num steps
        this._itr += n;
    }
1199331
private static void calculateClosure(Fst fst, State state, HashMap<Integer,Double>[] closure, Semiring semiring, int iEps, int oEps) {

    for (int j = 0; j < state.getArcCount(); j++) {
      Arc arc = state.getArc(j);
      if ((arc.getIlabel() != iEps) || (arc.getOlabel() != oEps)) {
        continue;
      }
      int nextStateId = arc.getNextState().getId();
      if (closure[nextStateId] == null) {
        calculateClosure(fst, arc.getNextState(), closure, semiring, iEps, oEps);
      }
      HashMap<Integer,Double> closureEntry = closure[nextStateId];
      if (closureEntry != null) {
        for (Integer pathFinalStateIndex : closureEntry.keySet()) {
          State pathFinalState = fst.getState(pathFinalStateIndex);
          Double prevPathWeight = getPathWeight(arc.getNextState(), pathFinalState, closure);
          Preconditions.checkNotNull(prevPathWeight, "prev arc %s never set in closure", arc);
          double newPathWeight = semiring.times(prevPathWeight, arc.getWeight());
          add(state, pathFinalState, newPathWeight, closure, semiring);
        }
      }
      add(state, arc.getNextState(), arc.getWeight(), closure, semiring);
    }
  }
1125341
function determineIfIncluded(conn, earlier_unit, arrLaterUnits, handleResult){
	if (!earlier_unit)
		throw Error("no earlier_unit");
	if (storage.isGenesisUnit(earlier_unit))
		return handleResult(true);
	storage.readPropsOfUnits(conn, earlier_unit, arrLaterUnits, function(objEarlierUnitProps, arrLaterUnitProps){
		if (objEarlierUnitProps.is_free === 1)
			return handleResult(false);
		
		var max_later_limci = Math.max.apply(
			null, arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.latest_included_mc_index; }));
		//console.log("max limci "+max_later_limci+", earlier mci "+objEarlierUnitProps.main_chain_index);
		if (objEarlierUnitProps.main_chain_index !== null && max_later_limci >= objEarlierUnitProps.main_chain_index)
			return handleResult(true);
		
		var max_later_level = Math.max.apply(
			null, arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.level; }));
		if (max_later_level < objEarlierUnitProps.level)
			return handleResult(false);
		
		function goUp(arrStartUnits){
			//console.log('determine', earlier_unit, arrLaterUnits, arrStartUnits);
			conn.query(
				"SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \n\
				FROM parenthoods JOIN units ON parent_unit=unit \n\
				WHERE child_unit IN(?)",
				[arrStartUnits],
				function(rows){
					var arrNewStartUnits = [];
					for (var i=0; i<rows.length; i++){
						var objUnitProps = rows[i];
						if (objUnitProps.unit === earlier_unit)
							return handleResult(true);
						if (objUnitProps.is_on_main_chain === 0 && objUnitProps.level > objEarlierUnitProps.level)
							arrNewStartUnits.push(objUnitProps.unit);
					}
					(arrNewStartUnits.length > 0) ? goUp(_.uniq(arrNewStartUnits)) : handleResult(false);
				}
			);
		}
		
		goUp(arrLaterUnits);
	
	});
}
216086
function(year) {
			var last = this._delay1(year - 1);
			var present = this._delay1(year);
			var next = this._delay1(year + 1);
			return ((next - present) === 356 ? 2 : ((present - last) === 382 ? 1 : 0));
		}