text:
package com.linkedin.norbert
package network
package partitioned

import java.net.ConnectException
import java.util
import java.util.concurrent.ExecutionException

import com.linkedin.norbert.cluster._
import com.linkedin.norbert.network.common.{ClusterIoClientComponent, BaseNetworkClientSpecification}
import com.linkedin.norbert.network.partitioned.loadbalancer._

import scala.collection.JavaConversions

class PartitionedNetworkClientSpec extends BaseNetworkClientSpecification {
  val networkClient = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent
      with PartitionedLoadBalancerFactoryComponent[Int] {
    val lb = mock[PartitionedLoadBalancer[Int]]
    val loadbalancer = new PartitionedLoadBalancer[Int] {
      def nextNode(id: Int, capability: Option[Long], permanentCapability: Option[Long]) = lb.nextNode(id, capability, permanentCapability)
      def nodesForOneReplica(id: Int, capability: Option[Long], permanentCapability: Option[Long]) = lb.nodesForOneReplica(id, capability, permanentCapability)
      def nodesForPartitionedId(id: Int, capability: Option[Long], permanentCapability: Option[Long]) = lb.nodesForPartitionedId(id, capability, permanentCapability)
      def nodesForPartitions(id: Int, partitions: Set[Int], capability: Option[Long], permanentCapability: Option[Long]) = lb.nodesForPartitions(id, partitions, capability, permanentCapability)
      override def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = lb.nextNodes(id, capability, persistentCapability)
    }
    val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
    val clusterIoClient = mock[ClusterIoClient]
    val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
  }

//  networkClient.messageRegistry.contains(any[Message]) returns true

  "PartitionedNetworkClient" should {
    "provide common functionality" in { sharedFunctionality }

    "throw ClusterDisconnectedException if the cluster is disconnected when a method is called" in {
      networkClient.start

      networkClient.broadcastMessage(request) must throwA[ClusterDisconnectedException]
      networkClient.sendRequestToNode(request, nodes(1)) must throwA[ClusterDisconnectedException]
      networkClient.sendRequest(1, request) must throwA[ClusterDisconnectedException]
      networkClient.sendRequest(Set(1, 2), request) must throwA[ClusterDisconnectedException]
      networkClient.sendMessage(1, request) must throwA[ClusterDisconnectedException]
      networkClient.sendMessage(Set(1, 2), request) must throwA[ClusterDisconnectedException]
    }

    "throw ClusterShutdownException if the cluster is shut down when a method is called" in {
      networkClient.shutdown

      networkClient.broadcastMessage(request) must throwA[NetworkShutdownException]
      networkClient.sendRequestToNode(request, nodes(1)) must throwA[NetworkShutdownException]
      networkClient.sendRequest(1, request) must throwA[NetworkShutdownException]
      networkClient.sendRequest(Set(1, 2), request) must throwA[NetworkShutdownException]
      networkClient.sendMessage(1, request) must throwA[NetworkShutdownException]
      networkClient.sendMessage(Set(1, 2), request) must throwA[NetworkShutdownException]
    }

//    "throw an InvalidMessageException if an unregistered message is sent" in {
//      clusterClient.nodes returns nodeSet
//      clusterClient.isConnected returns true
////      networkClient.messageRegistry.contains(any[Message]) returns false
//
//      networkClient.start
//
//      networkClient.broadcastMessage(request) must throwA[InvalidMessageException]
//      networkClient.sendRequestToNode(request, nodes(1)) must throwA[InvalidMessageException]
//      networkClient.sendRequest(1, request) must throwA[InvalidMessageException]
//      networkClient.sendRequest(Set(1, 2), request) must throwA[InvalidMessageException]
//    }

    "when sendRequest(id, message) is called" in {
      "send the provided message to the node specified by the load balancer for sendRequest" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns Some(nodes(1))
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(1, request) must notBeNull

        there was one(networkClient.lb).nextNode(1, None, None)
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "send the provided message to the node specified by the load balancer for sendMessage" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns Some(nodes(1))
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(1, request) must notBeNull

        there was one(networkClient.lb).nextNode(1, None, None)
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "send the provided message to the node specified by the load balancer filtering based on capability for sendRequest" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, Some(0x1), Some(0x2)) returns Some(nodes(1))

        networkClient.start
        networkClient.sendRequest(1, request, Some(0x1L), Some(2L)) must notBeNull

        there was one(networkClient.lb).nextNode(1, Some(0x1L), Some(2L))
        there was no(networkClient.lb).nextNode(1, None, None)
      }

      "send the provided message to the node specified by the load balancer filtering based on capability fir sendMessage" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, Some(0x1), Some(0x2)) returns Some(nodes(1))

        networkClient.start
        networkClient.sendMessage(1, request, Some(0x1L), Some(2L)) must notBeNull

        there was one(networkClient.lb).nextNode(1, Some(0x1L), Some(2L))
        there was no(networkClient.lb).nextNode(1, None, None)
      }

      "throw InvalidClusterException if there is no load balancer instance when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(1, request) must throwA[InvalidClusterException]

        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw InvalidClusterException if there is no load balancer instance when sendMessage is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(1, request) must throwA[InvalidClusterException]

        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw NoSuchNodeException if load balancer returns None when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.lb
        networkClient.lb.nextNode(1, None, None) returns None
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(1, request) must throwA[NoNodesAvailableException]

        there was one(networkClient.lb).nextNode(1, None, None)
        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw NoSuchNodeException if load balancer returns None when sendMessage is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.lb
        networkClient.lb.nextNode(1, None, None) returns None
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(1, request) must throwA[NoNodesAvailableException]

        there was one(networkClient.lb).nextNode(1, None, None)
        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }
    }

    "when sendRequest(ids, message) is called" in {
      "send the provided message to the node specified by the load balancer" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns Some(nodes(1))
        networkClient.lb.nextNode(2, None, None) returns Some(nodes(2))
        networkClient.lb.nextNode(3, None, None) returns Some(nodes(1))

        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), request) must notBeNull

        got {
          one(networkClient.lb).nextNode(1, None, None)
          one(networkClient.lb).nextNode(2, None, None)
          one(networkClient.lb).nextNode(3, None, None)
        }
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "send the provided one way message to the node specified by the load balancer" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns Some(nodes(1))
        networkClient.lb.nextNode(2, None, None) returns Some(nodes(2))
        networkClient.lb.nextNode(3, None, None) returns Some(nodes(1))

        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(Set(1, 2, 3), request) must notBeNull

        got {
          one(networkClient.lb).nextNode(1, None, None)
          one(networkClient.lb).nextNode(2, None, None)
          one(networkClient.lb).nextNode(3, None, None)
        }
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "send the provided message to the node specified by the load balancer with capability filter" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, Some(0xffL), Some(2L)) returns Some(nodes(1))
        networkClient.lb.nextNode(2, Some(0xffL), Some(2L)) returns Some(nodes(2))
        networkClient.lb.nextNode(3, Some(0xffL), Some(2L)) returns Some(nodes(1))

        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), request, Some(0xffL), Some(2L)) must notBeNull

        got {
          no(networkClient.lb).nextNode(1, None, None)
          no(networkClient.lb).nextNode(2, None, None)
          no(networkClient.lb).nextNode(3, None, None)
          one(networkClient.lb).nextNode(1, Some(0xffL), Some(2L))
          one(networkClient.lb).nextNode(2, Some(0xffL), Some(2L))
          one(networkClient.lb).nextNode(3, Some(0xffL), Some(2L))
        }
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "send the provided one way message to the node specified by the load balancer with capability filter" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, Some(0xffL), Some(2L)) returns Some(nodes(1))
        networkClient.lb.nextNode(2, Some(0xffL), Some(2L)) returns Some(nodes(2))
        networkClient.lb.nextNode(3, Some(0xffL), Some(2L)) returns Some(nodes(1))

        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(Set(1, 2, 3), request, Some(0xffL), Some(2L)) must notBeNull

        got {
          no(networkClient.lb).nextNode(1, None, None)
          no(networkClient.lb).nextNode(2, None, None)
          no(networkClient.lb).nextNode(3, None, None)
          one(networkClient.lb).nextNode(1, Some(0xffL), Some(2L))
          one(networkClient.lb).nextNode(2, Some(0xffL), Some(2L))
          one(networkClient.lb).nextNode(3, Some(0xffL), Some(2L))
        }
        //      clusterIoClient.sendRequest(node, message, null) was called
      }

      "throw InvalidClusterException if there is no load balancer instance when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), request) must throwA[InvalidClusterException]

        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw InvalidClusterException if there is no load balancer instance when sendMessage is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(Set(1, 2, 3), request) must throwA[InvalidClusterException]

        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw NoSuchNodeException if load balancer returns None when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns None
