later_mci is already known and not included in the chain
437258
function buildProofChainOnMc(later_mci, earlier_mci, arrBalls, onDone){
	
	function addBall(mci){
		if (mci < 0)
			throw Error("mci<0, later_mci="+later_mci+", earlier_mci="+earlier_mci);
		db.query("SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function(rows){
			if (rows.length !== 1)
				throw Error("no prev chain element? mci="+mci+", later_mci="+later_mci+", earlier_mci="+earlier_mci);
			var objBall = rows[0];
			if (objBall.content_hash)
				objBall.is_nonserial = true;
			delete objBall.content_hash;
			db.query(
				"SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", 
				[objBall.unit],
				function(parent_rows){
					if (parent_rows.some(function(parent_row){ return !parent_row.ball; }))
						throw Error("some parents have no balls");
					if (parent_rows.length > 0)
						objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; });
					db.query(
						"SELECT ball, main_chain_index \n\
						FROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \n\
						WHERE skiplist_units.unit=? ORDER BY ball", 
						[objBall.unit],
						function(srows){
							if (srows.some(function(srow){ return !srow.ball; }))
								throw Error("some skiplist units have no balls");
							if (srows.length > 0)
								objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; });
							arrBalls.push(objBall);
							if (mci === earlier_mci)
								return onDone();
							if (srows.length === 0) // no skiplist
								return addBall(mci-1);
							var next_mci = mci - 1;
							for (var i=0; i<srows.length; i++){
								var next_skiplist_mci = srows[i].main_chain_index;
								if (next_skiplist_mci < next_mci && next_skiplist_mci >= earlier_mci)
									next_mci = next_skiplist_mci;
							}
							addBall(next_mci);
						}
					);
				}
			);
		});
	}
	
	if (earlier_mci > later_mci)
		throw Error("earlier > later");
	if (earlier_mci === later_mci)
		return onDone();
	addBall(later_mci - 1);
}
560524
function flagBundlesIncludedByCommonParentModule(modules,bundles) {
	var
		 bundleToModule = extractBundleToModuleMap(modules),
		 bundleMap = extractBundleMap(bundles.bundlesArray),
		 moduleAncestors = {},
		 modulesArray, x, commonAncestor;
	
	for( x in bundleToModule ) {
		if( !bundleToModule.hasOwnProperty(x) ) continue;
		modulesArray = bundleToModule[x];
		commonAncestor = extractCommonAncestor(modulesArray);
		if( commonAncestor != null ) {
			includeBundleInModule(bundleMap[x], commonAncestor);
		}
	}
	
	
	function extractBundleToModuleMap(modules) {
		var x, i, ret = {}, bundleDeps, dependentModules;
		for( x in modules ) {
			if( !modules.hasOwnProperty(x) ) continue;
			bundleDeps = modules[x].bundleDeps;
			for( i=0; i < bundleDeps.length; i++ ) {
				if( bundleDeps[i].exclusive ) continue;
				dependentModules = ret[bundleDeps[i].id];
				if( dependentModules == null ) {
					dependentModules = [];
					ret[bundleDeps[i].id] = dependentModules;
				}
				dependentModules.push(modules[x]);
			}
		}
		return ret;
	}
	
	function extractBundleMap(bundlesArray) {
		var i, ret = {};
		for( i=0; i < bundlesArray.length; i++ ) {
			ret[bundlesArray[i].id] = bundlesArray[i];
		}
		return ret;
	}
	
	function findAllAncestors(module) {
		var ret = moduleAncestors[module.name];
		if( ret == null ) {
			ret = [];
			moduleAncestors[module.name] = ret;
			addParents(ret, module);
		}
		return ret;
		
		function addParents(ret, module) {
			var i, j, grandParents;
			for( i=0; i < module.parents.length; i++ ) {
				if( ret.indexOf(module.parents[i]) < 0 ) {
					ret.push(module.parents[i]);
					grandParents = findAllAncestors(modules[module.parents[i]]);
					for( j=0; j < grandParents.length; j++ ) {
						if( ret.indexOf(grandParents[j]) < 0 ) ret.push(grandParents[j]);
					}
				}
				
			}
		}
	}
	
	function isAncestor(potentialAncestorModuleName, module) {
		if( typeof(module) === "string" ) module = modules[module];
		var a = findAllAncestors(module);
		return a.indexOf(potentialAncestorModuleName) >= 0;
	}
	
	function extractCommonAncestor(modulesArray) {
		var i, j, foundNonAncestor;
		for( i=0; i < modulesArray.length; i++ ) {
			foundNonAncestor = false;
			for( j=0; j < modulesArray.length; j++ ) {
				if( i !== j ) {
					if( !isAncestor(modulesArray[i].name, modulesArray[j]) ) {
						foundNonAncestor = true;
						break;
					}
				}
			}
			if( !foundNonAncestor ) {
				return modulesArray[i];
			}
		}
		return null;
	}
	
	function includeBundleInModule(bundle, module) {
		var i, index, newExcludedDeps = [];
		bundle.includedIn = module.name;
		// re-enable bundle deps in module
		for( i=0; i < bundle.deps.length; i++ ) {
			index = module.excludedDeps.indexOf(bundle.deps[i]);
			module.excludedDeps[index] = false
		}
		for( i=0; i < module.excludedDeps.length; i++ ) {
			if( module.excludedDeps[i] === false ) continue;
			newExcludedDeps.push(module.excludedDeps[i]);
		}
		module.excludedDeps = newExcludedDeps;
	}
}
559053
void setChainUserIndex(int chain, int index, int value) {
		int i = getChainIndex_(chain);
		AttributeStreamOfInt32 stream = m_chainIndices.get(index);
		if (stream.size() <= i)
			stream.resize(m_chainData.size(), -1);

		stream.write(i, value);
	}
