Java Code Examples for org.apache.commons.lang3.ArrayUtils#indexOf()

The following examples show how to use org.apache.commons.lang3.ArrayUtils#indexOf() . 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: FeedUtils.java    From commafeed with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the declared encoding from the xml
 */
public static String extractDeclaredEncoding(byte[] bytes) {
	int index = ArrayUtils.indexOf(bytes, (byte) '>');
	if (index == -1) {
		return null;
	}

	String pi = new String(ArrayUtils.subarray(bytes, 0, index + 1)).replace('\'', '"');
	index = StringUtils.indexOf(pi, "encoding=\"");
	if (index == -1) {
		return null;
	}
	String encoding = pi.substring(index + 10, pi.length());
	encoding = encoding.substring(0, encoding.indexOf('"'));
	return encoding;
}
 
Example 2
Source File: CellSpaceBodyList.java    From notreal2d with MIT License 6 votes vote down vote up
@Nonnull
private static Body[] addBodyToCell(@Nullable Body[] cellBodies, @Nonnull Body body) {
    if (cellBodies == null) {
        return new Body[] {body};
    }

    int bodyIndex = ArrayUtils.indexOf(cellBodies, body);
    if (bodyIndex != ArrayUtils.INDEX_NOT_FOUND) {
        throw new IllegalStateException("Can't add Body {id=" + body.getId() + "} to index.");
    }

    int bodyCount = cellBodies.length;
    Body[] newCellBodies = new Body[bodyCount + 1];
    System.arraycopy(cellBodies, 0, newCellBodies, 0, bodyCount);
    newCellBodies[bodyCount] = body;
    return newCellBodies;
}
 
Example 3
Source File: SortedListFacade.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void elementRemoved(ListEvent<E> e)
{
	int index = ArrayUtils.indexOf(transform, e.getIndex());
	transform = ArrayUtils.removeElement(transform, transform.length - 1);
	sanityCheck();
	Arrays.sort(transform, indexComparator);
	fireElementRemoved(this, e.getElement(), index);
}
 
Example 4
Source File: BytesUtils.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public static String pretty(long duration, ByteUnit unit) {

        int index = ArrayUtils.indexOf(units, unit);
        StringBuilder stringBuilder = new StringBuilder();
        long carry = 0;
        long rest = 0;
        for (; index < units.length - 1; index++) {
            carry = duration / carries[index];
            rest = duration - (carry * carries[index]);
            if (rest > 0) {
                stringBuilder.insert(0, unitStrs[index])
                        .insert(0, rest);
            }
            if (carry == 0) {
                break;
            }
            duration = carry;
        }
        if (index == units.length - 1) {
            stringBuilder.insert(0, unitStrs[index])
                    .insert(0, duration);
        }
        if (stringBuilder.length() == 0) {
            return "0" + unitStrs[ArrayUtils.indexOf(units, unit)];
        }
        return stringBuilder.toString();

    }
 
Example 5
Source File: Permute.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public Permute(INDArray input, INDArray result, int... permuteDims){
    super(input, result);
    this.permuteDims = permuteDims;
    this.reverseDims = new int[permuteDims.length];
    for (int i = 0; i < reverseDims.length; i++) {
        reverseDims[i] = ArrayUtils.indexOf(permuteDims, i);
    }
    addIArgument(permuteDims);
}
 
Example 6
Source File: ContactActivity.java    From Contacts with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState)
{
	requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_contact);

	getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_background_transparent_gradient));
	getActionBar().setDisplayShowHomeEnabled(true);
	getActionBar().setDisplayHomeAsUpEnabled(true);

	String lookupKey = getIntent().getStringExtra("lookupKey");
	String[] lookupKeys = getIntent().getStringArrayExtra("lookupKeys");
	String name = getIntent().getStringExtra("name");

	setTitle(name);

	int index = ArrayUtils.indexOf(lookupKeys, lookupKey);

	// Create the adapter that will return a fragment for each of the three
	// primary sections of the app.
	mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), lookupKeys);

	// Set up the ViewPager with the sections adapter.
	mViewPager = (JazzyViewPager) findViewById(R.id.pager);
	mViewPager.setOnPageChangeListener(mSectionsPagerAdapter);
	mViewPager.setAdapter(mSectionsPagerAdapter);
	mViewPager.setCurrentItem(index);

	mViewPager.setTransitionEffect(TransitionEffect.FlipHorizontal);
}
 
