public List<Spawner> loadAllSpawnersFromWorld(World w) { List<Spawner> list = new ArrayList<Spawner>(); String ch = File.separator; String worldDir = w.getWorldFolder() + ch + "cs_data" + ch; String entityDir = worldDir + ch + "entity"; String spawnerDir = worldDir + ch + "spawner"; File spawnerFiles = new File(spawnerDir); File entityFiles = new File(entityDir); if (!spawnerFiles.exists()) spawnerFiles.mkdirs(); if (!entityFiles.exists()) entityFiles.mkdirs(); for (File spawnerFile : spawnerFiles.listFiles()) { Spawner s = PLUGIN.getFileManager().loadSpawner(spawnerFile); List<Integer> sEntsAsIDs = s.getTypeData(); List<SpawnableEntity> sEnts = new ArrayList<SpawnableEntity>(); ArrayList<SpawnableEntity> containedEntities = new ArrayList<SpawnableEntity>(); for (Integer i : sEntsAsIDs) { sEnts.add(CustomSpawners.getEntity(i.toString())); } for (File f : entityFiles.listFiles()) { containedEntities.add(PLUGIN.getFileManager().loadEntity(f)); } if (containedEntities.containsAll(sEnts)) list.add(s); } return list; }
public boolean areConsecutiveVisits(List<Integer> visits, Patient patient) { if (patient != null && visits != null && (visits.size() > 0)) { List<Visit> patientVisits = visitService.getVisitsByPatient(patient, true, false); if ((patientVisits != null) && (patientVisits.size() > 0)) { ArrayList<Integer> allVisits = new ArrayList<Integer>(); int j = 0; for (Visit visit : patientVisits) { allVisits.add(j++, visit.getId()); } if (allVisits.containsAll(visits)) { // find the index of the first candidate for a consecutive visit int i = allVisits.indexOf(visits.get(0)); // make sure there are still more elements in the list than the the number of candidate // consecutives if ((allVisits.size() - i) >= visits.size()) { for (Integer candidateVisit : visits) { if (allVisits.get(i).compareTo(candidateVisit) == 0) { i++; } else { return false; } } return true; } } } } return false; }
@Override public void run() { while (true) { if (istWindows()) aktuell = holeLaufwerkeWindows(); else aktuell = holeLaufwerkeUnix(); if (initial.size() != aktuell.size()) { if (!initial.containsAll(aktuell)) { neuesLaufwerk = holePathVonNeuemLaufwerk(initial, aktuell); textArea.append("Neues Laufwerk endeckt: " + neuesLaufwerk + System.lineSeparator()); this.initial = (ArrayList<Path>) aktuell.clone(); neuesLaufwerkDialog(); } else { this.initial = (ArrayList<Path>) aktuell.clone(); textArea.append("Laufwerk wurde entfernt" + System.lineSeparator()); } } try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Laufwerksprüfung wird abgebrochen"); } } }
@Test public void checkGetElements() { assumeTrue(dataStructure instanceof INodeListDatastructureReadable); IReadable tempDS = (IReadable) dataStructure; int size = 20; IElement singleDummy; ArrayList<IElement> dummies = new ArrayList<>(); for (int i = 0; i < size; i++) { singleDummy = mock(this.elementClass); /* * Nodes are stored with an index, so set it please! */ if (singleDummy instanceof Node) { when(((Node) singleDummy).getIndex()).thenReturn(i); } if (singleDummy instanceof Edge) { when(((Edge) singleDummy).getHashString()).thenReturn("" + i); } assertTrue(tempDS.add(singleDummy)); dummies.add(singleDummy); } Collection<IElement> elements = tempDS.getElements(); /* * Check for the proper size and content */ assertEquals(dummies.size(), elements.size()); assertTrue(dummies.containsAll(elements)); assertTrue(elements.containsAll(dummies)); }
public void onValueChange(ValueChangeEvent<Boolean> event) { if (event.getSource() == regularRolesBtn) { if (regularRolesBtn.getValue()) { showRoles(REGULAR_ROLES_TYPE); } } else if (event.getSource() == systemRolesBtn) { if (systemRolesBtn.getValue()) { showRoles(SYSTEM_ROLES_TYPE); } } else { if (rolesListBox.getSelectedIndex() >= 0) { ArrayList<String> selectedLogicalRoles = new ArrayList<String>(); for (LogicalRoleInfo logicalRoleInfo : logicalRoles.values()) { if (logicalRoleInfo.checkBox.getValue()) { selectedLogicalRoles.add(logicalRoleInfo.roleName); } } String runtimeRole = rolesListBox.getItemText(rolesListBox.getSelectedIndex()); List<String> originalRoles = masterRoleMap.get(runtimeRole); if (((originalRoles == null) || (originalRoles.size() == 0)) && (selectedLogicalRoles.size() == 0)) { newRoleAssignments.remove(runtimeRole); } else if ((originalRoles != null) && (originalRoles.containsAll(selectedLogicalRoles)) && selectedLogicalRoles.containsAll(originalRoles)) { newRoleAssignments.remove(runtimeRole); } else { newRoleAssignments.put(runtimeRole, selectedLogicalRoles); } } } }
@Test public void shouldGetVisitsByType() throws IOException, InterruptedException { addTestVisitsToDB(); String jsonInput = getVisitsByLookup("{\"type\":\"SCREENING\"}", "Find Visit By Type", 1, 5); List<Visit> visits = deserializeVisits(jsonInput).getRows(); assertEquals(2, visits.size()); assertTrue(testVisits.containsAll(visits)); }
@Test public void shouldGetVisitsBySubjectName() throws IOException, InterruptedException { addTestVisitsToDB(); String jsonInput = getVisitsByLookup("{\"subject.name\":\"Rafal\"}", "Find Visit By Participant Name", 1, 5); List<Visit> visits = deserializeVisits(jsonInput).getRows(); assertEquals(2, visits.size()); assertTrue(testVisits.containsAll(visits)); }
public boolean isAncientSword(final ItemStack item) { final ArrayList<String> lore = new ArrayList<String>(); lore.add("AncientSword"); lore.add("Very old and mysterious sword."); lore.add("This will protect you aganist Herobrine."); if ((item != null) && (item.getItemMeta() != null) && (item.getItemMeta().getLore() != null)) { final ArrayList<String> ilore = (ArrayList<String>) item.getItemMeta().getLore(); if (ilore.containsAll(lore)) { return true; } } return false; }
/** Get keyword map */ private Map<String, Integer> getKeywordMapLive(String token, List<String> filter) throws RepositoryException, DatabaseException { log.debug("getKeywordMapLive({}, {})", token, filter); String statement = "/jcr:root//*[@jcr:primaryType eq 'okm:document' or @jcr:primaryType eq 'okm:mail' or @jcr:primaryType eq 'okm:folder']"; HashMap<String, Integer> cloud = new HashMap<String, Integer>(); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } Workspace workspace = session.getWorkspace(); QueryManager queryManager = workspace.getQueryManager(); Query query = queryManager.createQuery(statement, Query.XPATH); javax.jcr.query.QueryResult qResult = query.execute(); for (NodeIterator nit = qResult.getNodes(); nit.hasNext(); ) { Node doc = nit.nextNode(); Value[] keywordsValue = doc.getProperty(com.openkm.bean.Property.KEYWORDS).getValues(); ArrayList<String> keywordCollection = new ArrayList<String>(); for (int i = 0; i < keywordsValue.length; i++) { keywordCollection.add(keywordsValue[i].getString()); } if (filter != null && keywordCollection.containsAll(filter)) { for (Iterator<String> it = keywordCollection.iterator(); it.hasNext(); ) { String keyword = it.next(); if (!filter.contains(keyword)) { Integer occurs = cloud.get(keyword) != null ? cloud.get(keyword) : 0; cloud.put(keyword, occurs + 1); } } } } } catch (javax.jcr.RepositoryException e) { log.error(e.getMessage(), e); throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) JCRUtils.logout(session); } log.debug("getKeywordMapLive: {}", cloud); return cloud; }
@Override public List<SignalMetadata> getSignalList( Double minLatitude, Double minLongitude, Double maxLatitude, Double maxLongitude, List<String> params) { // Check if params is a list of carriers or phoneTypes ArrayList<String> paramList = new ArrayList<String>(Arrays.asList("0", "1", "2", "3")); if (paramList.containsAll(params)) { return getSignalList(minLatitude, minLongitude, maxLatitude, null, params, null); } else { return getSignalList( minLatitude, minLongitude, maxLatitude, maxLongitude, params, null, null); } }
protected static void getLocation() throws Exception { // has to be a location that support compute, storage, vm, some of the locations are not, need // to find out the right one ArrayList<String> serviceName = new ArrayList<String>(); serviceName.add(LocationAvailableServiceNames.COMPUTE); serviceName.add(LocationAvailableServiceNames.PERSISTENTVMROLE); serviceName.add(LocationAvailableServiceNames.STORAGE); LocationsListResponse locationsListResponse = managementClient.getLocationsOperations().list(); for (LocationsListResponse.Location location : locationsListResponse) { ArrayList<String> availableServicelist = location.getAvailableServices(); String locationName = location.getName(); if (availableServicelist.containsAll(serviceName) == true) { if (locationName.contains("West US") == true) { vmLocation = locationName; } if (vmLocation == null) { vmLocation = locationName; } } } }
@Override public boolean containsAll(Collection<?> c) { return children.containsAll(c); }
public boolean containsAll(Collection<?> collection) { return mMedia.containsAll(collection); }
public boolean containsAll(Collection<?> c) { return list.containsAll(c); }
public static void main(String[] args) throws Exception { // hoursInWeeks test { int hoursInOneWeek = 1 * 7 * 24; int hoursInFourWeeks = 4 * 7 * 24; int hoursInZeroWeeks = 0; System.out.println("----------------------"); if (getHoursInWeeks(1) == hoursInOneWeek) { System.out.println("getHoursInWeeks passed test 1!"); } else { System.out.println( "getHoursInWeeks failed test 1. Expected=" + hoursInOneWeek + " Got=" + getHoursInWeeks(1)); } if (getHoursInWeeks(4) == hoursInFourWeeks) { System.out.println("getHoursInWeeks passed test 2!"); } else { System.out.println( "getHoursInWeeks failed test 2. Expected=" + hoursInFourWeeks + " Got=" + getHoursInWeeks(4)); } if (getHoursInWeeks(0) == hoursInZeroWeeks) { System.out.println("getHoursInWeeks passed test 3!"); } else { System.out.println( "getHoursInWeeks failed test 3. Expected=" + hoursInZeroWeeks + " Got=" + getHoursInWeeks(0)); } } // isEven test { boolean isTwoEven = true; boolean isOneEven = false; boolean isZeroEven = true; boolean isEightyOneEven = false; System.out.println("----------------------"); if (isEven(2) == isTwoEven) { System.out.println("isEven passed test 1!"); } else { System.out.println("isEven failed test 1. Expected=" + isTwoEven + " Got=" + isEven(2)); } if (isEven(1) == isOneEven) { System.out.println("isEven passed test 2!"); } else { System.out.println("isEven failed test 2. Expected=" + isOneEven + " Got=" + isEven(1)); } if (isEven(0) == isZeroEven) { System.out.println("isEven passed test 3!"); } else { System.out.println("isEven failed test 3. Expected=" + isZeroEven + " Got=" + isEven(0)); } if (isEven(81) == isEightyOneEven) { System.out.println("isEven passed test 4!"); } else { System.out.println( "isEven failed test 4. Expected=" + isEightyOneEven + " Got=" + isEven(81)); } } // checkGrade test { String gradeEighty = "pass"; String gradeHundredAndFive = "pass"; String gradeFifty = "pass"; String gradeZero = "fail"; String gradeNegative = "fail"; System.out.println("----------------------"); if (gradeEighty.equalsIgnoreCase(checkGrade(80))) { System.out.println("checkGrade passed test 1!"); } else { System.out.println( "checkGrade failed test 1. Expected=" + gradeEighty + " Got=" + checkGrade(80)); } if (gradeHundredAndFive.equalsIgnoreCase(checkGrade(105))) { System.out.println("checkGrade passed test 2!"); } else { System.out.println( "checkGrade failed test 2. Expected=" + gradeHundredAndFive + " Got=" + checkGrade(105)); } if (gradeFifty.equalsIgnoreCase(checkGrade(50))) { System.out.println("checkGrade passed test 3!"); } else { System.out.println( "checkGrade failed test 3. Expected=" + gradeFifty + " Got=" + checkGrade(50)); } if (gradeZero.equalsIgnoreCase(checkGrade(0))) { System.out.println("checkGrade passed test 4!"); } else { System.out.println( "checkGrade failed test 4. Expected=" + gradeZero + " Got=" + checkGrade(0)); } if (gradeNegative.equalsIgnoreCase(checkGrade(-5))) { System.out.println("checkGrade passed test 5!"); } else { System.out.println( "checkGrade failed test 5. Expected=" + gradeNegative + " Got=" + checkGrade(-5)); } } // getSum test { ArrayList<Integer> testOne = new ArrayList<Integer>(Arrays.asList(new Integer[] {1, 10, 2})); ArrayList<Integer> testTwo = new ArrayList<Integer>(Arrays.asList(new Integer[] {100})); ArrayList<Integer> testThree = new ArrayList<Integer>(); System.out.println("----------------------"); if (getSum(testOne) == 13) { System.out.println("getSum passed test 1!"); } else { System.out.println("getSum failed test 1. Expected=13" + " Got=" + getSum(testOne)); } if (getSum(testTwo) == 100) { System.out.println("getSum passed test 2!"); } else { System.out.println("getSum failed test 2. Expected=100" + " Got=" + getSum(testTwo)); } if (getSum(testThree) == 0) { System.out.println("getSum passed test 3!"); } else { System.out.println("getSum failed test 3. Expected=0" + " Got=" + getSum(testThree)); } } // getAverage test { ArrayList<Integer> testOne = new ArrayList<Integer>(Arrays.asList(new Integer[] {1, 10, 2})); ArrayList<Integer> testTwo = new ArrayList<Integer>(Arrays.asList(new Integer[] {50, 100})); ArrayList<Integer> testThree = new ArrayList<Integer>(Arrays.asList(new Integer[] {0})); System.out.println("----------------------"); if (getAverage(testOne) == 13.0 / 3) { System.out.println("getAverage passed test 1!"); } else { System.out.println( "getAverage failed test 1. Expected=" + 13.0 / 3 + " Got=" + getAverage(testOne)); } if (getAverage(testTwo) == 75) { System.out.println("getAverage passed test 2!"); } else { System.out.println( "getAverage failed test 2. Expected=" + 75 + " Got=" + getAverage(testTwo)); } if (getAverage(testThree) == 0) { System.out.println("getAverage passed test 3!"); } else { System.out.println( "getAverage failed test 3. Expected=" + 0 + " Got=" + getAverage(testThree)); } } // makeSentence test { ArrayList<String> testOne = new ArrayList<String>(Arrays.asList(new String[] {"Hi", "there"})); String resultOne = "Hi there"; ArrayList<String> testTwo = new ArrayList<String>(Arrays.asList(new String[] {"How", "are", "you"})); String resultTwo = "How are you"; ArrayList<String> testThree = new ArrayList<String>(); String resultThree = ""; System.out.println("----------------------"); if (resultOne.equals(makeSentence(testOne))) { System.out.println("makeSentence passed test 1!"); } else { System.out.println( "makeSentence failed test 1. Expected=" + resultOne + " Got=" + makeSentence(testOne)); } if (resultTwo.equals(makeSentence(testTwo))) { System.out.println("makeSentence passed test 2!"); } else { System.out.println( "makeSentence failed test 2. Expected=" + resultTwo + " Got=" + makeSentence(testTwo)); } if (resultThree.equals(makeSentence(testThree))) { System.out.println("makeSentence passed test 3!"); } else { System.out.println( "makeSentence failed test 3. Expected=" + resultThree + " Got=" + makeSentence(testThree)); } } // createNumberMap test { HashMap<Integer, String> results = createNumberMap(); System.out.println("----------------------"); if (results != null) { boolean checkNumKeys = results.keySet().size() == 10; boolean checkAllKeys = results.containsKey(1) && results.containsKey(2) && results.containsKey(3) && results.containsKey(4) && results.containsKey(5) && results.containsKey(6) && results.containsKey(7) && results.containsKey(8) && results.containsKey(9) && results.containsKey(10); if (checkNumKeys && checkAllKeys) { boolean checkAllValues = results.get(1).equalsIgnoreCase("one") && results.get(2).equalsIgnoreCase("two") && results.get(3).equalsIgnoreCase("three") && results.get(4).equalsIgnoreCase("four") && results.get(5).equalsIgnoreCase("five") && results.get(6).equalsIgnoreCase("six") && results.get(7).equalsIgnoreCase("seven") && results.get(8).equalsIgnoreCase("eight") && results.get(9).equalsIgnoreCase("nine") && results.get(10).equalsIgnoreCase("ten"); if (checkAllValues) { System.out.println("createNumberMap passed test!"); } else { System.out.println("createNumberMap failed to contain the correct values."); } } else { System.out.println("createNumberMap failed to contain the correct keys."); } } else { System.out.println("createNumberMap is returning a null object."); } } // getNumberText test { int testOne = 1; String resultOne = "one"; int testTwo = 0; String resultTwo = "not found"; int testThree = -1; String resultThree = "not found"; System.out.println("----------------------"); if (resultOne.equalsIgnoreCase(getNumberText(testOne))) { System.out.println("getNumberText passed test 1!"); } else { System.out.println( "getNumberText failed test 1. Expected=" + resultOne + " Got=" + getNumberText(testOne)); } if (resultTwo.equalsIgnoreCase(getNumberText(testTwo))) { System.out.println("getNumberText passed test 2!"); } else { System.out.println( "getNumberText failed test 2. Expected=" + resultTwo + " Got=" + getNumberText(testTwo)); } if (resultThree.equalsIgnoreCase(getNumberText(testThree))) { System.out.println("getNumberText passed test 3!"); } else { System.out.println( "getNumberText failed test 3. Expected=" + resultThree + " Got=" + getNumberText(testThree)); } } // getFibonacciNumber test { int testOneIndex = 1; int resultOne = 1; int testTwoIndex = 4; int resultTwo = 3; int testThreeIndex = 10; int resultThree = 55; System.out.println("----------------------"); if (resultOne == getFibonacciNumber(testOneIndex)) { System.out.println("getFibonacciNumber passed test 1!"); } else { System.out.println( "getFibonacciNumber failed test 1. Expected=" + resultOne + " Got=" + getFibonacciNumber(testOneIndex)); } if (resultTwo == getFibonacciNumber(testTwoIndex)) { System.out.println("getFibonacciNumber passed test 2!"); } else { System.out.println( "getFibonacciNumber failed test 2. Expected=" + resultTwo + " Got=" + getFibonacciNumber(testTwoIndex)); } if (resultThree == getFibonacciNumber(testThreeIndex)) { System.out.println("getFibonacciNumber passed test 3!"); } else { System.out.println( "getFibonacciNumber failed test 3. Expected=" + resultThree + " Got=" + getFibonacciNumber(testThreeIndex)); } } // getDuplicates test { LinkedList<Integer> testOne = new LinkedList<Integer>(Arrays.asList(new Integer[] {1, 1, 2})); ArrayList<Integer> resultOne = new ArrayList<Integer>(Arrays.asList(new Integer[] {1})); HashSet<Integer> resultSetOne = getDuplicates(testOne); LinkedList<Integer> testTwo = new LinkedList<Integer>(Arrays.asList(new Integer[] {1, 1, 1, 1})); ArrayList<Integer> resultTwo = new ArrayList<Integer>(Arrays.asList(new Integer[] {1})); HashSet<Integer> resultSetTwo = getDuplicates(testTwo); LinkedList<Integer> testThree = new LinkedList<Integer>(); ArrayList<Integer> resultThree = new ArrayList<Integer>(); HashSet<Integer> resultSetThree = getDuplicates(testThree); LinkedList<Integer> testFour = new LinkedList<Integer>(Arrays.asList(new Integer[] {1, 2, 3, 4})); ArrayList<Integer> resultFour = new ArrayList<Integer>(); HashSet<Integer> resultSetFour = getDuplicates(testFour); System.out.println("----------------------"); if (resultSetOne == null) { System.out.println( "getDuplicates failed test 1. Expected=" + resultOne + " Got=" + resultSetOne); } else if (resultOne.containsAll(resultSetOne) && resultSetOne.size() == resultOne.size()) { System.out.println("getDuplicates passed test 1!"); } if (resultSetTwo == null) { System.out.println( "getDuplicates failed test 2. Expected=" + resultTwo + " Got=" + resultSetTwo); } else if (resultTwo.containsAll(resultSetTwo) && resultSetTwo.size() == resultTwo.size()) { System.out.println("getDuplicates passed test 2!"); } if (resultSetThree == null) { System.out.println( "getDuplicates failed test 3. Expected=" + resultThree + " Got=" + resultSetThree); } else if (resultSetThree.size() == 0) { System.out.println("getDuplicates passed test 3!"); } if (resultSetFour == null) { System.out.println( "getDuplicates failed test 4. Expected=" + resultFour + " Got=" + resultSetFour); } else if (resultSetFour.size() == 0) { System.out.println("getDuplicates passed test 4!"); } } System.out.println("----------------------"); System.out.println("YOU ARE AWESOME!"); }
public boolean containsAll(Collection c) { return myList.containsAll(c); }
public boolean containsAll(Collection<?> collection) { return mSlides.containsAll(collection); }
@Override public List<DiscoveryNode> buildDynamicNodes() { List<DiscoveryNode> discoNodes = new ArrayList<>(); DescribeInstancesResult descInstances; try { // Query EC2 API based on AZ, instance state, and tag. // NOTE: we don't filter by security group during the describe instances request for two // reasons: // 1. differences in VPCs require different parameters during query (ID vs Name) // 2. We want to use two different strategies: (all security groups vs. any security groups) descInstances = client.describeInstances(buildDescribeInstancesRequest()); } catch (AmazonClientException e) { logger.info("Exception while retrieving instance list from AWS API: {}", e.getMessage()); logger.debug("Full exception:", e); return discoNodes; } logger.trace("building dynamic unicast discovery nodes..."); for (Reservation reservation : descInstances.getReservations()) { for (Instance instance : reservation.getInstances()) { // lets see if we can filter based on groups if (!groups.isEmpty()) { List<GroupIdentifier> instanceSecurityGroups = instance.getSecurityGroups(); ArrayList<String> securityGroupNames = new ArrayList<String>(); ArrayList<String> securityGroupIds = new ArrayList<String>(); for (GroupIdentifier sg : instanceSecurityGroups) { securityGroupNames.add(sg.getGroupName()); securityGroupIds.add(sg.getGroupId()); } if (bindAnyGroup) { // We check if we can find at least one group name or one group id in groups. if (Collections.disjoint(securityGroupNames, groups) && Collections.disjoint(securityGroupIds, groups)) { logger.trace( "filtering out instance {} based on groups {}, not part of {}", instance.getInstanceId(), instanceSecurityGroups, groups); // continue to the next instance continue; } } else { // We need tp match all group names or group ids, otherwise we ignore this instance if (!(securityGroupNames.containsAll(groups) || securityGroupIds.containsAll(groups))) { logger.trace( "filtering out instance {} based on groups {}, does not include all of {}", instance.getInstanceId(), instanceSecurityGroups, groups); // continue to the next instance continue; } } } String address = null; switch (hostType) { case PRIVATE_DNS: address = instance.getPrivateDnsName(); break; case PRIVATE_IP: address = instance.getPrivateIpAddress(); break; case PUBLIC_DNS: address = instance.getPublicDnsName(); break; case PUBLIC_IP: address = instance.getPublicIpAddress(); break; } if (address != null) { try { TransportAddress[] addresses = transportService.addressesFromString(address); // we only limit to 1 addresses, makes no sense to ping 100 ports for (int i = 0; (i < addresses.length && i < UnicastZenPing.LIMIT_PORTS_COUNT); i++) { logger.trace( "adding {}, address {}, transport_address {}", instance.getInstanceId(), address, addresses[i]); discoNodes.add( new DiscoveryNode( "#cloud-" + instance.getInstanceId() + "-" + i, addresses[i], version.minimumCompatibilityVersion())); } } catch (Exception e) { logger.warn("failed ot add {}, address {}", e, instance.getInstanceId(), address); } } else { logger.trace( "not adding {}, address is null, host_type {}", instance.getInstanceId(), hostType); } } } logger.debug("using dynamic discovery nodes {}", discoNodes); return discoNodes; }
public boolean containsAll(Collection<?> trees) { return list.containsAll(trees); }
/** * El metodo se encarga de realizar la asignación Hibrida para depósitos con capacidad limitada * (Algoritmo 1). * * <p>Recibe por parámetro <code>DTDepositoVRP</code> donde contiene toda la información del * problema a resolver. * * <p>Retorna una colección de <code>DTAsignacion</code>. Cada <code>DTAsignacion</code> contiene * un deposito y una colección de clientes que estan asignados al deposito. * * @param d <code>DTDepositoVRP</code> donde contiene toda la información del problema a resolver. * @return Devuelve una colección de <code>DTAsignacion</code>.. */ public Collection<DTAsignacion> asignar(DTDepositoVRP d) { System.out.println("Asignar capacidad"); clientes = new ArrayList<ClienteCap2>(); depositos = new ArrayList<Deposito>(); enajenados = new ArrayList<Enajenado>(); Iterator<DTNodo> it = d.getNodos().iterator(); while (it.hasNext()) { DTNodo dt = it.next(); if (dt.getEsDesposito()) { Deposito dep = new Deposito(dt); depositos.add(dep); } } Iterator<DTNodo> it2 = d.getNodos().iterator(); while (it2.hasNext()) { DTNodo dt = it2.next(); if (!dt.getEsDesposito()) { ClienteCap2 cli = new ClienteCap2(dt); cli.setMu(calcularMu(cli, depositos)); clientes.add(cli); } } // Calculo los 2 clientes mas cercanos para cada cliente (precalculo para fase 2) Iterator<ClienteCap2> it3 = this.clientes.iterator(); while (it3.hasNext()) { ClienteCap2 cliente = it3.next(); cliente = addClientesMasCercanos(cliente); System.out.println( "Clientes mas cercanos" + cliente.getNodo().getId() + " y nodos " + cliente.getClieteMasCercano1().getNodo().getId() + " ," + cliente.getClieteMasCercano2().getNodo().getId()); } // Asigno los nodos por urgencia (fase 1). while (clientes.size() > 0) { TreeSet<ClienteCap2> tr = new TreeSet<ClienteCap2>(clientes); Iterator<ClienteCap2> itc = tr.iterator(); ClienteCap2 proximo = itc.next(); proximo .getMasCercano() .agregarCliente(proximo); // agrego el cliente en el deposito mas cercano. clientes.remove(proximo); Iterator<ClienteCap2> itcli = clientes.iterator(); while (itcli.hasNext()) { ClienteCap2 n = itcli.next(); n.setMu(calcularMu(n, depositos)); } } // agrego a lista si los 2 cliente + cercanos a cada cliente pertencen al mismo deposito // deposito (que no es el mismo que el deposito asignado para el cliente). // acaaaa int capacidadvehiculo = Integer.valueOf(d.getCAPACITY()); System.out.println("cap del vehiculo " + capacidadvehiculo); ArrayList<DTAsignacion> ar = null; int costomenor = 0; Iterator<Deposito> itdd = this.depositos.iterator(); while (itdd.hasNext()) { Deposito dep = itdd.next(); DTAsignacion dta = new DTAsignacion(dep.getNodo()); Iterator<Cliente> itcli = dep.getAsignados().iterator(); while (itcli.hasNext()) { Cliente cli = itcli.next(); dta.agregarCliente(cli.getNodo()); } Iterator<DTRuteo> itrut = Fabrica.getInstancia().getRuteo().rutear(dta, capacidadvehiculo).iterator(); while (itrut.hasNext()) { DTRuteo next = itrut.next(); costomenor = costomenor + next.getCosto(); } } System.out.println("costo inicial " + costomenor); int cantidadIteraciones = 0; // Inicializo el Tiempo en Config Config.getInstancia().empezarAlgoritmo(costomenor); ArrayList<Integer> aux, tmp; tmp = new ArrayList<Integer>(); boolean terminar = false; while (!terminar) { cantidadIteraciones++; System.out.println("Cantidad Iteraciones " + cantidadIteraciones); this.calcularEnagenamiento(); // Aplico todos los cambios de la lista de enajenados .... aux = new ArrayList<Integer>(); Iterator<Enajenado> itena = this.enajenados.iterator(); while (itena.hasNext()) { Enajenado ena = itena.next(); aux.add(ena.getCliente().getNodo().getId()); if (ena.getDepositoDestino().getCapacidadLibrePonderada() >= ena.getCliente().getNodo().getDemanda()) { Iterator<Deposito> respita = this.depositos.iterator(); while (respita.hasNext()) { Deposito dep = respita.next(); Deposito nuevo = new Deposito(dep); if (nuevo.getNodo().getId() == ena.getDeposito().getNodo().getId()) nuevo.sacarCliente(ena.getCliente()); if (nuevo.getNodo().getId() == ena.getDepositoDestino().getNodo().getId()) nuevo.agregarCliente(ena.getCliente()); DTAsignacion dta = new DTAsignacion(nuevo.getNodo()); Iterator<Cliente> itcli = nuevo.getAsignados().iterator(); while (itcli.hasNext()) { Cliente cli = itcli.next(); dta.agregarCliente(cli.getNodo()); } } ena.getDeposito().sacarCliente(ena.getCliente()); ena.getDepositoDestino().agregarCliente(ena.getCliente()); } } boolean equalLists = ((aux.size() == tmp.size()) && (tmp.containsAll(aux))); tmp = new ArrayList<Integer>(); tmp.addAll(aux); if ((Config.getInstancia().terminarPorConfig(cantidadIteraciones, costomenor)) || equalLists) terminar = true; } // construir DT de salida. ar = new ArrayList<DTAsignacion>(); Iterator<Deposito> itd = depositos.iterator(); while (itd.hasNext()) { Deposito dep = itd.next(); DTAsignacion dta = new DTAsignacion(dep.getNodo()); Iterator<Cliente> itcli = dep.getAsignados().iterator(); while (itcli.hasNext()) { Cliente cli = itcli.next(); dta.agregarCliente(cli.getNodo()); } ar.add(dta); } Penalization.getInstancia().getCalculoPenalidad(ar); return ar; }
/** * Calculates patrol routes (depending on reachable <b>Coordinates</b> by <b>Guardian</b>) to see * all the <b>Grid</b>.</br> A patrol route is then assigned to each <b>Guardian</b> (If several * <b>Guardians</b> have access to the same <b>Coordinates</b>, their patrol will be the same). * * @param guardians : a list of <b>Guardians</b> in order to directly assign their patrol route. * @return a list containing all the <b>Coordinates</b> of all the patrols routes. (Debug) */ public ArrayList<Coordinate> patrolRouteCalculation(ArrayList<Guardian> guardians) { // long debut = System.currentTimeMillis(); int dimension = grid.getDimension(); // ArrayList de coordonnees pour l'itineraire de patrouille ArrayList<Coordinate> validCoordinates = new ArrayList<Coordinate>(); // ArrayList de coordonnees pour l'itineraire de patrouille // HashMap de coordonnees, et de l'ArrayList contenant le champ de vision a partir de cette // coordoneee HashMap<Coordinate, ArrayList<Coordinate>> visible = new HashMap<Coordinate, ArrayList<Coordinate>>(); // init ArrayList, tableau et HashMap for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { Coordinate coordTemp = new Coordinate(i, j); // System.out.println(grid); if (grid.isValid(coordTemp) && grid.isDirectlyAccessible(coordTemp)) { validCoordinates.add(coordTemp); visible.put(coordTemp, visualFieldCalculation(coordTemp)); } } } // Remplissage d'une HashMap avec les gardians pour Cle, et une ArrayList de coordonnees // atteignables en Valeur HashMap<Guardian, ArrayList<Coordinate>> guardianToCoordinates = new HashMap<Guardian, ArrayList<Coordinate>>(); for (Guardian guard : guardians) { ArrayList<Coordinate> accessibleCoordinatesGuardian = new ArrayList<Coordinate>(); for (Coordinate coord : validCoordinates) { ArrayList<Coordinate> itineraireTemp = routeCalculation(guard.getPosition(), coord, false); if (itineraireTemp.size() > 2 || areAdjacent(guard.getPosition(), coord)) // Coord accessible accessibleCoordinatesGuardian.add(coord); } accessibleCoordinatesGuardian.add(guard.getPosition()); Collections.sort(accessibleCoordinatesGuardian, new Tri.SortByCoordinate()); guardianToCoordinates.put(guard, accessibleCoordinatesGuardian); } // System.out.println(guardianVersCoordinates); // System.out.println(); // System.out.println(); // Fusion en ArrayList si plusieurs gardiens ont les mêmes coordonnees atteignables HashMap<ArrayList<Coordinate>, ArrayList<Guardian>> coordinatesToGuardians = new HashMap<ArrayList<Coordinate>, ArrayList<Guardian>>(); for (Guardian guard : guardians) { ArrayList<Guardian> guardiansCoord = coordinatesToGuardians.get(guardianToCoordinates.get(guard)); if (guardiansCoord == null) { guardiansCoord = new ArrayList<Guardian>(); } if (!guardiansCoord.contains(guard)) guardiansCoord.add(guard); coordinatesToGuardians.put(guardianToCoordinates.get(guard), guardiansCoord); } // System.out.println(coordinatesVersGuardian); // A ce moment, coordinatesVersGuardian contient des ArrayList de coordonnees atteignables // comme clé, // et des ArrayList des guardiens qui peuvent les atteindre comme valeur // HashMap inverse de CoordinatesVersGuardians HashMap<ArrayList<Guardian>, ArrayList<Coordinate>> guardiansToCoordinates = new HashMap<ArrayList<Guardian>, ArrayList<Coordinate>>(); for (ArrayList<Coordinate> alCoord : coordinatesToGuardians.keySet()) { guardiansToCoordinates.put(coordinatesToGuardians.get(alCoord), alCoord); } // initialisation des coordonnes a visiter pour effectuer la patrouille (checkpoint) // ne represente pas l'itineraire // ne garde que quelques coordonnes cles ArrayList<Coordinate> globalPatrolCoordinates = new ArrayList<Coordinate>(validCoordinates); // calculer si un ensemble d'ArrayList de coordonnees ne contiendrait pas par hasard toutes les // coordonnees visibles depuis une certaine coordonnee // calculer si le fait de supprimer une coordonnee enleve des cases visibles a l'ArrayList for (int i = 0; i < globalPatrolCoordinates.size(); i++) { ArrayList<Coordinate> coordinatesMinusOne = new ArrayList<Coordinate>(); ArrayList<Coordinate> unsortedVisibleCoordinatesMinusOne = new ArrayList<Coordinate>(); ArrayList<Coordinate> sortedVisibleCoordinatesMinusOne = new ArrayList<Coordinate>(); for (Coordinate coordTest : globalPatrolCoordinates) { coordinatesMinusOne.add(coordTest); } Coordinate coordReference = globalPatrolCoordinates.get(i); coordinatesMinusOne.remove(coordReference); for (Coordinate coordTemp : coordinatesMinusOne) { unsortedVisibleCoordinatesMinusOne.addAll(visible.get(coordTemp)); } Set<Coordinate> mySet = new HashSet<Coordinate>(unsortedVisibleCoordinatesMinusOne); sortedVisibleCoordinatesMinusOne.addAll(mySet); if (sortedVisibleCoordinatesMinusOne.containsAll(validCoordinates)) { globalPatrolCoordinates.remove(coordReference); i--; } } ArrayList<Coordinate> allPatrolsRoutes = new ArrayList<Coordinate>(); // debut boucle for (ArrayList<Guardian> alGuardian : coordinatesToGuardians.values()) { // On ne garde que les coordonnees atteignables par le groupe de gardiens ArrayList<Coordinate> groupPatrolCoordinates = new ArrayList<Coordinate>(globalPatrolCoordinates); // for(Coordinates coord : coordinatesPatrouilleGroupe) { // if(!guardiansVersCoordinates.get(alGuardian).contains(coord)) // coordinatesPatrouilleGroupe.remove(coord); // } for (int i = 0; i < groupPatrolCoordinates.size(); i++) { Coordinate coord = groupPatrolCoordinates.get(i); if (!guardiansToCoordinates.get(alGuardian).contains(coord)) { groupPatrolCoordinates.remove(coord); i--; } } TreeMap<Integer, Coordinate> patrolRoute = new TreeMap<Integer, Coordinate>(); // Si aucun checkpoint accessible if (groupPatrolCoordinates.size() == 0) { for (Guardian guardTemp : alGuardian) { guardTemp.setPatrolPosition(-2); } } else { ArrayList<Coordinate> routeFinal = new ArrayList<Coordinate>(); ArrayList<Coordinate> routeTemp = new ArrayList<Coordinate>(); Coordinate coordSource = groupPatrolCoordinates.get(0); Coordinate coordSourceTemp = coordSource; Coordinate coordTemp = null; int index = 0; while (groupPatrolCoordinates.size() > 0) { groupPatrolCoordinates.remove(coordSourceTemp); routeFinal.clear(); routeTemp.clear(); for (Coordinate coordDestinationTemp : groupPatrolCoordinates) { routeTemp = routeCalculation(coordSourceTemp, coordDestinationTemp, false); // System.out.println("Itineraire " + coordSourceTemp + " vers " + coordDestinationTemp // + " : " + itineraireTemp); if (routeFinal.size() == 0 || (routeTemp.size() != 0 && routeTemp.size() < routeFinal.size())) { routeFinal = new ArrayList<Coordinate>(routeTemp); coordTemp = coordDestinationTemp; } } // System.out.println(itineraireFinal); coordSourceTemp = coordTemp; for (int i = 0; i < routeFinal.size() - 1; i++) { patrolRoute.put(index, routeFinal.get(i)); index++; } } // Ajout de l'itineraire pour aller e la fin de la patrouille vers le debut routeFinal = routeCalculation(coordTemp, coordSource, false); for (int i = 0; i < routeFinal.size() - 1; i++) { patrolRoute.put(index, routeFinal.get(i)); index++; } // affectation de la patrouille a tous les gardiens, a modifier for (Guardian guardTemp : alGuardian) { guardTemp.setPatrol(patrolRoute); guardTemp.setReachableCoordinates(guardiansToCoordinates.get(alGuardian)); } allPatrolsRoutes.addAll(patrolRoute.values()); } // fin boucle } // entre 100 et 1000ms en fonction de la taille (complexite lineaire) // System.out.println(System.currentTimeMillis() - debut); // System.out.println(itinerairePatrouille); return allPatrolsRoutes; }
/** * Calculates patrol's <b>Coordinates</b>.</br> * * @param guardians : a list of <b>Guardians</b> to share the patrol. * @return a list containing the <b>Coordinates</b> checkpoints of the patrol. (Debug) */ public ArrayList<Coordinate> calculCoordinatesPatrouille(ArrayList<Guardian> guardians) { // long debut = System.currentTimeMillis(); int dimension = grid.getDimension(); // ArrayList de coordonnees pour l'itineraire de patrouille ArrayList<Coordinate> validCoordinates = new ArrayList<Coordinate>(); // ArrayList de coordonnees pour l'itineraire de patrouille // HashMap de coordonnees, et de l'ArrayList contenant le champ de vision a partir de cette // coordoneee HashMap<Coordinate, ArrayList<Coordinate>> visible = new HashMap<Coordinate, ArrayList<Coordinate>>(); // init ArrayList, tableau et HashMap for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { Coordinate coordTemp = new Coordinate(i, j); // System.out.println(grid); if (grid.isValid(coordTemp) && grid.isDirectlyAccessible(coordTemp)) { validCoordinates.add(coordTemp); visible.put(coordTemp, visualFieldCalculation(coordTemp)); } } } // Remplissage d'une HashMap avec les gardians pour Cle, et une ArrayList de coordonnees // atteignables en Valeur HashMap<Guardian, ArrayList<Coordinate>> guardianToCoordinates = new HashMap<Guardian, ArrayList<Coordinate>>(); for (Guardian guard : guardians) { ArrayList<Coordinate> accessibleCoordinatesGuardian = new ArrayList<Coordinate>(); for (Coordinate coord : validCoordinates) { ArrayList<Coordinate> itineraireTemp = routeCalculation(guard.getPosition(), coord, false); if (itineraireTemp.size() > 2 || areAdjacent(guard.getPosition(), coord)) // Coord accessible accessibleCoordinatesGuardian.add(coord); } accessibleCoordinatesGuardian.add(guard.getPosition()); Collections.sort(accessibleCoordinatesGuardian, new Tri.SortByCoordinate()); guardianToCoordinates.put(guard, accessibleCoordinatesGuardian); } // System.out.println(guardianVersCoordinates); // System.out.println(); // System.out.println(); // Fusion en ArrayList si plusieurs gardiens ont les mêmes coordonnees atteignables HashMap<ArrayList<Coordinate>, ArrayList<Guardian>> coordinatesToGuardians = new HashMap<ArrayList<Coordinate>, ArrayList<Guardian>>(); for (Guardian guard : guardians) { ArrayList<Guardian> guardiansCoord = coordinatesToGuardians.get(guardianToCoordinates.get(guard)); if (guardiansCoord == null) { guardiansCoord = new ArrayList<Guardian>(); } if (!guardiansCoord.contains(guard)) guardiansCoord.add(guard); coordinatesToGuardians.put(guardianToCoordinates.get(guard), guardiansCoord); } // System.out.println(coordinatesVersGuardian); // A ce moment, coordinatesVersGuardian contient des ArrayList de coordonnees atteignables // comme clé, // et des ArrayList des guardiens qui peuvent les atteindre comme valeur // HashMap inverse de CoordinatesVersGuardians HashMap<ArrayList<Guardian>, ArrayList<Coordinate>> guardiansToCoordinates = new HashMap<ArrayList<Guardian>, ArrayList<Coordinate>>(); for (ArrayList<Coordinate> alCoord : coordinatesToGuardians.keySet()) { guardiansToCoordinates.put(coordinatesToGuardians.get(alCoord), alCoord); } // initialisation des coordonnes a visiter pour effectuer la patrouille (checkpoint) // ne represente pas l'itineraire // ne garde que quelques coordonnes cles ArrayList<Coordinate> patrolCoordinates = new ArrayList<Coordinate>(validCoordinates); // calculer si un ensemble d'ArrayList de coordonnees ne contiendrait pas par hasard toutes les // coordonnees visibles depuis une certaine coordonnee // calculer si le fait de supprimer une coordonnee enleve des cases visibles a l'ArrayList for (int i = 0; i < patrolCoordinates.size(); i++) { ArrayList<Coordinate> coordinatesMinusOne = new ArrayList<Coordinate>(); ArrayList<Coordinate> unsortedVisibleCoordinatesMinusOne = new ArrayList<Coordinate>(); ArrayList<Coordinate> sortedVisibleCoordinatesMinusOne = new ArrayList<Coordinate>(); for (Coordinate coordTest : patrolCoordinates) { coordinatesMinusOne.add(coordTest); } Coordinate coordReference = patrolCoordinates.get(i); coordinatesMinusOne.remove(coordReference); for (Coordinate coordTemp : coordinatesMinusOne) { unsortedVisibleCoordinatesMinusOne.addAll(visible.get(coordTemp)); } Set<Coordinate> mySet = new HashSet<Coordinate>(unsortedVisibleCoordinatesMinusOne); sortedVisibleCoordinatesMinusOne.addAll(mySet); if (sortedVisibleCoordinatesMinusOne.containsAll(validCoordinates)) { patrolCoordinates.remove(coordReference); i--; } } return patrolCoordinates; }
@Override public boolean containsAll(Collection<?> c) { return original.containsAll(c); }
public boolean containsAll(Collection<?> c) { return internalList.containsAll(c); }
/** @tests java.util.ArrayList#addAll(int, java.util.Collection) */ @SuppressWarnings("unchecked") public void test_addAllILjava_util_Collection_2() { // Regression for HARMONY-467 ArrayList obj = new ArrayList(); try { obj.addAll((int) -1, (Collection) null); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected assertNotNull(e.getMessage()); } // Regression for HARMONY-5705 String[] data = new String[] {"1", "2", "3", "4", "5", "6", "7", "8"}; ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); for (String d : data) { list1.add(d); list2.add(d); list2.add(d); } while (list1.size() > 0) list1.remove(0); list1.addAll(list2); assertTrue( "The object list is not the same as original list", list1.containsAll(list2) && list2.containsAll(list1)); obj = new ArrayList(); for (int i = 0; i < 100; i++) { if (list1.size() > 0) { obj.removeAll(list1); obj.addAll(list1); } } assertTrue( "The object list is not the same as original list", obj.containsAll(list1) && list1.containsAll(obj)); // Regression for Harmony-5799 list1 = new ArrayList(); list2 = new ArrayList(); int location = 2; String[] strings = {"0", "1", "2", "3", "4", "5", "6"}; int[] integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (int i = 0; i < 7; i++) { list1.add(strings[i]); } for (int i = 0; i < 10; i++) { list2.add(integers[i]); } list1.remove(location); list1.addAll(location, list2); // Inserted elements should be equal to integers array for (int i = 0; i < integers.length; i++) { assertEquals(integers[i], list1.get(location + i)); } // Elements after inserted location should // be equals to related elements in strings array for (int i = location + 1; i < strings.length; i++) { assertEquals(strings[i], list1.get(i + integers.length - 1)); } }
public boolean containsAll(Collection<?> c) { return selections.containsAll(c); }
@Override public boolean containsAll(@Nonnull Collection<?> c) { return list.containsAll(c); }