//      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), request) must throwA[NoNodesAvailableException]

        there was one(networkClient.lb).nextNode(1, None, None)
//      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw NoSuchNodeException if load balancer returns None when sendMessage is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns None
        //      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendMessage(Set(1, 2, 3), request) must throwA[NoNodesAvailableException]

        there was one(networkClient.lb).nextNode(1, None, None)
        //      clusterIoClient.sendRequest(node, message, null) wasnt called
      }
    }

  "when sendRequest(ids, message, messageCustomizer) is called" in {
    "send the provided message to the node specified by the load balancer" in {
      clusterClient.nodes returns nodeSet
      clusterClient.isConnected returns true
      networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
      networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
      List(1, 2, 3).foreach(networkClient.lb.nextNode(_, None, None) returns Some(Node(1, "localhost:31313", true)))

      networkClient.start
      networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _)

      List(1, 2, 3).foreach(there was one(networkClient.lb).nextNode(_, None, None))

      List(1, 2, 3).foreach(networkClient.lb.nextNode(_, Some(0x3L), Some(0L)) returns Some(Node(1, "localhost:31313", true)))
      networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _, Some(0x3L), Some(0L))
      List(1, 2, 3).foreach(there was one(networkClient.lb).nextNode(_,Some(0x3L), Some(0L)))
    }

    "send the provided one way message to the node specified by the load balancer" in {
      clusterClient.nodes returns nodeSet
      clusterClient.isConnected returns true
      networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
      networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
      List(1, 2, 3).foreach(networkClient.lb.nextNode(_, None, None) returns Some(Node(1, "localhost:31313", true)))

      networkClient.start
      networkClient.sendMessage(Set(1, 2, 3), messageCustomizer _)

      List(1, 2, 3).foreach(there was one(networkClient.lb).nextNode(_, None, None))

      List(1, 2, 3).foreach(networkClient.lb.nextNode(_, Some(0x3L), Some(0L)) returns Some(Node(1, "localhost:31313", true)))
      networkClient.sendMessage(Set(1, 2, 3), messageCustomizer _, Some(0x3L), Some(0L))
      List(1, 2, 3).foreach(there was one(networkClient.lb).nextNode(_,Some(0x3L), Some(0L)))
    }

    "call the message customizer" in {
      var callCount = 0
      var nodeMap = Map[Node, Set[Int]]()

      def mc(node: Node, ids: Set[Int]): Ping = {
        callCount += 1
        nodeMap = nodeMap + (node -> ids)
        new Ping
      }

      clusterClient.nodes returns nodeSet
      clusterClient.isConnected returns true
      networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
      networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
      List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))
      List(3, 4).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(1)))

      networkClient.start
      networkClient.sendRequest(Set(1, 2, 3, 4), mc _)

      callCount must be_==(2)
      nodeMap.size must be_==(2)
      nodeMap(nodes(0)) must haveTheSameElementsAs(Array(1, 2))
      nodeMap(nodes(1)) must haveTheSameElementsAs(Array(3, 4))
    }

    "call the message customizer (one way message)" in {
      var callCount = 0
      var nodeMap = Map[Node, Set[Int]]()

      def mc(node: Node, ids: Set[Int]): Ping = {
        callCount += 1
        nodeMap = nodeMap + (node -> ids)
        new Ping
      }

      clusterClient.nodes returns nodeSet
      clusterClient.isConnected returns true
      networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
      networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
      List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))
      List(3, 4).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(1)))

      networkClient.start
      networkClient.sendMessage(Set(1, 2, 3, 4), mc _)

      callCount must be_==(2)
      nodeMap.size must be_==(2)
      nodeMap(nodes(0)) must haveTheSameElementsAs(Array(1, 2))
      nodeMap(nodes(1)) must haveTheSameElementsAs(Array(3, 4))
    }

    "treats an exception from the message customizer as a failed response" in {
      def mc(node: Node, ids: Set[Int]): Ping = {
        throw new Exception
      }

      clusterClient.nodes returns nodeSet
      clusterClient.isConnected returns true
      networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
      networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
      List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))

      networkClient.start
      val ri = networkClient.sendRequest(Set(1, 2), mc _)
      ri.hasNext must beTrue
      ri.next must throwA[ExecutionException]
    }

      "throw InvalidClusterException if there is no load balancer instance when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")
//      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _)  must throwA[InvalidClusterException]
        networkClient.sendMessage(Set(1, 2, 3), messageCustomizer _)  must throwA[InvalidClusterException]

//      clusterIoClient.sendRequest(node, message, null) wasnt called
      }

      "throw NoSuchNodeException if load balancer returns None when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns None
//      doNothing.when(clusterIoClient).sendRequest(node, message, null)

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _) must throwA[NoNodesAvailableException]
        networkClient.sendMessage(Set(1, 2, 3), messageCustomizer _) must throwA[NoNodesAvailableException]

        there were two(networkClient.lb).nextNode(1, None, None)

        // Test cases for fanout calls.
        networkClient.sendRequest(Set(1, 2, 3), 0, messageCustomizer _) must throwA[NoNodesAvailableException]
        networkClient.sendRequest(Set(1, 2, 3), 1, messageCustomizer _) must throwA[NoNodesAvailableException]