Example 7
Source File: AwkCommand.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
public AwkCondition greaterThan(String property, Object value) {
    int index = ArrayUtils.indexOf(properties, property);
    if (index == -1) {
        throw new IllegalArgumentException();
    }
    SimpleCondition condition = new SimpleCondition(AwkOperator.GREATER_THAN, index + 1, property + conditions.size(), value);
    conditions.put(conditions.size(), condition);
    return condition;
}
 
Example 8
Source File: WeeklySchedule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Calendar nextTime(Calendar from) {
   Set<DayOfWeek> days = allScheduledDays();
   Calendar nextCal = (Calendar) from.clone();
   nextCal.setFirstDayOfWeek(Calendar.MONDAY);

   DayOfWeek d = DayOfWeek.from(nextCal);

   int startIndex = ArrayUtils.indexOf(DayOfWeek.values(), d);

   DayOfWeek[] allDays = DayOfWeek.values();
   DayOfWeek next = null;
   for(int i = 0; i < 7; i++) {
      int nextIndex = (startIndex + i) % allDays.length;
      if(days.contains(allDays[nextIndex])) {
         next = allDays[nextIndex];
         break;
      }
   }

   if(next == null) {
      throw new IllegalStateException("couldn't find day of week even after iterating for 7 days");
   }

   if(next != d) {
      nextCal = CalendarUtil.midnight(nextCal);
   }

   if(needToAddWeek(next, d)) {
      nextCal.add(Calendar.WEEK_OF_YEAR, 1);
   }

   nextCal.set(Calendar.DAY_OF_WEEK, DayOfWeek.toCalendar(next));
   return nextCal;
}
 
Example 9
Source File: Permute.java    From nd4j with Apache License 2.0 5 votes vote down vote up
public Permute(SameDiff sameDiff, SDVariable i_v, int[] permuteDims) {
    super(sameDiff, i_v);
    this.permuteDims = permuteDims;
    this.reverseDims = new int[permuteDims.length];
    for (int i = 0; i < reverseDims.length; i++) {
        reverseDims[i] = ArrayUtils.indexOf(permuteDims, i);
    }
}
 
Example 10
Source File: ModeSwitchBehavior.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
    ItemStack itemStack = player.getHeldItem(hand);
    if(player.isSneaking()) {
        T currentMode = getModeFromItemStack(itemStack);
        int currentModeIndex = ArrayUtils.indexOf(enumConstants, currentMode);
        T nextMode = enumConstants[(currentModeIndex + 1) % enumConstants.length];
        setModeForItemStack(itemStack, nextMode);
        ITextComponent newModeComponent = new TextComponentTranslation(nextMode.getUnlocalizedName());
        ITextComponent textComponent = new TextComponentTranslation("metaitem.behavior.mode_switch.mode_switched", newModeComponent);
        player.sendStatusMessage(textComponent, true);
        return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack);
    }
    return ActionResult.newResult(EnumActionResult.PASS, itemStack);
}
 
Example 11
Source File: HiscorePanel.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void resetEndpoints()
{
	// Select the correct tab based on the world type.
	HiscoreEndpoint endpoint = selectWorldEndpoint();
	int idx = ArrayUtils.indexOf(ENDPOINTS, endpoint);
	tabGroup.select(tabGroup.getTab(idx));
}
 
Example 12
Source File: Permute.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public Permute(SameDiff sameDiff, SDVariable i_v, int... permuteDims) {
    super(sameDiff, i_v);
    this.permuteDims = permuteDims;
    this.reverseDims = new int[permuteDims.length];
    for (int i = 0; i < reverseDims.length; i++) {
        reverseDims[i] = ArrayUtils.indexOf(permuteDims, i);
    }
    addIArgument(permuteDims);
}
 
