Java Code Examples for java.util.ArrayList#size()

The following examples show how to use java.util.ArrayList#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void updateActuatorNames()
{
   ArrayList<String> namesList = new ArrayList<String>(4);
   ForceSet actuators = model.getForceSet();
   if (actuators != null) {
      for (int i=0; i<actuators.getSize(); i++) {
         Force act =actuators.get(i);
         Muscle muscle = Muscle.safeDownCast(act);
         if (muscle != null) {
            namesList.add(muscle.getName());
         }
       }
   }
   actuatorNames = new String[namesList.size()];
   System.arraycopy(namesList.toArray(), 0, actuatorNames, 0, namesList.size());
   java.util.Arrays.sort(actuatorNames);
}
 
Example 2
public Gaussian(String name, ArrayList<Parameter> params, int steps) throws InstantiationException {
    super(name);

    if(params.size()!=1){
        throw new InstantiationException("Wrong number of parameters for this spatial kernal function");
    }

    if(!params.get(0).getId().equals(ALPHA)){
        throw new InstantiationException("No parameter named alpha");
    }

    this.alpha = params.get(0);
    addVariable(alpha);


    integrator = new RiemannApproximation(steps);
}
 
Example 3
/**
 * Adds a Cqlistener to the end of the list of Cqlisteners on this CqQuery.
 * @param cql the user defined cq listener to add to the CqQuery.
 * @throws IllegalArgumentException if <code>aListener</code> is null
 */ 
public void addCqListener(CqListener cql)
{
  if (cql == null) {
    throw new IllegalArgumentException(LocalizedStrings.CqAttributesFactory_ADDCQLISTENER_PARAMETER_WAS_NULL.toLocalizedString());
  }
  synchronized (this.clSync) {
    ArrayList oldListeners = this.cqListeners;
    if (oldListeners == null || oldListeners.size() == 0) {
      ArrayList al = new ArrayList(1);
      al.add(cql);
      this.cqListeners = al;
    }
    else {
      if (!oldListeners.contains(cql)) {
        oldListeners.add(cql);
      }
    }
  }
}
 
Example 4
Source Project: Digital   File: Transition.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return the condition
 * @throws FiniteStateMachineException FiniteStateMachineException
 */
Expression getConditionExpression() throws FiniteStateMachineException {
    if (conditionExpression == null) {
        if (condition != null && condition.trim().length() > 0)
            try {
                ArrayList<Expression> ex = new Parser(condition).parse();
                if (ex.size() != 1)
                    throw new FiniteStateMachineException(Lang.get("err_fsmErrorInCondition_N", condition));

                this.conditionExpression = ex.get(0);
            } catch (IOException | ParseException e) {
                throw new FiniteStateMachineException(Lang.get("err_fsmErrorInCondition_N", condition), e);
            }
    }
    return conditionExpression;
}
 
Example 5
@NonNull
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    try {
        Field uriField = ContentProviderOperation.class.getDeclaredField("mUri");
        uriField.setAccessible(true);
        for (ContentProviderOperation operation : operations) {
            Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(KEY_URI));
            uriField.set(operation, pluginUri);
        }
    } catch (Exception e) {
        return new ContentProviderResult[0];
    }

    if (operations.size() > 0) {
        ContentProvider provider = getContentProvider(operations.get(0).getUri());
        if (provider != null) {
            return provider.applyBatch(operations);
        }
    }

    return new ContentProviderResult[0];
}
 
Example 6
/**
 * Remove unnecessary mappings from sparse array.
 */
private void cleanMapping() {
    ArrayList<Integer> toRemove = new ArrayList<Integer>();

    int size = mListMapping.size();
    for (int i = 0; i < size; ++i) {
        if (mListMapping.keyAt(i) == mListMapping.valueAt(i)) {
            toRemove.add(mListMapping.keyAt(i));
        }
    }

    size = toRemove.size();
    for (int i = 0; i < size; ++i) {
        mListMapping.delete(toRemove.get(i));
    }
}
 