//      clusterIoClient.sendRequest(node, message, null) wasnt called
      }
    }

    "when sendRequest(ids, message, messageCustomizer, maxRetry) is called" in {

      val MAX_RETRY = 3

      "send the provided message to the node specified by the load balancer" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1, 2, 3).foreach(networkClient.lb.nextNode(_, None, None) returns Some(Node(1, "localhost:31313", true)))

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _, MAX_RETRY)

        List(1, 2, 3).foreach(there was one(networkClient.lb).nextNode(_, None, None))
      }

      "call the message customizer" in {
        var callCount = 0
        var nodeMap = Map[Node, Set[Int]]()

        def mc(node: Node, ids: Set[Int]): Ping = {
          callCount += 1
          nodeMap = nodeMap + (node -> ids)
          new Ping
        }

        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))
        List(3, 4).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(1)))

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3, 4), mc _, MAX_RETRY)

        callCount must be_==(2)
        nodeMap.size must be_==(2)
        nodeMap(nodes(0)) must haveTheSameElementsAs(Array(1, 2))
        nodeMap(nodes(1)) must haveTheSameElementsAs(Array(3, 4))
      }

      "treats an exception from the message customizer as a failed response" in {
        def mc(node: Node, ids: Set[Int]): Ping = {
          throw new Exception
        }

        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))

        networkClient.start
        val ri = networkClient.sendRequest(Set(1, 2), mc _, MAX_RETRY)
        ri.hasNext must beTrue
        ri.next must throwA[ExecutionException]

        networkClient.sendRequest(Set(1, 2), 0, mc _, MAX_RETRY).hasNext must beTrue
        networkClient.sendRequest(Set(1, 2), 0, mc _, MAX_RETRY).next must throwA[ExecutionException]

        networkClient.sendRequest(Set(1, 2), 1, mc _, MAX_RETRY).hasNext must beTrue
        networkClient.sendRequest(Set(1, 2), 1, mc _, MAX_RETRY).next must throwA[ExecutionException]
      }

      "throw InvalidClusterException if there is no load balancer instance when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _, MAX_RETRY)  must throwA[InvalidClusterException]

        networkClient.sendRequest(Set(1, 2, 3), 0, messageCustomizer _, MAX_RETRY)  must throwA[InvalidClusterException]
        networkClient.sendRequest(Set(1, 2, 3), 1, messageCustomizer _, MAX_RETRY)  must throwA[InvalidClusterException]
      }

      "throw NoSuchNodeException if load balancer returns None when sendRequest is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns None

        networkClient.start
        networkClient.sendRequest(Set(1, 2, 3), messageCustomizer _, MAX_RETRY) must throwA[NoNodesAvailableException]

        there was one(networkClient.lb).nextNode(1, None, None)

        networkClient.sendRequest(Set(1, 2, 3), 0, messageCustomizer _) must throwA[NoNodesAvailableException]
        networkClient.sendRequest(Set(1, 2, 3), 1, messageCustomizer _) must throwA[NoNodesAvailableException]
      }
    }

    "when sendRequestToReplicas(id, message) is called" in {
      "send the provided message to every replica specified by the load balancer" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1,2,3).foreach(networkClient.lb.nodesForPartitionedId(_, None, None) returns nodeSet)

        networkClient.start
        networkClient.sendRequestToReplicas(2, request)
        got {
          one(networkClient.lb).nodesForPartitionedId(2, None, None)
        }
      }

      "send the provided message to every replica specified by the load balancer filtering capability" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1,2,3).foreach(networkClient.lb.nodesForPartitionedId(_, Some(0xfL), Some(2L)) returns nodeSet)

        networkClient.start
        networkClient.sendRequestToReplicas(2, request, 0, Some(0xfL), Some(2L))
        got {
              one(networkClient.lb).nodesForPartitionedId(2, Some(0xfL), Some(2L))
            }
      }

      "throw InvalidClusterException if there is no loadbalancer instance when sendRequestToReplicas is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) throws new InvalidClusterException("")

        networkClient.start
        networkClient.sendRequestToReplicas(3, request) must throwA[InvalidClusterException]
      }

      "throw NoSuchNodeException if load balancer returns None when sendRequests is called" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nodesForPartitionedId(1, None, None) returns (Set.empty[Node])

        networkClient.start
        networkClient.sendRequestToReplicas(1, request) must throwA[NoNodesAvailableException]
        there was one(networkClient.lb).nodesForPartitionedId(1, None, None)
      }

    }

    "retryCallback should propagate server exception to underlying when" in {

      val MAX_RETRY = 3
      var either: Either[Throwable, Ping] = null
      val callback = (e: Either[Throwable, Ping]) => either = e

      "exception does not provide RequestAccess" in {
        networkClient.retryCallback[Ping, Ping](callback, 0, None, None)(Left(new Exception)) // fallback to underlying
        either must notBeNull
        either.isLeft must beTrue
      }

      "request.retryAttempt >= maxRetry" in {
        val req: Request[Ping, Ping] = spy(PartitionedRequest[Int, Ping, Ping](null, null, null, null, null, null, Some(callback), MAX_RETRY))
        val ra: Exception with RequestAccess[Request[Ping, Ping]] = new Exception with RequestAccess[Request[Ping, Ping]] {
          def request = req
        }
        networkClient.retryCallback[Ping, Ping](callback, MAX_RETRY, None, None)(Left(ra))
        either must notBeNull
        either.isLeft must beTrue
        either.left.get mustEq ra
      }

      "cannot locate next available node" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns None
        networkClient.start

        networkClient.retryCallback[Ping, Ping](callback, MAX_RETRY, None, None)(Left(new RemoteException("FooClass", "ServerError")))
        either must notBeNull
        either.isLeft must beTrue
        either.left.get must haveClass[RemoteException]
      }

      "next node is same as failing node" in {
        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        networkClient.lb.nextNode(1, None, None) returns Some(nodes(1)) // node(1) -> node(1) -> node(1)

        networkClient.start

        var req: Request[Ping, Ping] = spy(PartitionedRequest[Int, Ping, Ping](null, nodes(1), null, null, null, null, Some(callback), 0))
        val ra: Exception with RequestAccess[Request[Ping, Ping]] = new Exception with RequestAccess[Request[Ping, Ping]] {
          def request = req
        }

        networkClient.retryCallback[Ping, Ping](callback, MAX_RETRY, None, None)(Left(ra))
        either must notBeNull
        either.isLeft must beTrue
        either.left.get mustEq ra
      }

      "sendMessage: MAX_RETRY reached" in {
        val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
          val lb = new PartitionedLoadBalancer[Int] {
            var iter = PartitionedNetworkClientSpec.this.nodes.iterator
            def nextNode(id: Int, c: Option[Long] = None, pc : Option[Long] = None) = {
              if (!iter.hasNext ) iter = PartitionedNetworkClientSpec.this.nodes.iterator
              Some(iter.next)
            }
            def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
            def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
            def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
            def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null
          }
          val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
          val clusterIoClient = new ClusterIoClient {
            var invocationCount: Int = 0
            def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
              invocationCount += 1
              requestCtx.onFailure(new Exception with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                def request = requestCtx
              })
            }
            def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
            def shutdown {}
          }
          val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
        }
        nc2.clusterClient.nodes returns nodeSet
        nc2.clusterClient.isConnected returns true
        nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
        nc2.start
        val resIter = nc2.sendRequest(Set(1,2,3), messageCustomizer _, MAX_RETRY)
        nc2.clusterIoClient.invocationCount mustEqual (MAX_RETRY * 4)
        while (resIter.hasNext) {
          resIter.next must throwAnException[Exception]
        }
        val resIter2 = nc2.sendRequest(Set(1,2,3), 1, messageCustomizer _, MAX_RETRY)
        nc2.clusterIoClient.invocationCount mustEqual (MAX_RETRY * 8)
        while (resIter2.hasNext) {
          resIter2.next must throwAnException[Exception]
        }
      }

    }

    "sendMessage should automatically handle partial failures" in {
      val MAX_RETRY = 3
      val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          val nodeIS = PartitionedNetworkClientSpec.this.nodes.toIndexedSeq
          var idx = 0
          def nextNode(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = {
            idx = (idx + 1) % nodeIS.size
            Some(nodeIS(idx))
          }
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None)= null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null
        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var succ: Boolean = false
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            if (!succ) {
              succ = true
              requestCtx.onFailure(new RemoteException("FooBar", "ServerError") with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                def request = requestCtx
              })
            } else {
              succ = false
              requestCtx.onSuccess(requestCtx.outputSerializer.requestToBytes(requestCtx.message))
            }
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start
      val resIter = nc2.sendRequest[Ping, Ping](Set(1,2), messageCustomizer _, MAX_RETRY)
      while (resIter.hasNext) {
        resIter.next mustNot throwAnException
      }
    }

    "sendMessage should automatically handle partial failures and adjust response size dynamically" in {
      val MAX_RETRY = 3
      val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          val nodeIS = PartitionedNetworkClientSpec.this.nodes.toIndexedSeq
          var count = 0
          def nextNode(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = {
            var ret: Node = null
            if (count < 2)
              ret = nodes(0)
            else
              ret = nodes(id + 1)
            count += 1
            Some(ret)
          }
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null

        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var failOnce: Boolean = true
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            if (failOnce) {
              failOnce = false
              requestCtx.onFailure(new RemoteException("FooBar", "ServerError") with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                def request = requestCtx
              })
            } else {
              requestCtx.onSuccess(requestCtx.outputSerializer.requestToBytes(requestCtx.message))
            }
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start
      val resIter = nc2.sendRequest[Ping, Ping](Set(0,1), messageCustomizer _, MAX_RETRY)
      var num = 0
      while (resIter.hasNext) {
        num += 1
        resIter.next mustNot throwAnException
      }
      num mustEq 2

      val resIter2 = nc2.sendRequest[Ping, Ping](Set(0,1), messageCustomizer _, MAX_RETRY)
      num = 0
      while (resIter2.hasNext) {
        num += 1
        resIter2.next mustNot throwAnException
      }
      num mustEq 2
    }

    "calculateNodesFromIds should properly exclude failing node" in {
      val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          val iter = PartitionedNetworkClientSpec.this.nodes.iterator
          def nextNode(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = Some(iter.next)
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null

        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var invocationCount: Int = 0
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            invocationCount += 1
            requestCtx.onFailure(new Exception with RequestAccess[Request[RequestMsg, ResponseMsg]] {
              def request = requestCtx
            })
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start

      val failingNode = nodes(0)
      val failingNodes = Set(failingNode)
      var nodes2Ids = nc2.calculateNodesFromIds(Set(1), failingNodes, 3, None, None)
      nodes2Ids must notBeNull
      nodes2Ids.keys must notHave(failingNodes)
    }

    "calculateNodesFromIds should properly exclude failing nodes in excluded set" in {
      val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          val iter = PartitionedNetworkClientSpec.this.nodes.iterator
          def nextNode(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = Some(iter.next)
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null
        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var invocationCount: Int = 0
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            invocationCount += 1
            requestCtx.onFailure(new Exception with RequestAccess[Request[RequestMsg, ResponseMsg]] {
              def request = requestCtx
            })
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start

      val failingNodes = Set(nodes(0), nodes(1))
      var nodes2Ids = nc2.calculateNodesFromIds(Set(1), failingNodes, 3, None, None)
      nodes2Ids must notBeNull
      nodes2Ids.keys must notHave(failingNodes)
    }

    "calculateNodesFromIds should throw NoNodesAvailableException if non-failing nodes not found" in {
      val nc2 = new PartitionedNetworkClient[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          val iter = PartitionedNetworkClientSpec.this.nodes.iterator
          def nextNode(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = if (iter.hasNext) Some(iter.next) else None
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = null

        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var invocationCount: Int = 0
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            invocationCount += 1
            requestCtx.onFailure(new Exception with RequestAccess[Request[RequestMsg, ResponseMsg]] {
              def request = requestCtx
            })
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start

      val failingNodes = Set(nodes(0), nodes(1), nodes(2))
      nc2.calculateNodesFromIds(Set(1), failingNodes, 3, None, None) must throwA[NoNodesAvailableException]
    }

    "when sendRequest is called with a response aggregator" in {
      "it calls the response aggregator" in {
        var callCount = 0
        def ag(ri: ResponseIterator[Ping]) = {
          callCount += 1
          123454321
        }

        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))

        networkClient.start
        networkClient.sendRequest(Set(1, 2), (node: Node, ids: Set[Int]) => request, ag _) must be_==(123454321)

        callCount must be_==(1)

        networkClient.sendRequest(Set(1, 2), 0, (node: Node, ids: Set[Int]) => request, ag _) must be_==(123454321)

        callCount must be_==(2)

        networkClient.sendRequest(Set(1, 2), 1, (node: Node, ids: Set[Int]) => request, ag _) must be_==(123454321)

        callCount must be_==(3)
      }

      "it rethrows exceptions thrown by the response aggregator" in {
        def ag(ri: ResponseIterator[Ping]): Int = {
          throw new Exception
        }

        clusterClient.nodes returns nodeSet
        clusterClient.isConnected returns true
        networkClient.clusterIoClient.nodesChanged(nodeSet) returns endpoints
        networkClient.loadBalancerFactory.newLoadBalancer(endpoints) returns networkClient.loadbalancer
        List(1, 2).foreach(networkClient.lb.nextNode(_, None, None) returns Some(nodes(0)))

        networkClient.start
        networkClient.sendRequest(Set(1, 2), (node: Node, ids: Set[Int]) => request, ag _) must throwA[Exception]

        networkClient.sendRequest(Set(1, 2), 0, (node: Node, ids: Set[Int]) => request, ag _) must throwA[Exception]
        networkClient.sendRequest(Set(1, 2), 1, (node: Node, ids: Set[Int]) => request, ag _) must throwA[Exception]
      }

      "Automatically fix partitioned requests " in {
        val testData = Map(
          Node(id = 0, url = "", available = true, partitionIds = Set(1, 2, 3)) -> Set(1, 2),
          Node(id = 1, url = "", available = true, partitionIds = Set(1, 2, 3)) -> Set(2, 3))

        val corrected = networkClient.ensureReplicaConsistency(testData)

        // Search for duplicates
        corrected.size must be_==(2)
        testData.values.map(_.toSeq).flatten.size must be_==(4)
        corrected.values.map(_.toSeq).flatten.size must be_==(3)
      }
    }
  }

  "PartitionedNetworkClientFailOver" should {
     "fail-over to next node" in {
       val nc2 = new PartitionedNetworkClientFailOver[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
         val lb = new PartitionedLoadBalancer[Int] {
           var iter = PartitionedNetworkClientSpec.this.nodes.iterator
           def nextNode(id: Int, c: Option[Long] = None, pc : Option[Long] = None) = {
             if (!iter.hasNext ) iter = PartitionedNetworkClientSpec.this.nodes.iterator
             Some(iter.next)
           }
           def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
           def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
           def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
           def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = {
             val result : util.LinkedHashSet[Node] = new util.LinkedHashSet()
             result.addAll(JavaConversions.asJavaCollection( PartitionedNetworkClientSpec.this.nodes))
             result
           }
         }
         val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
         val clusterIoClient = new ClusterIoClient {
           var invocationMap = Map(1 -> 0, 2 -> 0, 3 -> 0)
           def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
             val oldVal = invocationMap(node.id)
             invocationMap = invocationMap + (node.id -> (oldVal+1))
             if (node.id == 1) {
               requestCtx.onFailure(new ConnectException with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                 def request = requestCtx
               })
             } else {
               requestCtx.onSuccess(requestCtx.outputSerializer.requestToBytes(requestCtx.message))
             }
           }
           def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
           def shutdown {}
         }
         val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
       }
       nc2.clusterClient.nodes returns nodeSet
       nc2.clusterClient.isConnected returns true
       nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
       nc2.start

       // check pre-test assumptions
       nc2.clusterIoClient.invocationMap(1) must be_==(0)
       nc2.clusterIoClient.invocationMap(2) must be_==(0)
       nc2.clusterIoClient.invocationMap(3) must be_==(0)

       nc2.sendRequest[Ping, Ping](0, request)

       // check post-test values
       nc2.clusterIoClient.invocationMap(1) must be_==(1)
       nc2.clusterIoClient.invocationMap(2) must be_==(1)
       nc2.clusterIoClient.invocationMap(3) must be_==(0)

     }

    "fail when the fail over node fails" in {
      val nc2 = new PartitionedNetworkClientFailOver[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        val lb = new PartitionedLoadBalancer[Int] {
          var iter = PartitionedNetworkClientSpec.this.nodes.iterator
          def nextNode(id: Int, c: Option[Long] = None, pc : Option[Long] = None) = {
            if (!iter.hasNext ) iter = PartitionedNetworkClientSpec.this.nodes.iterator
            Some(iter.next)
          }
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = {
            val result : util.LinkedHashSet[Node] = new util.LinkedHashSet()
            result.addAll(JavaConversions.asJavaCollection( PartitionedNetworkClientSpec.this.nodes))
            result
          }
        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var invocationMap = Map(1 -> 0, 2 -> 0, 3 -> 0)
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            val oldVal = invocationMap(node.id)
            invocationMap = invocationMap + (node.id -> (oldVal+1))
            if (node.id == 1 || node.id == 2) {
              requestCtx.onFailure(new ConnectException with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                def request = requestCtx
              })
            } else {
              requestCtx.onSuccess(requestCtx.outputSerializer.requestToBytes(requestCtx.message))
            }
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start

      // check pre-test assumptions
      nc2.clusterIoClient.invocationMap(1) must be_==(0)
      nc2.clusterIoClient.invocationMap(2) must be_==(0)
      nc2.clusterIoClient.invocationMap(3) must be_==(0)

      val future = nc2.sendRequest[Ping, Ping](0, request)
      future.get must throwA[Exception]

      // check post-test values
      nc2.clusterIoClient.invocationMap(1) must be_==(1)
      nc2.clusterIoClient.invocationMap(2) must be_==(1)
      nc2.clusterIoClient.invocationMap(3) must be_==(0)

    }

    "fail-over must propagate to multiple nodes, if fail over nodes fail as well" in {
      val nc2 = new PartitionedNetworkClientFailOver[Int] with ClusterClientComponent with ClusterIoClientComponent with PartitionedLoadBalancerFactoryComponent[Int] {
        override val failOverAttempts = 1000;
        val lb = new PartitionedLoadBalancer[Int] {
          var iter = PartitionedNetworkClientSpec.this.nodes.iterator
          def nextNode(id: Int, c: Option[Long] = None, pc : Option[Long] = None) = {
            if (!iter.hasNext ) iter = PartitionedNetworkClientSpec.this.nodes.iterator
            Some(iter.next)
          }
          def nodesForOneReplica(id: Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitionedId(id:Int, c: Option[Long] = None, pc: Option[Long] = None) = null
          def nodesForPartitions(id: Int, partitions: Set[Int], c: Option[Long] = None, pc: Option[Long] = None) = null
          def nextNodes(id: Int, capability: Option[Long], persistentCapability: Option[Long]): util.LinkedHashSet[Node] = {
            val result : util.LinkedHashSet[Node] = new util.LinkedHashSet()
            result.addAll(JavaConversions.asJavaCollection( PartitionedNetworkClientSpec.this.nodes))
            result
          }
        }
        val loadBalancerFactory = mock[PartitionedLoadBalancerFactory[Int]]
        val clusterIoClient = new ClusterIoClient {
          var invocationMap = Map(1 -> 0, 2 -> 0, 3 -> 0)
          def sendMessage[RequestMsg, ResponseMsg](node: Node, requestCtx: Request[RequestMsg, ResponseMsg]) {
            val oldVal = invocationMap(node.id)
            invocationMap = invocationMap + (node.id -> (oldVal+1))
            if (node.id == 1 || node.id == 2) {
              requestCtx.onFailure(new ConnectException with RequestAccess[Request[RequestMsg, ResponseMsg]] {
                def request = requestCtx
              })
            } else {
              requestCtx.onSuccess(requestCtx.outputSerializer.requestToBytes(requestCtx.message))
            }
          }
          def nodesChanged(nodes: Set[Node]) = {PartitionedNetworkClientSpec.this.endpoints}
          def shutdown {}
        }
        val clusterClient = PartitionedNetworkClientSpec.this.clusterClient
      }
      nc2.clusterClient.nodes returns nodeSet
      nc2.clusterClient.isConnected returns true
      nc2.loadBalancerFactory.newLoadBalancer(endpoints) returns nc2.lb
      nc2.start

      // check pre-test assumptions
      nc2.clusterIoClient.invocationMap(1) must be_==(0)
      nc2.clusterIoClient.invocationMap(2) must be_==(0)
      nc2.clusterIoClient.invocationMap(3) must be_==(0)

      nc2.sendRequest[Ping, Ping](0, request)

      // check post-test values
      nc2.clusterIoClient.invocationMap(1) must be_==(1)
      nc2.clusterIoClient.invocationMap(2) must be_==(1)
      nc2.clusterIoClient.invocationMap(3) must be_==(1)
    }
  }
  def messageCustomizer(node: Node, ids: Set[Int]): Ping = new Ping
}


