下面列出了java.util.ArrayList#clear ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testTwoIterDiffKey() throws Exception {
HdfsSortedOplogOrganizer organizer = new HdfsSortedOplogOrganizer(regionManager, 0);
ArrayList<TestEvent> items = new ArrayList<TestEvent>();
items.add(new TestEvent(("0"), ("V1")));
organizer.flush(items.iterator(), items.size());
items.clear();
items.add(new TestEvent(("1"), ("V1")));
organizer.flush(items.iterator(), items.size());
List<TrackedReference<Hoplog>> oplogs = organizer.getSortedOplogs();
HoplogSetIterator iter = new HoplogSetIterator(oplogs);
assertTrue(iter.hasNext());
int count = 0;
for (ByteBuffer keyBB = null; iter.hasNext();) {
keyBB = iter.next();
byte[] key = HFileSortedOplog.byteBufferToArray(keyBB);
byte[] value = HFileSortedOplog.byteBufferToArray(iter.getValue());
assertEquals(String.valueOf(count), BlobHelper.deserializeBlob(key));
assertEquals("V1", ((PersistedEventImpl) SortedHoplogPersistedEvent.fromBytes(value)).getValue());
count++;
}
assertEquals(2, count);
organizer.close();
}
@Override
boolean apply(IXulDataSelectContext dataCtx, ArrayList<XulDataNode> ctx) {
ctx.clear();
XulBinding binding = dataCtx.getBindingById(_dataSource);
if (binding == null) {
return true;
}
if (!binding.isDataReady() && !binding.isUpdated()) {
return false;
}
XulDataNode dataNode = binding.getData();
if (dataNode != null) {
ctx.add(dataNode);
}
return true;
}
private synchronized List<String> getDistinctValsFromCVAndPlan( String planName, String planColName, String cropColName ) {
ArrayList<String> l = new ArrayList<String>();
Set set = new HashSet();
if ( planName != null )
l.addAll( HSQLQuerier.getDistinctValuesForColumn( p.getConnection(),
planName,
planColName ) );
l.addAll( HSQLQuerier.getDistinctValuesForColumn( p.getConnection(),
CROP_VAR_TABLE,
cropColName ) );
// list now contains all values, possibly some duplicates
// this ensures that the values are unique
set.addAll ( l );
l.clear();
l.addAll( set );
return l;
}
@Test
public void testGetNextTupleMultipleProjections() throws IOException, ExecException {
t = tRandom;
proj.attachInput(t);
proj.setOverloaded(true);
int j = 0;
ArrayList<Integer> cols = new ArrayList<Integer>();
while (true) {
cols.add(j);
cols.add(j + 1);
proj.setColumns(cols);
res = proj.getNextTuple();
if (res.returnStatus == POStatus.STATUS_EOP)
break;
TupleFactory tupleFactory = TupleFactory.getInstance();
ArrayList<Object> objList = new ArrayList<Object>();
objList.add(t.get(j));
objList.add(t.get(j + 1));
Tuple expectedResult = tupleFactory.newTuple(objList);
assertEquals(POStatus.STATUS_OK, res.returnStatus);
assertEquals(expectedResult, res.result);
++j;
cols.clear();
}
proj.attachInput(t);
proj.setColumn(8);
proj.setOverloaded(false);
res = proj.getNextTuple();
assertEquals(POStatus.STATUS_OK, res.returnStatus);
assertEquals(t.get(8), res.result);
}
private void evalInputs(final ArrayList<AbraBaseSite> inputs)
{
final ArrayList<AbraBaseSite> outputs = new ArrayList<>();
for (final AbraBaseSite input : inputs)
{
if (!(input instanceof AbraSiteKnot))
{
outputs.add(input);
continue;
}
final AbraSiteKnot knot = (AbraSiteKnot) input;
if (knot.block.index != AbraBlockSpecial.TYPE_CONCAT)
{
outputs.add(input);
continue;
}
knot.references--;
for (final AbraBaseSite knotInput : knot.inputs)
{
outputs.add(knotInput);
knotInput.references++;
}
}
inputs.clear();
inputs.addAll(outputs);
}
public void unstashAll(int index) {
if (stashed == null) {
return;
}
ArrayList<StashedMessage> stashedMessages = stashed.get(index);
if (stashedMessages == null || stashedMessages.size() == 0) {
return;
}
StashedMessage stashedMessage;
for (int i = stashedMessages.size() - 1; i >= 0; i--) {
stashedMessage = stashedMessages.get(i);
self().sendFirst(stashedMessage.getMessage(), stashedMessage.getSender());
}
stashedMessages.clear();
}
@SuppressWarnings("unchecked")
public <E> ArrayList<E> arrayList(int minCapacity) {
ArrayList<E> list = (ArrayList<E>) arrayList;
if (list == null) {
arrayList = new ArrayList<Object>(minCapacity);
return (ArrayList<E>) arrayList;
}
list.clear();
list.ensureCapacity(minCapacity);
return list;
}
@Test
public void testSerializerLazyInitializeInParallel() throws Exception {
final String name = "testSerializerLazyInitializeInParallel";
// use PojoTypeInfo which will create a new serializer when createSerializer is invoked.
final TestStateDescriptor<String> desc =
new TestStateDescriptor<>(name, new PojoTypeInfo<>(String.class, new ArrayList<>()));
final int threadNumber = 20;
final ArrayList<CheckedThread> threads = new ArrayList<>(threadNumber);
final ExecutionConfig executionConfig = new ExecutionConfig();
final ConcurrentHashMap<Integer, TypeSerializer<String>> serializers = new ConcurrentHashMap<>();
for (int i = 0; i < threadNumber; i++) {
threads.add(new CheckedThread() {
@Override
public void go() {
desc.initializeSerializerUnlessSet(executionConfig);
TypeSerializer<String> serializer = desc.getOriginalSerializer();
serializers.put(System.identityHashCode(serializer), serializer);
}
});
}
threads.forEach(Thread::start);
for (CheckedThread t : threads) {
t.sync();
}
assertEquals("Should use only one serializer but actually: " + serializers, 1, serializers.size());
threads.clear();
}
public static ArrayList<String> listFiles(String path, Context c) {
ArrayList<String> mDirContent = new ArrayList<>();
boolean showhidden = Settings.showHiddenFiles();
if (!mDirContent.isEmpty())
mDirContent.clear();
final File file = new File(path);
if (file.exists() && file.canRead()) {
String[] list = file.list();
// add files/folder to ArrayList depending on hidden status
for (String aList : list) {
if (!showhidden) {
if (aList.charAt(0) != '.')
mDirContent.add(path + "/" + aList);
} else {
mDirContent.add(path + "/" + aList);
}
}
} else if (Settings.rootAccess()) {
mDirContent = RootCommands.listFiles(file.getAbsolutePath(), showhidden);
} else {
Toast.makeText(c, c.getString(R.string.cantreadfolder), Toast.LENGTH_SHORT).show();
}
return mDirContent;
}
private static ArrayList<Integer> palette(Palette p, int defaultColor) {
ArrayList<Integer> extractedPalette = new ArrayList<>();
//get all palettes
Integer lightVibrant, vibrant, darkVibrant, lightMuted, muted, darkMuted;
lightVibrant = p.getVibrantColor(defaultColor);
vibrant = p.getVibrantColor(defaultColor);
darkVibrant = p.getDarkVibrantColor(defaultColor);
lightMuted = p.getLightMutedColor(defaultColor);
muted = p.getMutedColor(defaultColor);
darkMuted = p.getDarkMutedColor(defaultColor);
extractedPalette.add(lightVibrant);
extractedPalette.add(vibrant);
extractedPalette.add(darkVibrant);
extractedPalette.add(lightMuted);
extractedPalette.add(muted);
extractedPalette.add(darkMuted);
//add also default color, because if the next method fails we have a color anyway
extractedPalette.add(defaultColor);
//pass these palettes to a hashset to avoid duplicates
HashSet<Integer> hashSet = new HashSet<>();
hashSet.addAll(extractedPalette);
//add back these values to the palettes array list
extractedPalette.clear();
extractedPalette.addAll(hashSet);
return extractedPalette;
}
public Collisions project(Item item, float x, float y, float w, float h, float goalX, float goalY, CollisionFilter filter, Collisions collisions) {
collisions.clear();
ArrayList<Item> visited = project_visited;
visited.clear();
if (item != null) {
visited.add(item);
}
float tl = min(goalX, x);
float tt = min(goalY, y);
float tr = max(goalX + w, x + w);
float tb = max(goalY + h, y + h);
float tw = tr - tl;
float th = tb - tt;
grid.grid_toCellRect(cellSize, tl, tt, tw, th, project_c);
float cl = project_c.x, ct = project_c.y, cw = project_c.w, ch = project_c.h;
HashMap<Item, Boolean> dictItemsInCellRect = getDictItemsInCellRect(cl, ct, cw, ch, project_dictItemsInCellRect);
for (Item other : dictItemsInCellRect.keySet()) {
if (!visited.contains(other)) {
visited.add(other);
Response response = filter.filter(item, other);
if (response != null) {
Rect o = getRect(other);
float ox = o.x, oy = o.y, ow = o.w, oh = o.h;
Collision col = rectHelper.rect_detectCollision(x, y, w, h, ox, oy, ow, oh, goalX, goalY);
if (col != null) {
collisions.add(col.overlaps, col.ti, col.move.x, col.move.y, col.normal.x, col.normal.y, col.touch.x, col.touch.y, col.itemRect.x, col.itemRect.y, col.itemRect.w, col.itemRect.h, col.otherRect.x, col.otherRect.y, col.otherRect.w, col.otherRect.h, item, other, response);
}
}
}
}
if (tileMode) {
collisions.sort();
}
return collisions;
}
private void initDirWithJavaFiles(File libDir) throws IOException {
if (libDir.exists()) {
recursiveDelete(libDir);
}
libDir.mkdirs();
ArrayList<String> scratchpad = new ArrayList<>();
scratchpad.add("package lib;");
scratchpad.add("public class Fbo {");
scratchpad.add("public static void main(String... args){Foo.f();}");
scratchpad.add("public static void f(){}");
scratchpad.add("}");
createFile(new File(libDir, "Fbo.java"), scratchpad);
scratchpad.clear();
scratchpad.add("package lib;");
scratchpad.add("public class Foo {");
scratchpad.add("public static void main(String... args){");
scratchpad.add("for (String x : args) {");
scratchpad.add("System.out.println(x);");
scratchpad.add("}");
scratchpad.add("Fbo.f();");
scratchpad.add("}");
scratchpad.add("public static void f(){}");
scratchpad.add("}");
createFile(new File(libDir, "Foo.java"), scratchpad);
}
@Test
public void testWithOutCond1() throws Exception {
String userName = "test-001";
User user = prepareUser(userName);
user.setYuanbao(100);
user.setGoldenSimple(0);
ArrayList<XinqiMessage> list = new ArrayList<XinqiMessage>();
IoSession session = TestUtil.createIoSession(list);
user.setSession(session);
user.set_id(new UserId(username));
user.setSessionKey(SessionKey.createSessionKeyFromRandomString());
GameContext.getInstance().registerUserSession(session, user, null);
TaskManager manager = TaskManager.getInstance();
manager.deleteUserTasks(user);
TaskPojo task = new TaskPojo();
//2000 goledn
task.setId("10000");
task.setStep(1);
task.setScript(ScriptHook.TASK_SELL_GOOD.getHook());
task.setType(TaskType.TASK_ACHIVEMENT);
task.setName("二道贩子");
Award award = new Award();
award.id = "-1";
award.type = Constant.ACHIEVEMENT;
task.addAward(award);
LinkedList<TaskPojo> tasks = new LinkedList<TaskPojo>();
tasks.add(task);
user.addTasks(tasks);
TaskManager.getInstance().setTaskById(task);
//Sell goods
Bag bag = user.getBag();
WeaponPojo weapon = EquipManager.getInstance().getWeaponById(equipId2);
PropData propData = weapon.toPropData(30, WeaponColor.WHITE);
bag.addOtherPropDatas(propData);
Thread.sleep(200);
list.clear();
ShopManager shopManager = ShopManager.getInstance();
shopManager.sellGoodToShop(user, 20);
ConfirmManager.getInstance().receiveConfirmMessage(user, "shop.sell", 1);
Thread.sleep(200);
System.out.println(list);
XinqiMessage xinqi = null;
for ( XinqiMessage msg : list ) {
if (msg.payload instanceof BseFinishAchievement) {
xinqi = msg;
}
}
assertNotNull("BseFinishAchievement", xinqi);
}
@Test
public void testRoleMembership() {
Role role = roleService.getRole( role2Id );
assertNotNull( "r2 must exist", role );
ArrayList<String> roleList = new ArrayList<String>( 1 );
roleList.add( role2Id );
Collection<String> memberPrincipalIds = roleService.getRoleMemberPrincipalIds(role2NamespaceCode, role2Name, Collections.<String, String>emptyMap());
assertNotNull(memberPrincipalIds);
assertEquals("RoleTwo should have 6 principal ids", 5, memberPrincipalIds.size());
assertTrue( "p3 must belong to role", memberPrincipalIds.contains(principal3Id) );
assertTrue( "p2 must belong to role (assigned via group)", memberPrincipalIds.contains(principal2Id) );
assertTrue( "p1 must belong to r2 (via r1)", memberPrincipalIds.contains(principal1Id) );
Collection<RoleMembership> members = roleService.getRoleMembers( roleList, Collections.<String, String>emptyMap() );
assertNotNull( "returned list may not be null", members );
assertFalse( "list must not be empty", members.isEmpty() );
assertEquals("Returned list must have 4 members.", 4, members.size());
boolean foundP3 = false;
boolean foundG1 = false;
boolean foundR1 = false;
for (RoleMembership member : members) {
if (member.getMemberId().equals(principal3Id) && member.getType().equals(MemberType.PRINCIPAL)) {
foundP3 = true;
} else if (member.getMemberId().equals(group1Id) && member.getType().equals(MemberType.GROUP)) {
foundG1 = true;
} else if (member.getMemberId().equals(principal1Id) && member.getType().equals(MemberType.PRINCIPAL)) {
foundR1 = true;
assertEquals("Should have r1 embedded role id.", role1Id, member.getEmbeddedRoleId());
}
}
assertTrue("Failed to find p3 principal member", foundP3);
assertTrue("Failed to find g1 group member", foundG1);
assertTrue("Failed to find r1 role member", foundR1);
role = roleService.getRole( role1Id );
assertNotNull( "r1 must exist", role );
roleList.clear();
roleList.add( role1Id );
members = roleService.getRoleMembers( roleList, Collections.<String, String>emptyMap() );
assertNotNull( "returned list may not be null", members );
assertEquals("Should have 2 members", 2, members.size());
Iterator<RoleMembership> iter = members.iterator();
assertTrue("One of those members should be p1.", principal1Id.equals(iter.next().getMemberId()) || principal1Id.equals(iter.next().getMemberId()));
}
/**
* Copy data to CSV.
*
* @param csv CSVWriter.
* @param rows Array of rows.
* @param columns List of columns.
* @param includeHeader True to include column headers in the copy.
*/
private void toCSV(final SmartCSVWriter csv, final int[] rows, final List<Integer> columns, final boolean includeHeader) throws IOException {
int auditCounter = 0;
final TableModel dataModel = table.getModel();
int columnModelIdx;
final ArrayList<String> data = new ArrayList<>();
// Add column names.
if (includeHeader) {
final GraphTableModel gtmodel = (GraphTableModel) dataModel;
final GraphElementType elementType = gtmodel.getElementType();
for (final int column : columns) {
columnModelIdx = table.convertColumnIndexToModel(column);
String colName = dataModel.getColumnName(columnModelIdx);
// If this is a transaction table, prefix the column name with the element type so we know which column is which.
if (elementType == GraphElementType.TRANSACTION) {
switch (gtmodel.getAttributeSegment(columnModelIdx).segment) {
case TX:
colName = GraphRecordStoreUtilities.TRANSACTION + colName;
break;
case VX_SRC:
colName = GraphRecordStoreUtilities.SOURCE + colName;
break;
case VX_DST:
colName = GraphRecordStoreUtilities.DESTINATION + colName;
break;
default:
break;
}
}
data.add(colName);
}
csv.writeNext(data.toArray(new String[data.size()]));
}
// Add data.
for (final int row : rows) {
data.clear();
for (final Integer j : columns) {
final int rowModelIndex = table.convertRowIndexToModel(row);
columnModelIdx = table.convertColumnIndexToModel(j);
final Object o = dataModel.getValueAt(rowModelIndex, columnModelIdx);
final String s = o == null ? null : o.toString();
data.add(s);
auditCounter++;
}
csv.writeNext(data.toArray(new String[data.size()]));
}
final int count = auditCounter;
PluginExecution.withPlugin(new SimplePlugin("Copy To Clipboard") {
@Override
protected void execute(final PluginGraphs graphs, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
ConstellationLoggerHelper.copyPropertyBuilder(this, count, ConstellationLoggerHelper.SUCCESS);
}
}).executeLater(null);
}
/**
* Performs a number of random card drawings for the remaining board cards and uses this to compute the winning
* chance per bot. The chance per bot is computed as percentages multiplied with 10, for example 29.0% is stored as
* 290 so that simple integer representation is used with precision high enough. The odds information is added to
* the stored match history.
*/
private void updateBotOdds()
{
// set the current deck status as the starting point for each random draw
deck.setSavePoint();
int[] winsPerBot = new int[numberOfBots];
// perform the given number of random draws for table cards and count the winners
for(int n = 0; n < ODDS_RUNS; n++)
{
Vector<Card> tempTableCards = (Vector<Card>) tableCards.clone();
while(tempTableCards.size() < 5)
tempTableCards.add(deck.nextCard());
int[] botHandStrengths = computeHandStrengths(botHands, tempTableCards);
int maxStrength = -1;
ArrayList<Integer> winnerIndex = new ArrayList<Integer>();
for(int i = 0; i < numberOfBots; i++)
{
if(isInvolvedInHand[i] && botHandStrengths[i] >= maxStrength)
{
if(botHandStrengths[i] > maxStrength)
{
winnerIndex.clear();
maxStrength = botHandStrengths[i];
}
winnerIndex.add(i);
}
}
// keep track of the number of wins per bot in this simulation
for(int i = 0; i < winnerIndex.size(); i++)
winsPerBot[winnerIndex.get(i)]++;
// restore the deck to the current state
deck.restoreToSavePoint();
tempTableCards.clear();
// if all cards are on table, one run is sufficient, so make the stopping condition true
if(tableCards.size() == 5)
n = ODDS_RUNS;
}
// compute the total sum of winnings and use this to calculate the winning percentages
int sum = 0;
for(int i = 0; i < numberOfBots; i++)
if(isInvolvedInHand[i])
sum += winsPerBot[i];
// output the odds of the involved players
for(int i = 0; i < numberOfBots; i++)
{
String percentage;
if(isInvolvedInHand[i])
{
int percTimesTen = (int) Math.round(1000*winsPerBot[i] / (sum + .0));
percentage = Integer.toString(percTimesTen);
// below 1%, add the zero that comes in font of the dot
if(percTimesTen < 10)
percentage = "0" + percentage;
int stringLength = percentage.length();
percentage = percentage.substring(0, stringLength - 1) + "." + percentage.substring(stringLength - 1);
} else {
percentage = "0.0";
}
handHistory += String.format("\n%s odds %s%%", players.get(i).getName(), percentage);
}
}
/**
* Test isPropertyReadOnly() & isPropertyVisible().
*
* @throws SemanticException
*/
public void testIsPropertyReadOnlyAndIsPropertyVisible( )
throws SemanticException
{
ArrayList elements = new ArrayList( );
// bookmark and toc are all invisible
SimpleMasterPageHandle element = elemFactory
.newSimpleMasterPage( "my page" );//$NON-NLS-1$
LabelHandle element1 = elemFactory.newLabel( "label1" ); //$NON-NLS-1$
element.addElement( element1, SimpleMasterPage.PAGE_HEADER_SLOT );
elements.add( element1 );
GroupElementHandle groupHandle = new SimpleGroupElementHandle(
designHandle, elements );
assertTrue( !groupHandle.getPropertyHandle( ReportItem.TOC_PROP )
.isVisible( ) );
assertTrue( !groupHandle.getPropertyHandle( ReportItem.BOOKMARK_PROP )
.isVisible( ) );
assertTrue( !groupHandle
.getPropertyHandle( Style.PAGE_BREAK_AFTER_PROP ).isVisible( ) );
assertTrue( !groupHandle.getPropertyHandle(
Style.PAGE_BREAK_BEFORE_PROP ).isVisible( ) );
assertTrue( groupHandle.getPropertyHandle( ReportItem.TOC_PROP )
.isReadOnly( ) );
assertTrue( groupHandle.getPropertyHandle( ReportItem.BOOKMARK_PROP )
.isReadOnly( ) );
assertTrue( groupHandle.getPropertyHandle( Style.PAGE_BREAK_AFTER_PROP )
.isReadOnly( ) );
assertTrue( groupHandle
.getPropertyHandle( Style.PAGE_BREAK_BEFORE_PROP ).isReadOnly( ) );
// drop is only visible for cells in group
elements.clear( );
TableHandle table = elemFactory.newTableItem( "table" );
RowHandle row = elemFactory.newTableRow( );
CellHandle cell = elemFactory.newCell( );
row.addElement( cell, RowHandle.CONTENT_SLOT );
elements.add( cell );
groupHandle = new SimpleGroupElementHandle( designHandle, elements );
assertTrue( !groupHandle.getPropertyHandle( CellHandle.DROP_PROP )
.isVisible( ) );
assertTrue( groupHandle.getPropertyHandle( CellHandle.DROP_PROP )
.isReadOnly( ) );
}
private static IEnumerable<Object[]> AppendedPrependedConcatAlternationsData() {
final int EnumerableCount = 4; // How many enumerables to concat together per test case.
IEnumerable<Integer> foundation = Linq.empty();
ArrayList<Integer> expected = new ArrayList<>();
IEnumerable<Integer> actual = foundation;
ArgsList argsList = new ArgsList();
// each bit in the last EnumerableCount bits of i represent whether we want to prepend/append a sequence for this iteration.
// if it's set, we'll prepend. otherwise, we'll append.
for (int i = 0; i < (1 << EnumerableCount); i++) {
// each bit in last EnumerableCount bits of j is set if we want to ensure the nth enumerable
// concat'd is an ICollection.
// Note: It is important we run over the all-bits-set case, since currently
// Concat is specialized for when all inputs are ICollection.
for (int j = 0; j < (1 << EnumerableCount); j++) {
for (int k = 0; k < EnumerableCount; k++) {// k is how much bits we shift by, and also the item that gets appended/prepended.
IEnumerable<Integer> nextRange = Linq.range(k, 1);
boolean prepend = ((i >> k) & 1) != 0;
boolean forceCollection = ((j >> k) & 1) != 0;
if (forceCollection) {
nextRange = nextRange.toArray();
}
actual = prepend ? nextRange.concat(actual) : actual.concat(nextRange);
if (prepend) {
expected.add(0, k);
} else {
expected.add(k);
}
}
argsList.add(Linq.of(expected.toArray()), actual.toArray());
actual = foundation;
expected.clear();
}
}
return argsList;
}
/**
* if there is only one non-domination level (i.e., all solutions are non-dominated with each
* other), we should delete a solution from the most crowded subregion
*/
public void deleteRankOne(S indiv, int location) {
double indivFitness = fitnessFunction(indiv, lambda[location]);
// find the most crowded subregion, if there are more than one, keep them in crowdList
ArrayList<Integer> crowdList = new ArrayList<>();
int crowdIdx;
int nicheCount = countOnes(0);
if (location == 0) {
nicheCount++;
}
crowdList.add(0);
for (int i = 1; i < populationSize; i++) {
int curSize = countOnes(i);
if (location == i) {
curSize++;
}
if (curSize > nicheCount) {
crowdList.clear();
nicheCount = curSize;
crowdList.add(i);
} else if (curSize == nicheCount) {
crowdList.add(i);
}
}
// determine the index of the crowded subregion
if (crowdList.size() == 1) {
crowdIdx = crowdList.get(0);
} else {
int listLength = crowdList.size();
crowdIdx = crowdList.get(0);
double sumFitness = sumFitness(crowdIdx);
if (crowdIdx == location) {
sumFitness = sumFitness + indivFitness;
}
for (int i = 1; i < listLength; i++) {
int curIdx = crowdList.get(i);
double curFitness = sumFitness(curIdx);
if (curIdx == location) {
curFitness = curFitness + indivFitness;
}
if (curFitness > sumFitness) {
crowdIdx = curIdx;
sumFitness = curFitness;
}
}
}
switch (nicheCount) {
case 0:
System.out.println("Empty subregion!!!");
break;
case 1:
// if every subregion only contains one solution, delete the worst from indiv's subregion
int targetIdx;
for (targetIdx = 0; targetIdx < populationSize; targetIdx++) {
if (subregionIdx[location][targetIdx] == 1) {
break;
}
}
double prev_func = fitnessFunction(population.get(targetIdx), lambda[location]);
if (indivFitness < prev_func) {
replace(targetIdx, indiv);
}
break;
default:
if (location == crowdIdx) { // if indiv's subregion is the most crowded one
deleteCrowdIndiv_same(location, nicheCount, indivFitness, indiv);
} else {
int curNC = countOnes(location);
int crowdNC = countOnes(crowdIdx);
if (crowdNC > (curNC + 1)) { // if the crowdIdx subregion is more crowded, delete one from this subregion
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else if (crowdNC < (curNC + 1)) { // crowdNC == curNC, delete one from indiv's subregion
deleteCrowdIndiv_same(location, curNC, indivFitness, indiv);
} else { // crowdNC == (curNC + 1)
if (curNC == 0) {
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else {
double rnd = randomGenerator.nextDouble();
if (rnd < 0.5) {
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else {
deleteCrowdIndiv_same(location, curNC, indivFitness, indiv);
}
}
}
}
break;
}
}
public static void main(String[] args) throws Exception {
int initialSize = 20480*1024;
int maximumMapSize = 16*1024*1024;
int maximumFileSize = 300000000;
File file = File.createTempFile("exp", "tmp");
file.deleteOnExit();
RandomAccessFile f = new RandomAccessFile(file, "rw");
f.setLength(initialSize);
FileChannel fc = f.getChannel();
ByteBuffer[] buffers = new ByteBuffer[128];
System.out.format("map %d -> %d\n", 0, initialSize);
buffers[0] = fc.map(FileChannel.MapMode.READ_WRITE, 0, initialSize);
int currentBuffer = 0;
int currentSize = initialSize;
int currentPosition = 0;
ArrayList<String> junk = new ArrayList<String>();
while (currentPosition+currentSize < maximumFileSize) {
int inc = Math.max(1000*1024, (currentPosition+currentSize)/8);
int size = currentPosition+currentSize+inc;
f.setLength(size);
while (currentSize+inc > maximumMapSize) {
if (currentSize < maximumMapSize) {
System.out.format("map %d -> %d\n", currentPosition,
(currentPosition + maximumMapSize));
buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
currentPosition, maximumMapSize);
fillBuffer(buffers[currentBuffer], currentSize);
}
currentPosition += maximumMapSize;
inc = currentSize+inc-maximumMapSize;
currentSize = 0;
currentBuffer++;
if (currentBuffer == buffers.length) {
ByteBuffer[] old = buffers;
buffers = new ByteBuffer[currentBuffer+currentBuffer/2];
System.arraycopy(old, 0, buffers, 0, currentBuffer); }
}
currentSize += inc;
if (currentSize > 0) {
System.out.format("map %d -> %d\n", currentPosition,
(currentPosition + currentSize));
buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
currentPosition, currentSize);
fillBuffer(buffers[currentBuffer], currentSize-inc);
}
// busy loop needed to reproduce issue
long t = System.currentTimeMillis();
while (System.currentTimeMillis() < t+500) {
junk.add(String.valueOf(t));
if (junk.size() > 100000) junk.clear();
}
}
fc.close();
// cleanup the ref to mapped buffers so they can be GCed
for (int i = 0; i < buffers.length; i++)
buffers[i] = null;
System.gc();
// Take a nap to wait for the Cleaner to cleanup those unrefed maps
Thread.sleep(1000);
System.out.println("TEST PASSED");
}