Example 7
@Test
public void testDashboard_recommendedCoordinates() {
  Nodes recommendedListItem = dashboard.query("//ul[@id='recommended']/li");
  Assert.assertTrue(recommendedListItem.size() > 100);

  // fails if these are not valid Maven coordinates
  for (Node node : recommendedListItem) {
    new DefaultArtifact(node.getValue());
  }

  ImmutableList<String> coordinateList =
      Streams.stream(recommendedListItem).map(Node::getValue).collect(toImmutableList());
  
  ArrayList<String> sorted = new ArrayList<>(coordinateList);
  Comparator<String> comparator = new SortWithoutVersion();
  Collections.sort(sorted, comparator);

  for (int i = 0; i < sorted.size(); i++) {
    Assert.assertEquals(
        "Coordinates are not sorted: ", sorted.get(i), coordinateList.get(i));
  }
}
 
Example 8
@Override
public int defenseProc( Char enemy, int damage ) {

	ArrayList<Integer> spawnPoints = new ArrayList<>();
	
	for (int i=0; i < PathFinder.NEIGHBOURS8.length; i++) {
		int p = pos + PathFinder.NEIGHBOURS8[i];
		if (Actor.findChar( p ) == null && (Dungeon.level.passable[p] || Dungeon.level.avoid[p])) {
			spawnPoints.add( p );
		}
	}
	
	if (spawnPoints.size() > 0) {
		Larva larva = new Larva();
		larva.pos = Random.element( spawnPoints );
		
		GameScene.add( larva );
		Actor.addDelayed( new Pushing( larva, pos, larva.pos ), -1 );
	}

	for (Mob mob : Dungeon.level.mobs) {
		if (mob instanceof BurningFist || mob instanceof RottingFist || mob instanceof Larva) {
			mob.aggro( enemy );
		}
	}

	return super.defenseProc(enemy, damage);
}
 
Example 9
Source Project: SampleCode   File: LatencyPercentileTests.java    License: MIT License 5 votes vote down vote up
public void run(@NotNull CommandLineArgs options) {

        int threads = options.getThreadCount();
        int iterations = options.getIterationCount();

        ArrayList<WorkerThread> list = new ArrayList<WorkerThread>();

        try {
            Logging.writeLine("Starting %d thread(s), %d iteration(s), using client %s", threads, iterations, Redis.getClient().getClass().getSimpleName());

            for(int i = 0; i < threads; i++)
                list.add(startLoadTest(iterations));

            Thread.sleep(1000);
            Logging.writeLine("\r\nwaiting for iterations to complete...");

            while(list.size() > 0)
            {
                WorkerThread t = list.remove(0);
                while (t.isAlive())
                {
                    Logging.write(".");
                    Thread.sleep(1000);
                }
            }

            Logging.writeLine("\r\nResult aggregation complete...");

            printResults();

        }
        catch(Exception ex) {

            Logging.logException(ex);
        }
    }
 
Example 10
/**
 * Adds a new env key to the list of env keys. If a kay with a given key name exists the new key
 * value replaces the old.
 *
 * @param aEnvKeyName the a env key name
 * @param aEnvKeyValue the a env key value
 * @throws CpeDescriptorException the cpe descriptor exception
 */
@Override
public void addExecEnv(String aEnvKeyName, String aEnvKeyValue) throws CpeDescriptorException {
  CasProcessorRunInSeperateProcess rip = getRunInSeparateProcess();
  if (rip != null) {
    CasProcessorExecutable exe = rip.getExecutable();
    if (exe != null) {
      ArrayList envs = exe.getEnvs();
      NameValuePair nvp;
      boolean replacedExisiting = false;

      for (int i = 0; envs != null && i < envs.size(); i++) {
        nvp = (NameValuePair) envs.get(i);
        if (nvp.getName().equals(aEnvKeyName)) {
          nvp.setValue(aEnvKeyValue);
          replacedExisiting = true;
          break; // done
        }
      }
      if (envs != null && !replacedExisiting) {
        nvp = new NameValuePairImpl(aEnvKeyName, aEnvKeyValue);
        envs.add(nvp);
      }
    }
  }

  // }
}
 