text:
module.exports = {
  apiKey: null,
  endpoint: 'https://notify.bugsnag.com/js',
  projectRoot: null,
  context: null,
  user: {},
  metaData: {},
  releaseStage: 'production',
  appVersion: null,
  severity: 'error',
};

redpajama_set_name: RedPajamaGithub


text:
import json
import threading
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, Dict, Iterable, Iterator, List, Optional

from asgiref.sync import async_to_sync
from mypy_extensions import TypedDict

from .cache import element_cache, get_element_id
from .stream import stream
from .timing import Timing
from .utils import get_model_from_collection_string

class AutoupdateElementBase(TypedDict):
    id: int
    collection_string: str

class AutoupdateElement(AutoupdateElementBase, total=False):
    """
    Data container to handle one root rest element for the autoupdate, history
    and caching process.

    The fields `id` and `collection_string` are required to identify the element. All
    other fields are optional:

    full_data: If a value is given (dict or None), it won't be loaded from the DB.
    If otherwise no value is given, the AutoupdateBundle will try to resolve the object
    from the DB and serialize it into the full_data.

    information and user_id: These fields are for the history indicating what and who
    made changes.

    disable_history: If this is True, the element (and the containing full_data) won't
    be saved into the history. Information and user_id is then irrelevant.
    """

    information: List[str]
    user_id: Optional[int]
    disable_history: bool
    full_data: Optional[Dict[str, Any]]