Example 13
Source File: OutputColsHelper.java    From Alink with Apache License 2.0 4 votes vote down vote up
/**
 * The constructor.
 *
 * @param inputSchema      Schema of input data being predicted or transformed.
 * @param outputColNames   Output column names of the prediction/transformation operator.
 * @param outputColTypes   Output column types of the prediction/transformation operator.
 * @param reservedColNames Reserved column names, which is a subset of input data's column names that we want to preserve.
 */
public OutputColsHelper(TableSchema inputSchema, String[] outputColNames, TypeInformation[] outputColTypes,
                        String[] reservedColNames) {
    this.inputColNames = inputSchema.getFieldNames();
    this.inputColTypes = inputSchema.getFieldTypes();
    this.outputColNames = outputColNames;
    this.outputColTypes = outputColTypes;

    HashSet<String> toReservedCols = new HashSet<>(
        Arrays.asList(reservedColNames == null ? this.inputColNames : reservedColNames)
    );
    //the indices of the columns which need to be reserved.
    ArrayList<Integer> reservedColIndices = new ArrayList<>(toReservedCols.size());
    ArrayList<Integer> reservedColToResultIndex = new ArrayList<>(toReservedCols.size());
    outputColsPosInResult = new int[outputColNames.length];
    Arrays.fill(outputColsPosInResult, -1);
    int index = 0;
    for (int i = 0; i < inputColNames.length; i++) {
        int key = ArrayUtils.indexOf(outputColNames, inputColNames[i]);
        if (key >= 0) {
            outputColsPosInResult[key] = index++;
            continue;
        }
        //add these interested column.
        if (toReservedCols.contains(inputColNames[i])) {
            reservedColIndices.add(i);
            reservedColToResultIndex.add(index++);
        }
    }
    for (int i = 0; i < outputColsPosInResult.length; i++) {
        if (outputColsPosInResult[i] == -1) {
            outputColsPosInResult[i] = index++;
        }
    }
    //write reversed column information in array.
    this.reservedCols = new int[reservedColIndices.size()];
    this.reservedColsPosInResult = new int[reservedColIndices.size()];
    for (int i = 0; i < this.reservedCols.length; i++) {
        this.reservedCols[i] = reservedColIndices.get(i);
        this.reservedColsPosInResult[i] = reservedColToResultIndex.get(i);
    }
}
 