Example 11
/**
 * 获取本手牌已下注的玩家下的最大注
 * 
 * @param betStates
 * @return
 */
private int getMaxBet(ArrayList<BetState> betStates) {
	int maxBet = 0;
	for (int i = 0; i < betStates.size(); i++) {
		if (betStates.get(i).getBet() > maxBet)
			maxBet = betStates.get(i).getBet();
	}
	return maxBet;
}
 
Example 12
Source Project: litho   File: TransitionUtils.java    License: Apache License 2.0 5 votes vote down vote up
static boolean targetsAllLayout(@Nullable Transition transition) {
  if (transition == null) {
    return false;
  } else if (transition instanceof TransitionSet) {
    ArrayList<Transition> children = ((TransitionSet) transition).getChildren();
    for (int i = 0, size = children.size(); i < size; i++) {
      if (targetsAllLayout(children.get(i))) {
        return true;
      }
    }
  } else if (transition instanceof Transition.TransitionUnit) {
    final Transition.TransitionUnit unit = (Transition.TransitionUnit) transition;
    final Transition.ComponentTargetType targetType =
        unit.getAnimationTarget().componentTarget.componentTargetType;
    if (targetType == Transition.ComponentTargetType.ALL
        || targetType == Transition.ComponentTargetType.AUTO_LAYOUT) {
      return true;
    }
  } else if (transition instanceof Transition.BaseTransitionUnitsBuilder) {
    final Transition.BaseTransitionUnitsBuilder builder =
        (Transition.BaseTransitionUnitsBuilder) transition;
    final List<Transition.TransitionUnit> units = builder.getTransitionUnits();
    for (int i = 0, size = units.size(); i < size; i++) {
      if (targetsAllLayout(units.get(i))) {
        return true;
      }
    }
  } else {
    throw new RuntimeException("Unhandled transition type: " + transition);
  }

  return false;
}
 
Example 13
/**
 * Gets the all data source.
 *
 * @return the all data source
 */
public SpagoBiDataSource[] getAllDataSource() {
	logger.debug("IN");
	ArrayList tmpList = new ArrayList();

	// gets all data source from database
	try {
		List lstDs = DAOFactory.getDataSourceDAO().loadAllDataSources();
		if (lstDs == null) {
			logger.warn("Data sources aren't found on the database.");
			return null;
		}

		Iterator dsIt = lstDs.iterator();
		while (dsIt.hasNext()) {
			IDataSource ds = (IDataSource) dsIt.next();
			SpagoBiDataSource sbds = toSpagoBiDataSource(ds);
			tmpList.add(sbds);
		}
	} catch (Exception e) {
		logger.error("The data sources are not correctly returned", e);
	}
	// mapping generic array list into array of SpagoBiDataSource objects
	SpagoBiDataSource[] arDS = new SpagoBiDataSource[tmpList.size()];
	for (int i = 0; i < tmpList.size(); i++) {
		arDS[i] = (SpagoBiDataSource) tmpList.get(i);
	}
	logger.debug("OUT");
	return arDS;
}
 
Example 14
Source Project: java-technology-stack   File: AVLTree.java    License: MIT License 5 votes vote down vote up
public boolean isBST(){

        ArrayList<K> keys = new ArrayList<>();
        inOrder(root, keys);
        for(int i = 1 ; i < keys.size() ; i ++)
            if(keys.get(i - 1).compareTo(keys.get(i)) > 0)
                return false;
        return true;
    }
 