class AutoupdateBundle:
    """
    Collects changed elements via inform*_data. After the collecting-step is finished,
    the bundle releases all changes to the history and element cache via `.done()`.
    """

    def __init__(self) -> None:
        self.autoupdate_elements: Dict[str, Dict[int, AutoupdateElement]] = defaultdict(
            dict
        )
        self._disable_history = False

    def add(self, elements: Iterable[AutoupdateElement]) -> None:
        """Adds the elements to the bundle"""
        for element in elements:
            self.autoupdate_elements[element["collection_string"]][
                element["id"]
            ] = element

    def disable_history(self) -> None:
        self._disable_history = True

    def done(self) -> Optional[int]:
        """
        Finishes the bundle by resolving all missing data and passing it to
        the history and element cache.

        Returns the change id, if there are autoupdate elements. Otherwise none.
        """
        if not self.autoupdate_elements:
            return None

        for collection, elements in self.autoupdate_elements.items():
            # Get all ids, that do not have a full_data key
            # (element["full_data"]=None will not be resolved again!)
            ids = [
                element["id"]
                for element in elements.values()
                if "full_data" not in element
            ]
            if ids:
                # Get all missing models. If e.g. an id could not be found it
                # means, it was deleted. Since there is not full_data entry
                # for the element, the data will be interpreted as None, which
                # is correct for deleted elements.
                model_class = get_model_from_collection_string(collection)
                for full_data in model_class.get_elements(ids):
                    elements[full_data["id"]]["full_data"] = full_data

        # Save histroy here using sync code.
        if not self._disable_history:
            save_history(self.element_iterator)

        # Update cache and send autoupdate using async code.
        change_id = async_to_sync(self.dispatch_autoupdate)()

        return change_id

    @property
    def element_iterator(self) -> Iterable[AutoupdateElement]:
        """Iterator for all elements in this bundle"""
        for elements in self.autoupdate_elements.values():
            yield from elements.values()

    async def get_data_for_cache(self) -> Dict[str, Optional[Dict[str, Any]]]:
        """
        Async helper function to update the cache.

        Returns the change_id
        """
        cache_elements: Dict[str, Optional[Dict[str, Any]]] = {}
        for element in self.element_iterator:
            element_id = get_element_id(element["collection_string"], element["id"])
            cache_elements[element_id] = element.get("full_data")
        return cache_elements

    async def dispatch_autoupdate(self) -> int:
        """
        Async helper function to update cache and send autoupdate.

        Return the change_id
        """
        # Update cache
        cache_elements = await self.get_data_for_cache()
        change_id = await element_cache.change_elements(cache_elements)

        # Send autoupdate
        autoupdate_payload = {"elements": cache_elements, "change_id": change_id}
        await stream.send("autoupdate", autoupdate_payload)

        return change_id

