Java Code Examples for com.google.common.primitives.Ints#max()

The following examples show how to use com.google.common.primitives.Ints#max() . 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
Source File: ClusterAgentAutoScaler.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private int calculateAgentScaleUpCountByDominantResource(Set<String> taskIds,
                                                         Map<String, Job> allJobs,
                                                         Map<String, Task> allTasks,
                                                         ResourceDimension resourceDimension) {
    double totalCpus = 0;
    double totalMemoryMB = 0;
    double totalDiskMB = 0;
    double totalNetworkMbps = 0;
    for (String taskId : taskIds) {
        Pair<Job, Task> jobTaskPair = getJobTaskPair(taskId, allJobs, allTasks);
        if (jobTaskPair != null) {
            ContainerResources containerResources = jobTaskPair.getLeft().getJobDescriptor().getContainer().getContainerResources();
            if (containerResources != null) {
                totalCpus += containerResources.getCpu();
                totalMemoryMB += containerResources.getMemoryMB();
                totalDiskMB += containerResources.getDiskMB();
                totalNetworkMbps += containerResources.getNetworkMbps();
            }
        }
    }

    int instancesByCpu = (int) Math.ceil(totalCpus / resourceDimension.getCpu());
    int instancesByMemory = (int) Math.ceil(totalMemoryMB / (double) resourceDimension.getMemoryMB());
    int instancesByDisk = (int) Math.ceil(totalDiskMB / (double) resourceDimension.getDiskMB());
    int instancesByNetwork = (int) Math.ceil(totalNetworkMbps / (double) resourceDimension.getNetworkMbs());

    return Ints.max(instancesByCpu, instancesByMemory, instancesByDisk, instancesByNetwork);
}
 
Example 2
Source File: CppLinkActionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testLinkoptsComeAfterLinkerInputs() throws Exception {
  RuleContext ruleContext = createDummyRuleContext();

  String solibPrefix = "_solib_k8";
  Iterable<LibraryToLink> linkerInputs =
      LinkerInputs.opaqueLibrariesToLink(
          ArtifactCategory.DYNAMIC_LIBRARY,
          ImmutableList.of(
              getOutputArtifact(solibPrefix + "/FakeLinkerInput1.so"),
              getOutputArtifact(solibPrefix + "/FakeLinkerInput2.so"),
              getOutputArtifact(solibPrefix + "/FakeLinkerInput3.so"),
              getOutputArtifact(solibPrefix + "/FakeLinkerInput4.so")));

  CppLinkAction linkAction =
      createLinkBuilder(
              ruleContext,
              LinkTargetType.EXECUTABLE,
              "dummyRuleContext/out",
              ImmutableList.of(),
              ImmutableList.copyOf(linkerInputs),
              getMockFeatureConfiguration(/* envVars= */ ImmutableMap.of()))
          .addLinkopts(ImmutableList.of("FakeLinkopt1", "FakeLinkopt2"))
          .build();

  List<String> argv = linkAction.getLinkCommandLine().getRawLinkArgv();
  int lastLinkerInputIndex =
      Ints.max(
          argv.indexOf("FakeLinkerInput1"), argv.indexOf("FakeLinkerInput2"),
          argv.indexOf("FakeLinkerInput3"), argv.indexOf("FakeLinkerInput4"));
  int firstLinkoptIndex = Math.min(argv.indexOf("FakeLinkopt1"), argv.indexOf("FakeLinkopt2"));
  assertThat(lastLinkerInputIndex).isLessThan(firstLinkoptIndex);
}
 
Example 3
Source File: GenericCsvInputFormat.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
protected void setFieldsGeneric(int[] sourceFieldIndices, Class<?>[] fieldTypes) {
	Preconditions.checkNotNull(sourceFieldIndices);
	Preconditions.checkNotNull(fieldTypes);
	Preconditions.checkArgument(sourceFieldIndices.length == fieldTypes.length,
		"Number of field indices and field types must match.");

	for (int i : sourceFieldIndices) {
		if (i < 0) {
			throw new IllegalArgumentException("Field indices must not be smaller than zero.");
		}
	}

	int largestFieldIndex = Ints.max(sourceFieldIndices);
	this.fieldIncluded = new boolean[largestFieldIndex + 1];
	ArrayList<Class<?>> types = new ArrayList<Class<?>>();

	// check if we support parsers for these types
	for (int i = 0; i < fieldTypes.length; i++) {
		Class<?> type = fieldTypes[i];

		if (type != null) {
			if (FieldParser.getParserForType(type) == null) {
				throw new IllegalArgumentException("The type '" + type.getName()
					+ "' is not supported for the CSV input format.");
			}
			types.add(type);
			fieldIncluded[sourceFieldIndices[i]] = true;
		}
	}

	Class<?>[] denseTypeArray = (Class<?>[]) types.toArray(new Class[types.size()]);
	this.fieldTypes = denseTypeArray;
}
 