185722
def toolchain(name, tc)
      raise "not a tc" unless tc.is_a?(Hash)
      check_hash(tc, Cxxproject::Toolchain::Provider.default.keys)
      check_compiler(tc[:COMPILER]) if tc[:COMPILER]
      check_linker(tc[:LINKER]) if tc[:LINKER]
      check_archiver(tc[:ARCHIVER]) if tc[:ARCHIVER]
      PluginContext::expand(tc)
      Cxxproject::Toolchain::Provider.add(name)
      Cxxproject::Toolchain::Provider.merge(Cxxproject::Toolchain::Provider[name], tc)
    end
1277519
function onAfterInit()
    {
        foreach ((array)$this->owner->config()->include_requirements_from_class as $class => $method) {
            if (is_numeric($class)) {
                singleton($method)->includes($this->owner);
            } else {
                singleton($class)->$method($this->owner);
            }
        }

        if($this->owner instanceof \KickAssets) {
            return;
        }

        Requirements::javascript(singleton('env')->get('mwm-utilities.dir', basename(rtrim(dirname(dirname(dirname(dirname(__FILE__)))), DIRECTORY_SEPARATOR))) . '/js/mwm.core.leftandmain.js');
    }
427018
function __chain_inner(result) {
		var args = slice.call(arguments, 1);
		nextTick(function() {
			try {
				if (result) {
					var params = that.handle_args(env, that.if_true, args);
					params.unshift(env, after);
					env._fm.$push_call(helpers.fname(that.if_true, that.if_true.fn.name));
					that.if_true.fn.apply(null, params);
				}
				else {
					var params = that.handle_args(env, that.if_false, args);
					params.unshift(env, after);
					env._fm.$push_call(helpers.fname(that.if_false, that.if_false.fn.name));
					that.if_false.fn.apply(null, params);
				}
			}
			catch (e) {
				env.$throw(e);
			}
		});
	}
635351
public final void chainInitialized() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "chainInitialized, chain: " + this.name);
        }
        // Clone the list in case one of the event listeners modifies
        // the chain during this iteration.
        for (ChainEventListener listener : chainEventListeners) {
            listener.chainInitialized(this);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "chainInitialized");
        }
    }