@contextmanager
def autoupdate_bundle() -> Iterator[AutoupdateBundle]:
    bundle = _autoupdate_bundle.get(threading.get_ident())
    autodone = False
    if bundle is None:
        bundle = AutoupdateBundle()
        autodone = True

    yield bundle

    if autodone:
        bundle.done()

"""
Global container for autoupdate bundles
"""
_autoupdate_bundle: Dict[int, AutoupdateBundle] = {}

class AutoupdateBundleMiddleware:
    """
    Middleware to handle autoupdate bundling.
    """

    def __init__(self, get_response: Any) -> None:
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request: Any) -> Any:
        thread_id = threading.get_ident()
        _autoupdate_bundle[thread_id] = AutoupdateBundle()

        timing = Timing("request")

        response = self.get_response(request)

        timing()

        status_ok = response.status_code >= 200 and response.status_code < 300
        status_redirect = response.status_code >= 300 and response.status_code < 400

        # rewrite the response by adding the autoupdate on any success-case (2xx status)
        bundle: AutoupdateBundle = _autoupdate_bundle.pop(thread_id)
        if status_ok or status_redirect:
            change_id = bundle.done()

            # inject the change id, if there was an autoupdate and the response status is
            # ok (and not redirect; redirects do not have a useful content)
            if change_id is not None and status_ok:
                # Inject the autoupdate in the response.
                # The complete response body will be overwritten!
                content = {"change_id": change_id, "data": response.data}
                # Note: autoupdate may be none on skipped ones (which should not happen
                # since the user has made the request....)
                response.content = json.dumps(content)

        timing(True)
        return response

def save_history(elements: Iterable[AutoupdateElement]) -> Iterable:
    """
    Thin wrapper around the call of history saving manager method.

    This is separated to patch it during tests.
    """
    from ..core.models import History

    return History.objects.add_elements(elements)


text:
title:  Vor Faders planer for os
date:  10/08/2022
---

Alle ønsker at have håb. Men hvor kan vi finde det? Nogle mennesker finder håb i en vens smil. Andre finder håb i økonomisk sikkerhed eller et stabilt ægteskab. Hvor leder du normalt efter håb og mod?

Salmisten udtrykker de landflygtiges følelser: "Ved Babylons floder sad vi og græd, når vi tænkte på Zion" (Sl 137,1).

I Jeremias' Bog skriver profeten til folk, som havde mistet alt håb i deres landflygtighed. Men selv om de var sønderknuste, giver han dem begrundelser for ikke at opgive håbet.

`Læs Jer 29,1-10. Hvilke begrundelser for håb finder vi i disse vers?`

For det første siger Gud til sit folk, at de ikke må opgive håbet, for deres situation er ikke et resultat af tilfældigheder. Gud var klar over, at det ville ske. Han siger selv: "Jeg har ført [Juda] bort fra Jerusalem til Babylon" (Jer 29,4). Selv om de føler sig omringet af ondskab, har Gud aldrig sluppet Juda ud af sine hænder.

For det andet siger Gud til sit folk, at de ikke må opgive håbet, for han kan være med dem også i deres nuværende vanskeligheder. "Stræb efter lykke og fremgang for den by, jeg førte jer bort til, og bed til Herren for den; går det den godt, går det også jer godt" (Jer 29,7).

For det tredje siger Gud til sit folk, at de ikke må opgive håbet, for han skal gøre ende på deres landflygtighed på et bestemt tidspunkt: "Dette siger Herren: Først når der er gået halvfjerds år i Babylon, vil jeg drage omsorg for jer, og jeg vil opfylde det gode løfte, jeg gav jer, og bringe jer tilbage til dette sted" (Jer 29,10).

Efter at Gud har forklaret, hvordan han havde kontrol både med deres fortid og deres nuværende situation, og at han vil have kontrol med deres fremtid, udtrykker han smukt sin kærlige omsorg for sit folk (se Jer 29,11-14).

`Til eftertanke. Læs Jer 29,11-14 og indsæt dit eget navn hver gang der står "jer/I" i teksten, som om Gud giver disse løfter til dig personligt. Gør brug af disse løfter i dit eget liv, uanset hvad dine vanskeligheder måtte være.`


text:
using System;
using System.Xml.Linq;
using Intacct.Infrastructure;