Example 15
Source Project: gemfirexd-oss   File: SQLDistTxTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void processDerbyOpsWithBatching(Connection dConn,
    boolean compareQuery) {
  if (dConn == null)
    return;
  ArrayList<Object[]> ops = (ArrayList<Object[]>) derbyOps.get();
  if (ops == null)
    Log.getLogWriter().info("derby ops is not set");
  else {
    for (int i = 0; i < ops.size(); i++) {
      Object[] derbyOp = ops.get(i);
      DMLDistTxStmtIF dmlStmt = null;
      if (useNewTables)
        dmlStmt = dmlDistTxFactory
            .createNewTablesDMLDistTxStmt((Integer) derbyOp[0]);
      else
        dmlStmt = dmlDistTxFactory.createDMLDistTxStmt((Integer) derbyOp[0]);

      String operation = (String) derbyOp[1];

      if (operation.equals("insert")) {
        dmlStmt.insertDerby(dConn, i);
      } else if (operation.equals("update")) {
        dmlStmt.updateDerby(dConn, i);
      } else if (operation.equals("delete"))
        dmlStmt.deleteDerby(dConn, i);
      else if (operation.equals("query")) {
        if (compareQuery)
          dmlStmt.queryDerby(dConn, i);
      } else
        throw new TestException("Unknown entry operation: " + operation);
    }
    resetDerbyOps();
  }
}
 
Example 16
private Integer[] getKey(String refName, int pos, int pos2) {
        Integer tmpList[] = {null, null};
        ArrayList<BedRegion> keyList = null;
        try {
            keyList = regionsByChrom.get(refName);
            int i = 0;
            int found = 0;
            while (i < keyList.size() && found <2) {
                BedRegion tmp = keyList.get(i);
                if (pos >= tmp.start && pos < tmp.end) {
                    tmpList[0] = tmp.key;
                    found++;
                }
                if (pos2 >= tmp.start && pos2 < tmp.end) {
                    tmpList[1] = tmp.key;
                    found++;
                }
                i++;
            } 
/*
// old      
        for (BedRegion region: regions) {
            if (refName.equalsIgnoreCase(region.contig) && pos >= region.start && pos < region.end)
                tmpList[0] = region.key;
            if (refName.equalsIgnoreCase(region.contig) && pos2 >= region.start && pos2 < region.end)
                tmpList[1] = region.key;
        }

// last correct before
        Integer tmpList[] = {null, null};
        int p, p2;
        if(pos < pos2)  { p = pos; p2 = pos2; }
        else            { p = pos2; p2 = pos; }
        ArrayList<BedRegion> keyList =  regions.get(refName);
        if(keyList == null) return tmpList;
        int i = 0;
        while(i < keyList.size() && p > keyList.get(i).end)
            i++;
        if(i >= keyList.size()) {
            return tmpList;
        } else {
            if(p >=  keyList.get(i).start)
                tmpList[0] = keyList.get(i).key;
            while(i < keyList.size() && p2 > keyList.get(i).end)
                i++;
            if(i >= keyList.size())
                return tmpList;
            else {
                if(p2 >=  keyList.get(i).start ) 
                    tmpList[1] = keyList.get(i).key;
            }
        }
*/
            
        } catch (NullPointerException ex) {
            if(keyList == null) {
                Logger.DEBUG("refname " + refName + " not found");
                throw new NullPointerException("chromosome " + refName + " not found in reference");
            }
        }
        return tmpList;
    }
 
Example 17
Source Project: buck   File: EscapeAnalysis.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Replaces the use for a scalar replaceable array. Gets and puts become
 * move instructions, and array lengths and fills are handled. Can also
 * identify ArrayIndexOutOfBounds exceptions and throw them if detected.
 *
 * @param use {@code non-null;} move result instruction for array
 * @param prev {@code non-null;} instruction for instantiating new array
 * @param newRegs {@code non-null;} mapping of array indices to new
 * registers
 * @param deletedInsns {@code non-null;} set of instructions marked for
 * deletion
 */
