Search in sources :

Example 46 with MutablePair

use of org.apache.commons.lang3.tuple.MutablePair in project PneumaticCraft by MineMaarten.

the class TileEntityPneumaticBase method disperseAir.

private void disperseAir(List<Pair<ForgeDirection, IAirHandler>> teList) {
    boolean shouldRepeat = false;
    List<Pair<Integer, Integer>> dispersion = new ArrayList<Pair<Integer, Integer>>();
    do {
        shouldRepeat = false;
        // Add up every volume and air.
        int totalVolume = getVolume();
        int totalAir = currentAir;
        for (Pair<ForgeDirection, IAirHandler> entry : teList) {
            IAirHandler airHandler = entry.getValue();
            totalVolume += airHandler.getVolume();
            totalAir += airHandler.getCurrentAir(entry.getKey().getOpposite());
        }
        // Only go push based, ignore any machines that have a higher pressure than this block.
        Iterator<Pair<ForgeDirection, IAirHandler>> iterator = teList.iterator();
        while (iterator.hasNext()) {
            Pair<ForgeDirection, IAirHandler> entry = iterator.next();
            IAirHandler airHandler = entry.getValue();
            // Calculate the total air the machine is going to get.
            int totalMachineAir = (int) ((long) totalAir * airHandler.getVolume() / totalVolume);
            int airDispersed = totalMachineAir - airHandler.getCurrentAir(entry.getKey().getOpposite());
            if (airDispersed < 0) {
                iterator.remove();
                shouldRepeat = true;
                dispersion.clear();
                break;
            } else {
                dispersion.add(new MutablePair(getMaxDispersion(entry.getKey()), airDispersed));
            }
        }
    } while (shouldRepeat);
    int toBeDivided = 0;
    int receivers = dispersion.size();
    for (Pair<Integer, Integer> disp : dispersion) {
        if (disp.getValue() > disp.getKey()) {
            // Any air that wants to go to a neighbor, but can't (because of regulator module) gives back its air.
            toBeDivided += disp.getValue() - disp.getKey();
            disp.setValue(disp.getKey());
            receivers--;
        }
    }
    while (toBeDivided >= receivers && receivers > 0) {
        // try to give every receiver an equal part of the to be divided air.
        int dividedValue = toBeDivided / receivers;
        for (Pair<Integer, Integer> disp : dispersion) {
            int maxTransfer = disp.getKey() - disp.getValue();
            if (maxTransfer > 0) {
                if (maxTransfer <= dividedValue) {
                    // next step this receiver won't be able to receive any air.
                    receivers--;
                }
                // cap it at the max it can have.
                int transfered = Math.min(dividedValue, maxTransfer);
                disp.setValue(disp.getValue() + transfered);
                toBeDivided -= transfered;
            } else {
                receivers--;
            }
        }
    }
    for (int i = 0; i < teList.size(); i++) {
        IAirHandler neighbor = teList.get(i).getValue();
        int transferedAir = dispersion.get(i).getValue();
        onAirDispersion(transferedAir, teList.get(i).getKey());
        neighbor.addAir(transferedAir, teList.get(i).getKey().getOpposite());
        addAir(-transferedAir, teList.get(i).getKey());
    }
}
Also used : IAirHandler(pneumaticCraft.api.tileentity.IAirHandler) MutablePair(org.apache.commons.lang3.tuple.MutablePair) ArrayList(java.util.ArrayList) ForgeDirection(net.minecraftforge.common.util.ForgeDirection) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair)

Example 47 with MutablePair

use of org.apache.commons.lang3.tuple.MutablePair in project shifu by ShifuML.

the class ShifuCLI method analysisModelFi.

public static int analysisModelFi(String modelPath) {
    File modelFile = new File(modelPath);
    if (!modelFile.exists() || !(modelPath.toUpperCase().endsWith("." + CommonConstants.GBT_ALG_NAME) || modelPath.toUpperCase().endsWith("." + CommonConstants.RF_ALG_NAME))) {
        log.error("The model {} doesn't exist or it isn't GBT/RF model.", modelPath);
        return 1;
    }
    FileInputStream inputStream = null;
    String fiFileName = modelFile.getName() + ".fi";
    try {
        inputStream = new FileInputStream(modelFile);
        BasicML basicML = TreeModel.loadFromStream(inputStream);
        Map<Integer, MutablePair<String, Double>> featureImportances = CommonUtils.computeTreeModelFeatureImportance(Arrays.asList(new BasicML[] { basicML }));
        CommonUtils.writeFeatureImportance(fiFileName, featureImportances);
    } catch (IOException e) {
        log.error("Fail to analysis model FI for {}", modelPath);
        return 1;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return 0;
}
Also used : MutablePair(org.apache.commons.lang3.tuple.MutablePair) BasicML(org.encog.ml.BasicML) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 48 with MutablePair

use of org.apache.commons.lang3.tuple.MutablePair in project azure-iot-sdk-java by Azure.

the class MqttDeviceMethodTest method receiveThrowsIfMethodNameCouldNotBeParsed.

// Tests_SRS_MQTTDEVICEMETHOD_25_029: [**If method name not found or is null then receive shall throw TransportException **]**
@Test(expected = TransportException.class)
public void receiveThrowsIfMethodNameCouldNotBeParsed() throws TransportException {
    // arrange
    String topic = "$iothub/methods/POST/";
    byte[] actualPayload = "TestPayload".getBytes(StandardCharsets.UTF_8);
    testreceivedMessages.add(new MutablePair<>(topic, actualPayload));
    MqttDeviceMethod testMethod = new MqttDeviceMethod("", mockConnectOptions, new HashMap<Integer, Message>(), new ConcurrentLinkedQueue<Pair<String, byte[]>>());
    Deencapsulation.setField(testMethod, "receivedMessages", testreceivedMessages);
    testMethod.start();
    // act
    testMethod.receive();
}
Also used : Message(com.microsoft.azure.sdk.iot.device.Message) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) MqttDeviceMethod(com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceMethod) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Pair(org.apache.commons.lang3.tuple.Pair) Test(org.junit.Test)