namespace Intacct.Entities
{
	public class IntacctLineItem : IntacctObject
	{
	    public IntacctLineItem(XElement data)
	    {
	        this.SetPropertyValue(x => AccountNumber, data);
	        this.SetPropertyValue(x => AccountLabel, data, true);
	        this.SetPropertyValue(x => Amount, data);
	        this.SetPropertyValue(x => Memo, data);
	        this.SetPropertyValue(x => LocationId, data);
	        this.SetPropertyValue(x => DepartmentId, data);
	    }

        [IntacctName("glaccountno")]
		public int AccountNumber { get; private set; }
        [IntacctName("accountlabel")]
		public string AccountLabel { get; private set; }

		public decimal Amount { get; set; }

		public string Memo { get; set; }
        public int LocationId { get; set; }
        public int DepartmentId { get; set; }

		public static IntacctLineItem CreateWithAccountNumber(int accountNumber, decimal amount)
		{
			return new IntacctLineItem(amount) { AccountNumber = accountNumber };
		}

		public static IntacctLineItem CreateWithAccountLabel(string accountLabel, decimal amount)
		{
			return new IntacctLineItem(amount) { AccountLabel = accountLabel };
		}

		private IntacctLineItem(decimal amount)
		{
			Amount = amount;
		}

		internal override XObject[] ToXmlElements()
		{
			return new XObject[]
				       {
					       GetAccountXmlElement(),
					       new XElement("amount", Amount),
						   new XElement("memo", Memo ?? ""),
                           new XElement("locationid", LocationId),
                           new XElement("departmentid", DepartmentId)
				       };
		}

		private XElement GetAccountXmlElement()
		{
			if (!string.IsNullOrWhiteSpace(AccountNumber.ToString())) return new XElement("glaccountno", AccountNumber);
			if (!string.IsNullOrWhiteSpace(AccountLabel)) return new XElement("accountlabel", AccountLabel);

			throw new Exception("Unable to generate line item XML because neither account number or label are set.");
		}
	}
}


text:
    <a href="<?php echo site_url('/home') ?>" class="logo">

        ALT

        AdminLTE

            Toggle navigation

                        <img src="<?php echo base_url()?>public/dist/img/user2-160x160.jpg" class="user-image" alt="User Image" />
                        Haezal Musa

                            <img src="<?php echo base_url()?>public/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image" />

                                Haezal Musa - Web Developer
                                Member since Sept. 2019

                                <a href="<?php echo site_url('user/profile') ?>" class="btn btn-default btn-flat">Profile

                                <a href="<?php echo site_url('auth/logout') ?>" class="btn btn-default btn-flat">Sign out


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

namespace OpenLiveWriter.PostEditor.JumpList
{
    /// <summary>
    /// Interface for jump list items
    /// </summary>
    public interface IJumpListItem
    {
        /// <summary>
        /// Gets or sets this item's path
        /// </summary>
        string Path { get; set; }
    }
}


text:
namespace {

constexpr uint32_t kPageSize = 4096;

class ReadCapacity10Test : public ::testing::Test {
 protected:
  scsi::ReadCapacity10Command read_capacity_10_cmd_;
  nvme::GenericQueueEntryCmd identify_cmd_;
  translator::NvmeCmdWrapper nvme_wrapper_;
  translator::Span<const uint8_t> scsi_cmd_;
  nvme::IdentifyNamespace identify_ns_;

  uint8_t buffer_[200];

  // Per-test-suite set-up.
  // Called before the first test in this test suite.
  static void SetUpTestSuite() {
    auto alloc_callback = [](uint32_t page_size, uint16_t count) -> uint64_t {
      // TODO: fix count == 0
      // EXPECT_EQ(1, count);
      return 1337;
    };
    void (*dealloc_callback)(uint64_t, uint16_t) = nullptr;
    translator::SetAllocPageCallbacks(alloc_callback, dealloc_callback);
  }

  // You can define per-test set-up logic as usual.
  void SetUp() override {
    identify_ns_ = {};
    SetNamespace(&identify_ns_);

    read_capacity_10_cmd_ = {};
    SetCommand();
    nvme_wrapper_.cmd = identify_cmd_;
    memset(buffer_, 0, sizeof(buffer_));
  }

  void SetCommand() {
    const uint8_t* cmd_ptr =
        reinterpret_cast<const uint8_t*>(&read_capacity_10_cmd_);
    scsi_cmd_ = translator::Span<const uint8_t>(
        cmd_ptr, sizeof(scsi::ReadCapacity10Command));
  }