private void replaceUse(SsaInsn use, SsaInsn prev,
                            ArrayList<RegisterSpec> newRegs,
                            HashSet<SsaInsn> deletedInsns) {
    int index;
    int length = newRegs.size();
    SsaInsn next;
    RegisterSpecList sources;
    RegisterSpec source, result;
    CstLiteralBits indexReg;

    switch (use.getOpcode().getOpcode()) {
        case RegOps.AGET:
            // Replace array gets with moves
            next = getMoveForInsn(use);
            sources = use.getSources();
            indexReg = ((CstLiteralBits) sources.get(1).getTypeBearer());
            index = indexReg.getIntBits();
            if (index < length) {
                source = newRegs.get(index);
                result = source.withReg(next.getResult().getReg());
                insertPlainInsnBefore(next, RegisterSpecList.make(source),
                                          result, RegOps.MOVE, null);
            } else {
                // Throw an exception if the index is out of bounds
                insertExceptionThrow(next, sources.get(1), deletedInsns);
                deletedInsns.add(next.getBlock().getInsns().get(2));
            }
            deletedInsns.add(next);
            break;
        case RegOps.APUT:
            // Replace array puts with moves
            sources = use.getSources();
            indexReg = ((CstLiteralBits) sources.get(2).getTypeBearer());
            index = indexReg.getIntBits();
            if (index < length) {
                source = sources.get(0);
                result = source.withReg(newRegs.get(index).getReg());
                insertPlainInsnBefore(use, RegisterSpecList.make(source),
                                          result, RegOps.MOVE, null);
                // Update the newReg entry to mark value as unknown now
                newRegs.set(index, result.withSimpleType());
            } else {
                // Throw an exception if the index is out of bounds
                insertExceptionThrow(use, sources.get(2), deletedInsns);
            }
            break;
        case RegOps.ARRAY_LENGTH:
            // Replace array lengths with const instructions
            TypeBearer lengthReg = prev.getSources().get(0).getTypeBearer();
            //CstInteger lengthReg = CstInteger.make(length);
            next = getMoveForInsn(use);
            insertPlainInsnBefore(next, RegisterSpecList.EMPTY,
                                      next.getResult(), RegOps.CONST,
                                      (Constant) lengthReg);
            deletedInsns.add(next);
            break;
        case RegOps.MARK_LOCAL:
            // Remove mark local instructions
            break;
        case RegOps.FILL_ARRAY_DATA:
            // Create const instructions for each fill value
            Insn ropUse = use.getOriginalRopInsn();
            FillArrayDataInsn fill = (FillArrayDataInsn) ropUse;
            ArrayList<Constant> constList = fill.getInitValues();
            for (int i = 0; i < length; i++) {
                RegisterSpec newFill =
                    RegisterSpec.make(newRegs.get(i).getReg(),
                                          (TypeBearer) constList.get(i));
                insertPlainInsnBefore(use, RegisterSpecList.EMPTY, newFill,
                                          RegOps.CONST, constList.get(i));
                // Update the newRegs to hold the new const value
                newRegs.set(i, newFill);
            }
            break;
        default:
    }
}
 
Example 18
/**
 * Ensure that the RegionFactory set methods mirrors those found in RegionAttributes
 * 
 * @throws Exception
 */