Example 14
Source File: TestBaseLoadBalancer.java    From hbase with Apache License 2.0 4 votes vote down vote up
@Test
public void testClusterRegionLocations() {
  // tests whether region locations are handled correctly in Cluster
  List<ServerName> servers = getListOfServerNames(randomServers(10, 10));
  List<RegionInfo> regions = randomRegions(101);
  Map<ServerName, List<RegionInfo>> clusterState = new HashMap<>();

  assignRegions(regions, servers, clusterState);

  // mock block locality for some regions
  RegionLocationFinder locationFinder = mock(RegionLocationFinder.class);
  // block locality: region:0   => {server:0}
  //                 region:1   => {server:0, server:1}
  //                 region:42 => {server:4, server:9, server:5}
  when(locationFinder.getTopBlockLocations(regions.get(0))).thenReturn(
      Lists.newArrayList(servers.get(0)));
  when(locationFinder.getTopBlockLocations(regions.get(1))).thenReturn(
      Lists.newArrayList(servers.get(0), servers.get(1)));
  when(locationFinder.getTopBlockLocations(regions.get(42))).thenReturn(
      Lists.newArrayList(servers.get(4), servers.get(9), servers.get(5)));
  when(locationFinder.getTopBlockLocations(regions.get(43))).thenReturn(
      Lists.newArrayList(ServerName.valueOf("foo", 0, 0))); // this server does not exists in clusterStatus

  BaseLoadBalancer.Cluster cluster = new Cluster(clusterState, null, locationFinder, null);

  int r0 = ArrayUtils.indexOf(cluster.regions, regions.get(0)); // this is ok, it is just a test
  int r1 = ArrayUtils.indexOf(cluster.regions, regions.get(1));
  int r10 = ArrayUtils.indexOf(cluster.regions, regions.get(10));
  int r42 = ArrayUtils.indexOf(cluster.regions, regions.get(42));
  int r43 = ArrayUtils.indexOf(cluster.regions, regions.get(43));

  int s0 = cluster.serversToIndex.get(servers.get(0).getAddress());
  int s1 = cluster.serversToIndex.get(servers.get(1).getAddress());
  int s4 = cluster.serversToIndex.get(servers.get(4).getAddress());
  int s5 = cluster.serversToIndex.get(servers.get(5).getAddress());
  int s9 = cluster.serversToIndex.get(servers.get(9).getAddress());

  // region 0 locations
  assertEquals(1, cluster.regionLocations[r0].length);
  assertEquals(s0, cluster.regionLocations[r0][0]);

  // region 1 locations
  assertEquals(2, cluster.regionLocations[r1].length);
  assertEquals(s0, cluster.regionLocations[r1][0]);
  assertEquals(s1, cluster.regionLocations[r1][1]);

  // region 10 locations
  assertEquals(0, cluster.regionLocations[r10].length);

  // region 42 locations
  assertEquals(3, cluster.regionLocations[r42].length);
  assertEquals(s4, cluster.regionLocations[r42][0]);
  assertEquals(s9, cluster.regionLocations[r42][1]);
  assertEquals(s5, cluster.regionLocations[r42][2]);

  // region 43 locations
  assertEquals(1, cluster.regionLocations[r43].length);
  assertEquals(-1, cluster.regionLocations[r43][0]);
}
 
Example 15
Source File: OutputColsHelper.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * The constructor.
 *
 * @param inputSchema      Schema of input data being predicted or transformed.
 * @param outputColNames   Output column names of the prediction/transformation operator.
 * @param outputColTypes   Output column types of the prediction/transformation operator.
 * @param reservedColNames Reserved column names, which is a subset of input data's column names that we want to preserve.
 */
public OutputColsHelper(TableSchema inputSchema, String[] outputColNames, TypeInformation<?>[] outputColTypes,
						String[] reservedColNames) {
	this.inputColNames = inputSchema.getFieldNames();
	this.inputColTypes = inputSchema.getFieldTypes();
	this.outputColNames = outputColNames;
	this.outputColTypes = outputColTypes;

	HashSet<String> toReservedCols = new HashSet<>(
		Arrays.asList(reservedColNames == null ? this.inputColNames : reservedColNames)
	);
	//the indices of the columns which need to be reserved.
	ArrayList<Integer> reservedColIndices = new ArrayList<>(toReservedCols.size());
	ArrayList<Integer> reservedColToResultIndex = new ArrayList<>(toReservedCols.size());
	outputColsPosInResult = new int[outputColNames.length];
	Arrays.fill(outputColsPosInResult, -1);
	int index = 0;
	for (int i = 0; i < inputColNames.length; i++) {
		int key = ArrayUtils.indexOf(outputColNames, inputColNames[i]);
		if (key >= 0) {
			outputColsPosInResult[key] = index++;
			continue;
		}
		//add these interested column.
		if (toReservedCols.contains(inputColNames[i])) {
			reservedColIndices.add(i);
			reservedColToResultIndex.add(index++);
		}
	}
	for (int i = 0; i < outputColsPosInResult.length; i++) {
		if (outputColsPosInResult[i] == -1) {
			outputColsPosInResult[i] = index++;
		}
	}
	//write reversed column information in array.
	this.reservedCols = new int[reservedColIndices.size()];
	this.reservedColsPosInResult = new int[reservedColIndices.size()];
	for (int i = 0; i < this.reservedCols.length; i++) {
		this.reservedCols[i] = reservedColIndices.get(i);
		this.reservedColsPosInResult[i] = reservedColToResultIndex.get(i);
	}
}
 