  void SetNamespace(nvme::IdentifyNamespace* identify_ns_) {
    identify_cmd_.dptr.prp.prp1 = reinterpret_cast<uint64_t>(identify_ns_);
  }
};

TEST_F(ReadCapacity10Test, ToNvmeSuccess) {
  translator::Allocation allocation{};
  uint32_t alloc_len = 0;
  EXPECT_EQ(translator::ReadCapacity10ToNvme(
                scsi_cmd_, nvme_wrapper_, kPageSize, 1, allocation, alloc_len),
            translator::StatusCode::kSuccess);
  EXPECT_EQ(nvme_wrapper_.is_admin, true);
  EXPECT_EQ(nvme_wrapper_.buffer_len, kPageSize * 1);
  EXPECT_EQ(alloc_len, 8);
}

TEST_F(ReadCapacity10Test, ToNvmeBadBuffer) {
  uint8_t bad_buffer[1];
  translator::Allocation allocation{};
  uint32_t alloc_len = 0;
  EXPECT_EQ(translator::ReadCapacity10ToNvme(
                bad_buffer, nvme_wrapper_, kPageSize, 1, allocation, alloc_len),
            translator::StatusCode::kInvalidInput);
}

TEST_F(ReadCapacity10Test, ToNvmeBadControlByteNaca) {
  read_capacity_10_cmd_.control_byte.naca = 1;
  translator::Allocation allocation{};
  uint32_t alloc_len = 0;
  EXPECT_EQ(translator::ReadCapacity10ToNvme(scsi_cmd_, nvme_wrapper_, 1,
                                             kPageSize, allocation, alloc_len),
            translator::StatusCode::kInvalidInput);
}

TEST_F(ReadCapacity10Test, Success) {
  identify_ns_.nsze = 0;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 10;
  uint32_t scsi_block_length = htonl(1 << 10);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(result.returned_logical_block_address, 0);
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, NszeNonzero) {
  identify_ns_.nsze = 1;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 10;
  uint32_t scsi_block_length = htonl(1 << 10);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(
      result.returned_logical_block_address,
      htonl(static_cast<uint32_t>(translator::ltohll(identify_ns_.nsze))));
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, NszeLarge) {
  identify_ns_.nsze = 0xffffffffffff;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 10;
  uint32_t scsi_block_length = htonl(1 << 10);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(result.returned_logical_block_address, 0xffffffff);
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, NszeLimit) {
  identify_ns_.nsze = 0xffffffff;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 10;
  uint32_t scsi_block_length = htonl(1 << 10);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(result.returned_logical_block_address, 0xffffffff);
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, BlocklengthNonzeo) {
  identify_ns_.nsze = 0;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 10;
  uint32_t scsi_block_length = htonl(1 << 10);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(result.returned_logical_block_address, 0);
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, BlocklengthTooSmall) {
  identify_ns_.nsze = 0;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 8;
  EXPECT_EQ(translator::StatusCode::kFailure,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
}

TEST_F(ReadCapacity10Test, BlocklengthTooBig) {
  identify_ns_.nsze = 0;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 32;
  EXPECT_EQ(translator::StatusCode::kFailure,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
}

TEST_F(ReadCapacity10Test, BlocklengthLimit) {
  identify_ns_.nsze = 0;
  identify_ns_.flbas.format = 0;
  identify_ns_.lbaf[identify_ns_.flbas.format].lbads = 31;
  uint32_t scsi_block_length = htonl(1 << 31);
  EXPECT_EQ(translator::StatusCode::kSuccess,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
  scsi::ReadCapacity10Data result = {};
  ASSERT_TRUE(translator::ReadValue(buffer_, result));
  EXPECT_EQ(result.returned_logical_block_address, 0);
  EXPECT_EQ(result.block_length, scsi_block_length);
}

TEST_F(ReadCapacity10Test, FailsOnNullptr) {
  nvme_wrapper_.cmd.dptr.prp.prp1 = 0;
  ASSERT_EQ(translator::StatusCode::kFailure,
            translator::ReadCapacity10ToScsi(buffer_, nvme_wrapper_.cmd));
}

}  // namespace


text:
'use strict';

/* global describe beforeEach jest test expect */
jest.dontMock('../index.js');

const index = require('../index.js');

describe('index.js', () => {
  test('exposes endpoint function', () => {
    expect(index).toBeInstanceOf(Function);
    expect(index.name).toBe('endpoint');
  });
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="author" content="Emanuel Eichhammer" />
<meta name="copyright" content="(C) 2011-2016 Emanuel Eichhammer" />
<title>QCPPaintBufferPixmap Class Reference</title>
<link href="qcp.css" rel="stylesheet" type="text/css"/>

Main Page ·
Class Overview ·
Hierarchy ·
All Classes ·
Special Pages

Public Functions |
Protected Functions

QCPPaintBufferPixmap Class Reference

A paint buffer based on QPixmap, using software raster rendering.
 More...

Inheritance diagram for QCPPaintBufferPixmap:

<map name="QCPPaintBufferPixmap_inherit__map" id="QCPPaintBufferPixmap_inherit__map">
<area shape="rect" id="node2" href="classQCPAbstractPaintBuffer.html" title="The abstract base class for paint buffers, which define the rendering backend. " alt="" coords="4,5,157,29"/>
</map>

Public Functions

 	QCPPaintBufferPixmap (const QSize &size, double devicePixelRatio)

virtual QCPPainter * 	startPainting ()

virtual void 	draw (QCPPainter *painter) const

void 	clear (const QColor &color)

 Public Functions inherited from QCPAbstractPaintBuffer

 	QCPAbstractPaintBuffer (const QSize &size, double devicePixelRatio)

QSize 	size () const

bool 	invalidated () const

double 	devicePixelRatio () const

void 	setSize (const QSize &size)

void 	setInvalidated (bool invalidated=true)

void 	setDevicePixelRatio (double ratio)

virtual void 	donePainting ()

Protected Functions

virtual void 	reallocateBuffer ()

Detailed Description

A paint buffer based on QPixmap, using software raster rendering.

This paint buffer is the default and fall-back paint buffer which uses software rendering and QPixmap as internal buffer. It is used if QCustomPlot::setOpenGl is false.

Constructor & Destructor Documentation

§ QCPPaintBufferPixmap()

          QCPPaintBufferPixmap::QCPPaintBufferPixmap
          (
          const QSize &
          size,

          double
          devicePixelRatio

          )

explicit

Creates a pixmap paint buffer instancen with the specified size and devicePixelRatio, if applicable.

Member Function Documentation

§ startPainting()

          QCPPainter * QCPPaintBufferPixmap::startPainting
          (
          	)

virtual

Returns a QCPPainter which is ready to draw to this buffer. The ownership and thus the responsibility to delete the painter after the painting operations are complete is given to the caller of this method.

Once you are done using the painter, delete the painter and call donePainting.

While a painter generated with this method is active, you must not call setSize, setDevicePixelRatio or clear.

This method may return 0, if a painter couldn't be activated on the buffer. This usually indicates a problem with the respective painting backend.

Implements QCPAbstractPaintBuffer.

§ draw()

          void QCPPaintBufferPixmap::draw
          (
          QCPPainter *
          painter	)
           const

virtual

Draws the contents of this buffer with the provided painter. This is the method that is used to finally join all paint buffers and draw them onto the screen.

Implements QCPAbstractPaintBuffer.

§ clear()

          void QCPPaintBufferPixmap::clear
          (
          const QColor &
          color	)

virtual

Fills the entire buffer with the provided color. To have an empty transparent buffer, use the named color Qt::transparent.

This method must not be called if there is currently a painter (acquired with startPainting) active.

Implements QCPAbstractPaintBuffer.

§ reallocateBuffer()

          void QCPPaintBufferPixmap::reallocateBuffer
          (
          	)

protectedvirtual

Reallocates the internal buffer with the currently configured size (setSize) and device pixel ratio, if applicable (setDevicePixelRatio). It is called as soon as any of those properties are changed on this paint buffer.

Note

Subclasses of QCPAbstractPaintBuffer must call their reimplementation of this method in their constructor, to perform the first allocation (this can not be done by the base class because calling pure virtual methods in base class constructors is not possible).

Implements QCPAbstractPaintBuffer.

The documentation for this class was generated from the following files:

src/paintbuffer.h

src/paintbuffer.cpp


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author: Ilia A. Leviev
Version: $Revision: 1.3 $
-->
<Test
  ID="invokespecial1606"
  date-of-creation="2005-10-06"
  timeout="1"
  >
 <Author value="Ilia A. Leviev"/>
  <Description>
    The test is against the invokespecial java virtual machine instruction.
    It performs the following check.
    public method is accessible if method is member of current class
    and type of object is current class.
   Covered assertions assert_const208 assert_const228 assert_const230
</Description>

  <Source name="invokespecial1606p.j"/>
  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.invokeReturn.invokespecial.invokespecial16.invokespecial1606.invokespecial1606p"/>
  </Runner>
</Test>


text:
using Colourful;
using Colourful.Conversion;
using System;

namespace OneCog.Io.Philips.Hue
{
    public static class ColourfulExtensions
    {
        private static readonly ColourfulConverter Converter = new ColourfulConverter();

        public static Dto.LightState ToLightState(this ColourfulConverter converter, IColorVector color)
        {
            var xy = converter.ToxyY(color);

            return new Dto.LightState
            {
                Xy = new[] { xy.x, xy.y },
                Brightness = Convert.ToInt32(255.0 * xy.Luminance)
            };
        }

        public static Dto.LightState ToLightState(this IColorVector color)
        {
            var xy = Converter.ToxyY(color);

            return new Dto.LightState
            {
                Xy = new[] { xy.x, xy.y },
                Brightness = Convert.ToInt32(255.0 * xy.Luminance)
            };
        }
    }
}


text:
var PageView = require('./base');
var templates = require('../templates');

var app = require('ampersand-app');

module.exports = PageView.extend({
    pageTitle: 'datasets',
    template: templates.pages.datasets,
});


text:
sudo apt-get install -y ruby-full
sudo gem install redis