public void testAttributesFactoryConformance() throws Exception {
  Method[] af = AttributesFactory.class.getDeclaredMethods();
  Method[] rf = RegionFactory.class.getDeclaredMethods();
  Method am, rm;
  
  ArrayList afDeprected = new ArrayList(); // hack to ignore deprecated methods
  afDeprected.add("setCacheListener");
  afDeprected.add("setMirrorType");
  afDeprected.add("setPersistBackup");
  afDeprected.add("setBucketRegion");    
  afDeprected.add("setEnableWAN");    
  afDeprected.add("setEnableBridgeConflation");    
  afDeprected.add("setEnableConflation");    
  ArrayList methodsToImplement = new ArrayList();

  // Since the RegionFactory has an AttributesFactory member,
  // we only need to make sure the RegionFactory class adds proxies for the
  // 'set' and 'add' methods added to the AttributesFactory. The java complier
  // will notify the
  // developer if a method is removed from AttributesFactory.
  String amName;
  boolean hasMethod = false;
  assertTrue(af.length != 0);
  for (int i=0; i<af.length; i++) {
    am = af[i];
    amName = am.getName();
    if (!afDeprected.contains(amName) && 
        (amName.startsWith("set") || amName.startsWith("add"))) {
      for (int j=0; j<rf.length; j++) {
        rm = rf[j];
        if (rm.getName().equals(am.getName())) {
          Class[] rparams = rm.getParameterTypes();
          Class[] aparams = am.getParameterTypes();
          if (rparams.length == aparams.length) {
            boolean hasAllParams = true;
            for (int k = 0; k < rparams.length; k++) {
              if (aparams[k] != rparams[k]) {
                hasAllParams = false;
                break;
              }
            } // parameter check
            if (hasAllParams) {
              hasMethod = true;
            }
          } 
        } 
      } // region factory methods
      if (!hasMethod) {
        methodsToImplement.add(am);
      } else {
        hasMethod = false;
      }
    }
  } // attributes methods
  
  if (methodsToImplement.size() > 0) {
    fail("RegionFactory does not conform to AttributesFactory, its should proxy these methods " + methodsToImplement);                
  }
}
 
Example 19
Source Project: gemfirexd-oss   File: PartitionClause.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected static void writePortfolioPartitionToBB(int whichClause) {
  ArrayList<String>  partitionKey = new ArrayList<String> ();
  int portfolioPRs = 2;
  switch (whichClause) {
  case 0:
    ArrayList<String>  custPartition = (ArrayList<String>) partitionMap.get("customersPartition");
    ArrayList<String>  secPartition = (ArrayList<String> ) partitionMap.get("securitiesPartition");
    if (custPartition.contains("cid")&& custPartition.size()==1) partitionKey.add("cid"); //cid is the first foreign key
    else if (secPartition.contains("sec_id") && secPartition.size()==1) partitionKey.add("sid");
    else {
      partitionKey.add("cid");
      partitionKey.add("sid");
    }
    counters.decrement(SQLBB.numOfPRs); //no gloabl hash index
    --portfolioPRs;
    if (SQLTest.hasHdfs == true && hdfsExtnParams.get("TRADE.PORTFOLIO" + HDFSSqlTest.STORENAME) != null){      
      counters.decrement(SQLBB.numOfPRs);
    }
    break;
  case 1:
    partitionKey.add("cid");
    partitionMap.put("portfPartitionOn", "range");
    counters.decrement(SQLBB.numOfPRs); //no gloabl hash index
    --portfolioPRs;
    if (SQLTest.hasHdfs == true && hdfsExtnParams.get("TRADE.PORTFOLIO" + HDFSSqlTest.STORENAME) != null){      
      counters.decrement(SQLBB.numOfPRs);
    }
    break;
  case 2:
    partitionKey.add("tid");
    break;
  case 3:
    partitionKey.add("qty");
    break;
  case 4:
    partitionKey.add("qty");
    partitionKey.add("availQty");
    break;
  case 5:
    partitionKey.add("subTotal");
    break;
  case 6:
    partitionKey.add("sid");
    partitionMap.put("portfPartitionOn", "wrongRange"); //not colocated as the range are incompatiable
    counters.decrement(SQLBB.numOfPRs); //no gloabl hash index
    --portfolioPRs;
    if (SQLTest.hasHdfs == true && hdfsExtnParams.get("TRADE.PORTFOLIO" + HDFSSqlTest.STORENAME) != null){      
      counters.decrement(SQLBB.numOfPRs);
    }
    break;
  case 7:
    //replicated table
    counters.subtract(SQLBB.numOfPRs, 2); //no gloabl hash index & PR
    portfolioPRs = 0;
    break;
  default:
    throw new TestException("Unknown partitionKey " + whichClause)
    ;
  }

  counters.add(SQLBB.numOfPRs, 2); //PR and global hash index
  partitionMap.put("portfolioPartition", partitionKey); //put into BB 
          
  if (SQLTest.hasHdfs == true && hdfsExtnParams.get("TRADE.PORTFOLIO" + HDFSSqlTest.STORENAME) != null){      
    counters.add(SQLBB.numOfPRs, 2); //PR and global hash index
    
    if (hdfsExtnParams.get("TRADE.PORTFOLIO" + HDFSSqlTest.EVICTION_CRITERIA) == null){
      if (whichClause != 0 && whichClause != 1 && whichClause != 6 && whichClause != 7){
        counters.subtract(SQLBB.numOfPRs, 1); //no hdfs PR for global hash index if no eviction criteria
      }
    }
  }
  
  Log.getLogWriter().info("numOfPRs now is " + counters.read(SQLBB.numOfPRs) + (SQLTest.hasHdfs ? " after calculating PR for HDFS ignoring colocation" : " "));
  boolean reproduce50116 = TestConfig.tab().booleanAt(SQLPrms.toReproduce50116, true);
  if (SQLTest.hasPortfolioV1 && !reproduce50116) {
    counters.add(SQLBB.numOfPRs, portfolioPRs);
    Log.getLogWriter().info("add num of PR for portfoliov1 table: " + portfolioPRs
         + " as original portfoilio is not dropped to work around #50116");
  }

}
 