582326
private static Chain isKnownChain(String asymId, List<Chain> chains){

		for (int i = 0; i< chains.size();i++){
			Chain testchain =  chains.get(i);
			//System.out.println("comparing chainID >"+chainID+"< against testchain " + i+" >" +testchain.getName()+"<");
			if (asymId.equals(testchain.getId())) {
				//System.out.println("chain "+ chainID+" already known ...");
				return testchain;
			}
		}

		return null;
	}
487246
def add_chain(self, *nodes, _input=BEGIN, _output=None, _name=None):
        
        if len(nodes):
            _input = self._resolve_index(_input)
            _output = self._resolve_index(_output)
            _first = None
            _last = None

            for i, node in enumerate(nodes):
                _last = self.add_node(node)
                if not i and _name:
                    if _name in self.named:
                        raise KeyError("Duplicate name {!r} in graph.".format(_name))
                    self.named[_name] = _last
                if _first is None:
                    _first = _last
                self.outputs_of(_input, create=True).add(_last)
                _input = _last

            if _output is not None:
                self.outputs_of(_input, create=True).add(_output)

            if hasattr(self, "_topologcally_sorted_indexes_cache"):
                del self._topologcally_sorted_indexes_cache

            return GraphRange(self, _first, _last)
        return GraphRange(self, None, None)
772189
def spawn_missing_master(self):
        '''
        
        '''
        d = defer.succeed(None)
        if callable(self.on_master_missing_cb):
            d.addCallback(defer.drop_param, self.on_master_missing_cb)
        return d
672247
function (options, iterationInfo, modules) {

        // Ignore explicitly excluded directories
        if (options.excludeDirs) {
            var match = iterationInfo.fileName.match(options.excludeDirs);
            if (match)
                return;
        }

        // Recursively call requireAll on each child directory
        var subIterationInfo = _.clone(iterationInfo);
        ++subIterationInfo.depth;
        subIterationInfo.dirName = iterationInfo.absoluteFullPath;

        //process subtree recursively
        var subTreeResult = doInterations(options, subIterationInfo);

        //omit empty dirs
        if (_.isEmpty(subTreeResult))
            return;

        //add to the list or to the subtree
        if (options.mode === 'list') {
            //check uniqueness
            _.forEach(subTreeResult, function (value, index) {
                if (options.useVersions === true) {
                    modules[index] = modules[index] || {};
                    _.forEach(value, function (versionValue, versionIndex) {
                        if (modules[index][versionIndex])
                            throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
                        modules[index][versionIndex] = versionValue;
                    });
                }
                else {
                    if (modules[index])
                        throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
                    modules[index] = value;
                }
            })
        }
        else if (options.mode === 'tree') {
            if (options.markDirectories !== false) {
                subTreeResult.isDirectory = true;
            }

            var identity = generateIdentity(options, iterationInfo);
            modules[identity] = subTreeResult;
        }
        else
            throw new Error('Unknown mode');
    }
1066119
function addMachine(name) {
        return co(function*(){
            debug("Adding a new machine with the name '%s'", name);
            let manifest = getManifest();

            if(manifest.machines[name]) {
                debug("Machine already exists");
                throw new Error("Machine already exists");
            }

            manifest.machines[name] = {
                route: "machines/" + name,
                "versions": {
                    "version1": {
                        "route": "machines/" + name + "/versions/version1",
                        "instances": {}
                    }
                }
            };

            let machineDirPath = "machines/" + name;
            let machineVersionsDirPath = machineDirPath + "/versions";
            let version1DirPath = machineVersionsDirPath + "/version1";
            let version1InstancesDirPath = version1DirPath + "/instances";
            let modelFile = version1DirPath + '/model.scxml';
            let infoFile = version1DirPath + "/info.json";

            debug("Creating the directories");
            fs.mkdirSync(repositoryPath + "/" + machineDirPath);
            fs.mkdirSync(repositoryPath + "/" + machineVersionsDirPath);
            fs.mkdirSync(repositoryPath + "/" + version1DirPath);
            fs.mkdirSync(repositoryPath + "/" + version1InstancesDirPath);

            debug("Creating the base.scxml file");
            fs.copySync(__dirname + '/base.scxml', repositoryPath + "/" + modelFile);

            debug("Creating the version info.json file");
            let infoVersion1 = { "isSealed": false };
            jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion1);

            debug("Setting the manifest");
            setManifest(manifest);

            yield _commit(null, ["manifest.json", modelFile, infoFile], "Added '" + name + "' machine");
            debug("A new machine with the name '%s' was successfully added", name);
        });
    }