Example 16
Source File: MultiSelectDragListPreference.javaMultiSelectDragListPreference.java    From Klyph with MIT License 4 votes vote down vote up
@Override
protected void onPrepareDialogBuilder(Builder builder)
{
	super.onPrepareDialogBuilder(builder);

	if (mEntries == null || mEntryValues == null)
	{
		throw new IllegalStateException("MultiSelectListPreference requires an entries array and "
										+ "an entryValues array.");
	}

	String[] entries = new String[mEntries.length];
	for (int i = 0; i < mEntries.length; i++)
	{
		entries[i] = mEntries[i].toString();
	}

	boolean [] selectedItems = getSelectedItems();

	ArrayList<String> orderedList = new ArrayList<String>();
	int n = selectedItems.length;
	
	for (String value : mValues)
	{
		int index = ArrayUtils.indexOf(mEntryValues, value);
		orderedList.add(mEntries[index].toString());
	}

	for (int i = 0; i < mEntries.length; i++)
	{
		if (!mValues.contains(mEntryValues[i]))
			orderedList.add(mEntries[i].toString());
	}

	adapter = new ArrayAdapter<String>(getContext(), R.layout.item_list_preference_multi_drag, R.id.text,
			orderedList);
	listView = new DragSortListView(getContext(), null);
	listView.setAdapter(adapter);

	listView.setDropListener(onDrop);
	listView.setDragEnabled(true);
	listView.setFloatAlpha(0.8f);

	DragSortController controller = new DragSortController(listView);
	controller.setDragHandleId(R.id.drag_handle);
	controller.setRemoveEnabled(false);
	controller.setSortEnabled(true);
	controller.setBackgroundColor(0xFFFFFF);
	controller.setDragInitMode(DragSortController.ON_DOWN);

	listView.setFloatViewManager(controller);
	listView.setOnTouchListener(controller);

	
	builder.setView(listView);
	listView.setOnItemClickListener(new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			mPreferenceChanged = true;
			refreshNewValues();
		}});
	
	listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	for (int i = 0; i < n; i++)
	{
		listView.setItemChecked(i, i < mValues.size());
	}

	/*
	 * boolean [] checkedItems = getSelectedItems();
	 * builder.setMultiChoiceItems(mEntries, checkedItems,
	 * new DialogInterface.OnMultiChoiceClickListener() {
	 * public void onClick(DialogInterface dialog, int which, boolean 
	 * isChecked) {
	 * if (isChecked) {
	 * mPreferenceChanged |= mNewValues.add(mEntryValues[which].toString());
	 * } else {
	 * mPreferenceChanged |=
	 * mNewValues.remove(mEntryValues[which].toString());
	 * }
	 * }
	 * });
	 */
	mNewValues.clear();
	mNewValues.addAll(mValues);
}
 
Example 17
Source File: MetaBlocks.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static <T> T[] copyNotNull(T[] src) {
    int nullIndex = ArrayUtils.indexOf(src, null);
    return Arrays.copyOfRange(src, 0, nullIndex == -1 ? src.length : nullIndex);
}
 
Example 18
Source File: Direction.java    From riiablo with Apache License 2.0 4 votes vote down vote up
public static float direction8ToRadians(int direction) {
  int i = ArrayUtils.indexOf(DIRS_8M, direction);
  if (i == ArrayUtils.INDEX_NOT_FOUND) return 0;
  return RADIANS_8[i];
}
 
Example 19
Source File: SyncedField.java    From PneumaticCraft with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Byte retrieveValue(Field field, Object te) throws Exception{
    Object[] enumTypes = field.getType().getEnumConstants();
    return (byte)ArrayUtils.indexOf(enumTypes, field.get(te));
}
 
Example 20
Source File: GoConfigRevision.java    From gocd with Apache License 2.0 4 votes vote down vote up
private int offset() {
    return ArrayUtils.indexOf(values(), this);
}