Example 20
private MatrixBlock computeLIBSVMSizeAndCreateOutputMatrixBlock(InputSplit[] splits, Path path,
		JobConf job, long rlen, long clen, long estnnz)
	throws IOException, DMLRuntimeException 
{
	int nrow = 0;
	int ncol = (int) clen;
	
	FileInputFormat.addInputPath(job, path);
	TextInputFormat informat = new TextInputFormat();
	informat.configure(job);

	// count rows in parallel per split
	try 
	{
		ExecutorService pool = CommonThreadPool.get(_numThreads);
		ArrayList<CountRowsTask> tasks = new ArrayList<>();
		for (InputSplit split : splits) {
			tasks.add(new CountRowsTask(split, informat, job));
		}
		pool.invokeAll(tasks);
		pool.shutdown();

		// collect row counts for offset computation
		// early error notify in case not all tasks successful
		_offsets = new SplitOffsetInfos(tasks.size());
		for (CountRowsTask rt : tasks) {
			if (!rt.getReturnCode())
				throw new IOException("Count task for libsvm input failed: "+ rt.getErrMsg());
			_offsets.setOffsetPerSplit(tasks.indexOf(rt), nrow);
			_offsets.setLenghtPerSplit(tasks.indexOf(rt), rt.getRowCount());
			nrow = nrow + rt.getRowCount();
		}
	} 
	catch (Exception e) {
		throw new IOException("Threadpool Error " + e.getMessage(), e);
	}
	
	//robustness for wrong dimensions which are already compiled into the plan
	if( (rlen != -1 && nrow != rlen) || (clen != -1 && ncol != clen) ) {
		String msg = "Read matrix dimensions differ from meta data: ["+nrow+"x"+ncol+"] vs. ["+rlen+"x"+clen+"].";
		if( rlen < nrow || clen < ncol ) {
			//a) specified matrix dimensions too small
			throw new DMLRuntimeException(msg);
		}
		else {
			//b) specified matrix dimensions too large -> padding and warning
			LOG.warn(msg);
			nrow = (int) rlen;
			ncol = (int) clen;
		}
	}
	
	// allocate target matrix block based on given size; 
	// need to allocate sparse as well since lock-free insert into target
	long estnnz2 = (estnnz < 0) ? (long)nrow * ncol : estnnz;
	return createOutputMatrixBlock(nrow, ncol, nrow, estnnz2, true, true);
}