755858
function (chain) {
    const web3Provider = web3ProviderFactory.getProvider(chain, web3ProviderFactory.typeWS)
      , retryAttempts = 100
      , timerInterval = 5000
      , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0}
    ;
    if (!web3Provider) {
      // this is a error scenario.
      let errObj = responseHelper.error({
        internal_error_identifier: 's_u_ps_1',
        api_error_identifier: 'invalid_chain',
        error_config: basicHelper.fetchErrorConfig()
      });
      return Promise.reject(errObj);
    }

    return new Promise(function (onResolve, onReject) {
      chainTimer['timer'] = setInterval(function () {
        if (chainTimer['retryCounter'] <= retryAttempts) {
          web3Provider.eth.getBlockNumber(function (err, blocknumber) {
            if (err) {
              logger.error("Geth Checker - " + chain + " fetch block number failed.", err);
              chainTimer['retryCounter']++;
            } else {
              if (chainTimer['blockNumber'] != 0 && chainTimer['blockNumber'] != blocknumber) {
                clearInterval(chainTimer['timer']);
                onResolve(responseHelper.successWithData({}));
              }
              chainTimer['blockNumber'] = blocknumber;
            }
          });
        } else {
          logger.error("Geth Checker - " + chain + " chain has no new blocks.");

          let errObj = responseHelper.error({
            internal_error_identifier: 's_u_ps_2_' + chain,
            api_error_identifier: 'no_new_blocks',
            error_config: basicHelper.fetchErrorConfig()
          });
          onReject(errObj);
        }
        chainTimer['retryCounter']++;
      }, timerInterval);
    });

  }
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);
	
	});
}
868942
function (chain, type) {
    const oThis = this;
    if (oThis.valueChain === chain) {
      if (oThis.typeRPC === type) {
        return require(rootPrefix + '/lib/web3/providers/value_rpc');
      } else if (oThis.typeWS === type) {
        return require(rootPrefix + '/lib/web3/providers/value_ws');
      }
    } else if (oThis.utilityChain === chain) {
      if (oThis.typeRPC === type) {
        return require(rootPrefix + '/lib/web3/providers/utility_rpc');
      } else if (oThis.typeWS === type) {
        return require(rootPrefix + '/lib/web3/providers/utility_ws');
      }
    }
    return null;
  }
532665
@Override
    protected void alreadyProcessed(ClientlibRef ref, VisitorMode mode, ClientlibResourceFolder folder) {
        if (mode == EMBEDDED) {
            LOG.warn("Trying to embed already embedded / dependency {} again at {}", ref, folder);
        }
    }
725290
@Override
	public void setChainInfo(String chainId, String chainName, int groupCount) {
		// First check to see if the chain exists
		Map<String, Chain> modelChainMap = chainMap.get(modelNumber);
		if(modelChainMap.containsKey(chainId)){
			chain = modelChainMap.get(chainId);
		}
		// If we need to set a new chain do this
		else{
			chain = new ChainImpl();
			chain.setId(chainId.trim());
			chain.setName(chainName);
			chain.setAtomGroups(new ArrayList<>(groupCount));
			modelChainMap.put(chainId, chain);
			chainList.add(chain);
		}
	}