Example 49 with MutablePair

use of org.apache.commons.lang3.tuple.MutablePair in project azure-iot-sdk-java by Azure.

the class MqttDeviceMethodTest method receiveReturnsEmptyPayLoadIfNullPayloadParsed.

@Test
public void receiveReturnsEmptyPayLoadIfNullPayloadParsed() throws TransportException {
    // arrange
    String topic = "$iothub/methods/POST/testMethod/?$rid=10";
    byte[] actualPayload = "".getBytes(StandardCharsets.UTF_8);
    testreceivedMessages.add(new MutablePair<>(topic, actualPayload));
    MqttDeviceMethod testMethod = new MqttDeviceMethod("", mockConnectOptions, new HashMap<Integer, Message>(), new ConcurrentLinkedQueue<Pair<String, byte[]>>());
    Deencapsulation.setField(testMethod, "receivedMessages", testreceivedMessages);
    testMethod.start();
    // act
    Message testMessage = testMethod.receive();
    IotHubTransportMessage testDMMessage = (IotHubTransportMessage) testMessage;
    // assert
    assertNotNull(testMessage);
    assertEquals(0, testMessage.getBytes().length);
    assertEquals(testMessage.getMessageType(), MessageType.DEVICE_METHODS);
    assertEquals(testDMMessage.getRequestId(), String.valueOf(10));
    assertEquals("testMethod", testDMMessage.getMethodName());
    assertEquals(testDMMessage.getDeviceOperationType(), DEVICE_OPERATION_METHOD_RECEIVE_REQUEST);
}
Also used : Message(com.microsoft.azure.sdk.iot.device.Message) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) MqttDeviceMethod(com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceMethod) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Pair(org.apache.commons.lang3.tuple.Pair) Test(org.junit.Test)

Example 50 with MutablePair

use of org.apache.commons.lang3.tuple.MutablePair in project azure-iot-sdk-java by Azure.

the class MqttDeviceTwinTest method receiveSetsReqIdOnResTopic.

/*
    **Tests_SRS_MQTTDEVICETWIN_25_040: [If the topic is of type response topic then this method shall parse further to look for request id which if found is set by calling setRequestId]
     */
@Test
public void receiveSetsReqIdOnResTopic() throws TransportException {
    final byte[] actualPayload = "GetTwinResponseDataContainingDesiredAndReportedPropertiesDocument".getBytes(StandardCharsets.UTF_8);
    final String expectedTopic = "$iothub/twin/res/" + "200" + "/?$rid=" + mockReqId;
    IotHubTransportMessage receivedMessage = null;
    try {
        // arrange
        MqttDeviceTwin testTwin = new MqttDeviceTwin("", mockedConnectOptions, new HashMap<Integer, Message>(), new ConcurrentLinkedQueue<Pair<String, byte[]>>());
        Queue<Pair<String, byte[]>> testreceivedMessages = new ConcurrentLinkedQueue<>();
        testreceivedMessages.add(new MutablePair<>(expectedTopic, actualPayload));
        Deencapsulation.setField(testTwin, "receivedMessages", testreceivedMessages);
        Deencapsulation.setField(testTwin, "stateLock", new Object());
        Map<String, DeviceOperations> requestMap = new HashMap<>();
        requestMap.put(mockReqId, DEVICE_OPERATION_TWIN_GET_REQUEST);
        Deencapsulation.setField(testTwin, "requestMap", requestMap);
        // act
        receivedMessage = testTwin.receive();
    } finally {
        // assert
        assertNotNull(receivedMessage);
        assertSame(receivedMessage.getMessageType(), MessageType.DEVICE_TWIN);
        assertSame(receivedMessage.getDeviceOperationType(), DEVICE_OPERATION_TWIN_GET_RESPONSE);
        assertEquals(receivedMessage.getRequestId(), mockReqId);
        assertEquals("200", receivedMessage.getStatus());
        assertNull(receivedMessage.getVersion());
    }
}
Also used : Message(com.microsoft.azure.sdk.iot.device.Message) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) DeviceOperations(com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceOperations) HashMap(java.util.HashMap) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) MqttDeviceTwin(com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceTwin) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Pair(org.apache.commons.lang3.tuple.Pair) Test(org.junit.Test)

Aggregations

MutablePair (org.apache.commons.lang3.tuple.MutablePair)67 Pair (org.apache.commons.lang3.tuple.Pair)33 Test (org.junit.Test)28 Message (com.microsoft.azure.sdk.iot.device.Message)27 IotHubTransportMessage (com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)27 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)23 HashMap (java.util.HashMap)18 MqttDeviceTwin (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceTwin)17 ArrayList (java.util.ArrayList)17 IOException (java.io.IOException)9 DeviceOperations (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceOperations)8 AreaId (bwem.area.typedef.AreaId)7 List (java.util.List)7 Map (java.util.Map)6 MqttDeviceMethod (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceMethod)5 MiniTile (bwem.tile.MiniTile)4 Altitude (bwem.typedef.Altitude)4 ContainerStartRequest (com.datatorrent.stram.StreamingContainerAgent.ContainerStartRequest)4 ContainerRequest (org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest)4 WalkPosition (org.openbw.bwapi4j.WalkPosition)4