Example 4
Source File: AccessTokenUtil.java    From wechat-mp-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public String load(License license) throws Exception {
    URI uri = new URIBuilder(WechatRequest.GET_ACCESS_TOKEN.getUrl())
            .setParameter("grant_type", GrantType.CLIENT_CREDENTIAL.getValue())
            .setParameter("appid", license.getAppId())
            .setParameter("secret", license.getAppSecret())
            .build();
    log.info("get access token for {}, url = {}", license, uri);

    String json = Request.Get(uri)
            .connectTimeout(HttpUtil.CONNECT_TIMEOUT)
            .socketTimeout(HttpUtil.SOCKET_TIMEOUT)
            .execute().returnContent().asString();
    log.info("get access token for {}, rtn = {}", license, json);

    AccessTokenJsonRtn rtn = JsonRtnUtil.parseJsonRtn(json, AccessTokenJsonRtn.class);
    if (rtn == null) {
        log.info("parse return json msg failed when get access token for {}, rtn = {}", license, json);
        return null;
    }

    if (!JsonRtnUtil.isSuccess(rtn)) {
        log.info("unsuccessfully get access token for {}, rtn = {}", license, rtn);
        return null;
    }

    // for safe, expiresSeconds - 60s
    int expiresSeconds = Ints.max(rtn.getExpiresIn() - 60, 0);
    queue.put(new DelayItem<License>(license, TimeUnit.NANOSECONDS.convert(expiresSeconds, TimeUnit.SECONDS)));

    String accessToken = rtn.getAccessToken();
    log.info("successfully get access token for {}, rtn = {}", license, rtn);
    return accessToken;
}
 
Example 5
Source File: BlazeCoverageRunner.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static int maxLineNumber(FileData fileData) {
  return Ints.max(fileData.lineHits.keys());
}
 
Example 6
Source File: DynamicMetric.java    From imhotep with Apache License 2.0 4 votes vote down vote up
@Override
public long getMax() {
    return Ints.max(values);
}
 
Example 7
Source File: MaxValueInArray.java    From levelup-java-examples with Apache License 2.0 4 votes vote down vote up
@Test
public void find_max_value_in_numeric_array_with_guava () {
	int highest = Ints.max(numbers);
	assertEquals(91, highest);
}
 
Example 8
Source File: UpdateMeta.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Override
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
  this.databases = databases;
  try {
    databaseMeta = rep.loadDatabaseMetaFromStepAttribute( id_step, "id_connection", databases );
    skipLookup = rep.getStepAttributeBoolean( id_step, "skip_lookup" );
    commitSize = rep.getStepAttributeString( id_step, "commit" );
    if ( commitSize == null ) {
      long comSz = -1;
      try {
        comSz = rep.getStepAttributeInteger( id_step, "commit" );
      } catch ( Exception ex ) {
        commitSize = "100";
      }
      if ( comSz >= 0 ) {
        commitSize = Long.toString( comSz );
      }
    }
    useBatchUpdate = rep.getStepAttributeBoolean( id_step, "use_batch" );
    schemaName = rep.getStepAttributeString( id_step, "schema" );
    tableName = rep.getStepAttributeString( id_step, "table" );

    errorIgnored = rep.getStepAttributeBoolean( id_step, "error_ignored" );
    ignoreFlagField = rep.getStepAttributeString( id_step, "ignore_flag_field" );

    int nrKeyName = rep.countNrStepAttributes( id_step, "key_name" );
    int nrKeyField = rep.countNrStepAttributes( id_step, "key_field" );
    int nrKeyCondition = rep.countNrStepAttributes( id_step, "key_condition" );
    int nrKeyName2 = rep.countNrStepAttributes( id_step, "key_name2" );

    int nrkeys = Ints.max( nrKeyName, nrKeyCondition, nrKeyField, nrKeyName2 );

    int nrValueName = rep.countNrStepAttributes( id_step, "value_name" );
    int nrValueRename = rep.countNrStepAttributes( id_step, "value_rename" );

    int nrvalues = Ints.max( nrValueName, nrValueRename );

    allocate( nrkeys, nrvalues );

    for ( int i = 0; i < nrkeys; i++ ) {
      keyStream[i] = rep.getStepAttributeString( id_step, i, "key_name" );
      keyLookup[i] = rep.getStepAttributeString( id_step, i, "key_field" );
      keyCondition[i] = rep.getStepAttributeString( id_step, i, "key_condition" );
      keyStream2[i] = rep.getStepAttributeString( id_step, i, "key_name2" );
    }

    for ( int i = 0; i < nrvalues; i++ ) {
      updateLookup[i] = rep.getStepAttributeString( id_step, i, "value_name" );
      updateStream[i] = rep.getStepAttributeString( id_step, i, "value_rename" );
    }
  } catch ( Exception e ) {
    throw new KettleException( BaseMessages.getString(
      PKG, "UpdateMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository" ), e );
  }
}
 
Example 9
Source File: GuavaTutorial.java    From maven-framework-project with MIT License 3 votes vote down vote up
@Test
public void example20(){
	
	int[] array1 = { 1, 2, 3, 4, 5 };
	int a = 4;
	
	boolean contains = Ints.contains(array1, a);//判断数组中是否存在a元素
	
	System.out.println(contains);
	
	int indexOf = Ints.indexOf(array1, a); //获取该元素在数组中的下标
	
	System.out.println(indexOf);
	
	int max = Ints.max(array1);//求数组中的最大值
	
	System.out.println(max);
	
	int min = Ints.min(array1);//求数组中的最小值
	
	System.out.println(min);
	
	int[] array2 = {6, 7, 8, 9, 10};
	
	int[] concat = Ints.concat(array1, array2 );//合并数组
	
	System.out.println(Arrays.toString(concat));
	
}