text:
import maya.OpenMaya as OpenMaya
import maya.cmds as cmds
from collections import Counter

# DataDict structure (dict)
# Key : fullpath of each node
# item : dict of errors:
#        key : name of error
#        item : list of components
#
# For example,
# {u'|group3|group1|pSphere1':
#     {'laminaFaces': [],
#      'smoothPreview': [],
#      'intermediateObject': [],
#      'nonManifoldEdges': [],
#      'opposite': [],
#      'shapeNames': [u'|group3|group1|pSphere1'],
#      'lockedChannels': [],
#      'duplicateNames': [],
#      'transform': [u'|group3|group1|pSphere1'],
#      'keyframes': [],
#      'defaultShader': [],
#      'nGons': [],
#      'intermediateObj': [],
#      'concaveFaces': [],
#      'doubleSided': [],
#      'geoSuffix': [],
#      'history':[u'group1|pSphere1|pSphereShape1', u'polySphere1'],
#      'badExtraordinaryVtx': []],
#      'triangles': []],
#      'nonManifoldVtx': []},
#  u'|group3|group1|pSphere2':
#     {'laminaFaces': [],
#      'smoothPreview': [],
#      'intermediateObject': [],
#      ...

# nodeList : List of all shape and transform nodes

def extend_to_shape(path):

    slist = OpenMaya.MSelectionList()
    dagpath = OpenMaya.MDagPath()
    slist.add(path)
    slist.getDagPath(0, dagpath)
    try:
        dagpath.extendToShape()
        fullpath = dagpath.fullPathName()
        return fullpath
    except RuntimeError:
        return None

def get_shapes(path):
    """ Get shape nodes from transform node
    Args:
        path (str) : full path of transform node
    Return:
        shapes (list) : list of shape nodes
    """

    shapes = cmds.listRelatives(path, ad=True, fullPath=True, type="mesh")
    return shapes

def get_selection_list(nodeList):
    slist = OpenMaya.MSelectionList()
    for i in nodeList:
        slist.add(i)
    return slist

def check_mesh(dagpath):
    """ Check if current item is mesh. """

    pass

def get_history(dataDict, nodeList, badNodeList, *args):
    for i in nodeList:
        hist = cmds.listHistory(i)
        if len(hist) == 1:
            dataDict[i]['history'] = []
        else:
            dataDict[i]['history'] = hist
            badNodeList.append(i)

def get_transform(dataDict, nodeList, badNodeList, *args):

    zeros = [(0.0, 0.0, 0.0)]
    zeros_s = [(1.0, 1.0, 1.0)]

    for i in nodeList:
        trans = cmds.getAttr(i + ".translate")
        rotation = cmds.getAttr(i + ".rotate")
        scale = cmds.getAttr(i + ".scale")
        if (trans == zeros and rotation == zeros and scale == zeros_s):
            dataDict[i]['transform'] = []
        else:
            dataDict[i]['transform'] = [i]
            badNodeList.append(i)

def get_badextraordianry_vtx(dataDict, nodeList, badNodeList, *args):
    """ Store a list of badextravtx to the dict """

    slist = get_selection_list(nodeList)

    utils = OpenMaya.MScriptUtil()
    ptr_int = utils.asIntPtr()

    m_dagpath = OpenMaya.MDagPath()

    for i in range(slist.length()):
        slist.getDagPath(i, m_dagpath)
        vlist = []

        try:
            iter_verts = OpenMaya.MItMeshVertex(m_dagpath)
        except RuntimeError:
            # If it's not mesh
            continue

        while not iter_verts.isDone():
            iter_verts.numConnectedEdges(ptr_int)
            edge_count = utils.getInt(ptr_int)
            index = iter_verts.index()
            if edge_count > 5:
                fullpath = m_dagpath.fullPathName() + ".vtx[%s]" % index
                vlist.append(fullpath)
            iter_verts.next()
        if len(vlist) != 0:
            badNodeList.append(m_dagpath.fullPathName())

        dataDict[m_dagpath.fullPathName()]['badExtraordinaryVtx'] = vlist

def get_triangles(dataDict, nodeList, badNodeList, *args):
    """ Store a list of triangles to the dict """

    slist = get_selection_list(nodeList)

    for i in range(slist.length()):
        m_dagpath = OpenMaya.MDagPath()
        slist.getDagPath(i, m_dagpath)
        edge_list = OpenMaya.MIntArray()
        flist = []

        try:
            iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        except RuntimeError:
            # If it's not mesh
            continue

        iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        while not iter_faces.isDone():
            iter_faces.getEdges(edge_list)
            edge_count = edge_list.length()
            index = iter_faces.index()
            if edge_count == 3:
                fullpath = m_dagpath.fullPathName() + ".f[%s]" % index
                flist.append(fullpath)
            iter_faces.next()
        if len(flist) != 0:
            badNodeList.append(m_dagpath.fullPathName())

        dataDict[m_dagpath.fullPathName()]['triangles'] = flist

def get_ngons(dataDict, nodeList, badNodeList, *args):
    """ Store a list of ngons to the dict """

    slist = get_selection_list(nodeList)

    for i in range(slist.length()):
        m_dagpath = OpenMaya.MDagPath()
        slist.getDagPath(i, m_dagpath)
        edge_list = OpenMaya.MIntArray()
        flist = []

        try:
            iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        except RuntimeError:
            # If it's not mesh
            continue

        while not iter_faces.isDone():
            iter_faces.getEdges(edge_list)
            edge_count = edge_list.length()
            index = iter_faces.index()
            if edge_count >= 5:
                fullpath = m_dagpath.fullPathName() + ".f[%s]" % index
                flist.append(fullpath)
            iter_faces.next()

        if len(flist) != 0:
            badNodeList.append(m_dagpath.fullPathName())

        dataDict[m_dagpath.fullPathName()]['nGons'] = flist

def get_lamina_faces(dataDict, nodeList, badNodeList, *args):
    """ Store a list of lamina faces to the dict """

    slist = get_selection_list(nodeList)

    for i in range(slist.length()):
        m_dagpath = OpenMaya.MDagPath()
        slist.getDagPath(i, m_dagpath)
        flist = []

        try:
            iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        except RuntimeError:
            # If it's not mesh
            continue

        while not iter_faces.isDone():
            lamina_checker = iter_faces.isLamina()
            index = iter_faces.index()
            if lamina_checker is True:
                fullpath = m_dagpath.fullPathName() + ".f[%s]" % index
                flist.append(fullpath)
            iter_faces.next()
        if len(flist) != 0:
            badNodeList.append(m_dagpath.fullPathName())

        dataDict[m_dagpath.fullPathName()]['laminaFaces'] = flist

def get_concave_faces(dataDict, nodeList, badNodeList, *args):
    """ Store a list of lamina faces to the dict """

    slist = get_selection_list(nodeList)

    for i in range(slist.length()):
        m_dagpath = OpenMaya.MDagPath()
        slist.getDagPath(i, m_dagpath)
        flist = []

        try:
            iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        except RuntimeError:
            # If it's not mesh
            continue

        iter_faces = OpenMaya.MItMeshPolygon(m_dagpath)
        while not iter_faces.isDone():
            convex_checker = iter_faces.isConvex()
            index = iter_faces.index()
            if convex_checker is False:
                fullpath = m_dagpath.fullPathName() + ".f[%s]" % index
                flist.append(fullpath)
            iter_faces.next()

        if len(flist) != 0:
            badNodeList.append(m_dagpath.fullPathName())

        dataDict[m_dagpath.fullPathName()]['concaveFaces'] = flist

def get_nonmanifold_vertices(dataDict, nodeList, badNodeList, *args):
    """ Store a list of non manifold vertices. """

    for i in nodeList:
        verts = cmds.polyInfo(i, nonManifoldVertices=True)
        dataDict[i]['nonManifoldVtx'] = verts

        if verts is not None:
            badNodeList.append(i)

        dataDict[i]['nonManifoldVtx'] = []

def get_nonmanifold_edges(dataDict, nodeList, badNodeList, *args):
    """ Store a list of non manifold edges. """

    for i in nodeList:
        edges = cmds.polyInfo(i, nonManifoldEdges=True)
        dataDict[i]['nonManifoldEdges'] = edges

        if edges is not None:
            badNodeList.append(i)

        dataDict[i]['nonManifoldEdges'] = []

def get_opposite(dataDict, nodeList, badNodeList, *args):

    for i in nodeList:
        shape = extend_to_shape(i)
        if shape is None:
            continue
        else:
            oppositeStatus = cmds.getAttr(i + ".opposite")
            if oppositeStatus is True:
                dataDict[i]['opposite'] = [i]
                badNodeList.append(i)
            else:
                dataDict[i]['opposite'] = []

def get_doublesided(dataDict, nodeList, badNodeList, *args):

    for i in nodeList:
        shape = extend_to_shape(i)
        if shape is None:
            continue
        else:
            oppositeStatus = cmds.getAttr(i + ".doubleSided")
            if oppositeStatus is True:
                dataDict[i]['doubleSided'] = []
            else:
                dataDict[i]['doubleSided'] = [i]
                badNodeList.append(i)

def get_intermediate_obj(dataDict, nodeList, badNodeList, *args):

    for i in nodeList:
        shapes = get_shapes(i)
        if shapes is None:
            continue
        else:
            for shape in shapes:
                oppositeStatus = cmds.getAttr(shape + ".intermediateObject")
                if oppositeStatus is True:
                    dataDict[i]['intermediateObj'] = [shape]
                    badNodeList.append(i)
                    return
                else:
                    dataDict[i]['intermediateObj'] = []

def get_bad_shapenames(dataDict, nodeList, badNodeList, *args):

    for i in nodeList:
        shape = extend_to_shape(i)
        if shape is None:
            continue
        else:
            shape = shape.split("|")[-1]

        rightShape = i.split("|")[-1] + "Shape"
        if shape == rightShape:
            dataDict[i]['shapeNames'] = []
        else:
            dataDict[i]['shapeNames'] = [i]
            badNodeList.append(i)

def get_duplicated_names(dataDict, nodeList, badNodeList, *args):
    shortNames = [i.split("|")[-1] for i in nodeList]
    collection = Counter(shortNames)
    duplicateNamesList = [i for i in collection if collection[i] > 1]

    for i in nodeList:
        if i.split("|")[-1] in duplicateNamesList:
            dataDict[i]['duplicateNames'] = duplicateNamesList
            badNodeList.append(i)

def get_smooth_mesh(dataDict, nodeList, badNodeList, *args):

    for i in nodeList:
        shape = extend_to_shape(i)
        if shape is None:
            pass
        else:
            smoothMesh = cmds.getAttr(i + ".displaySmoothMesh")
            if smoothMesh == 1:
                dataDict[i]['smoothPreview'] = [i]
                badNodeList.append(i)
            elif smoothMesh == 2:
                dataDict[i]['smoothPreview'] = [i]
                badNodeList.append(i)
            else:
                dataDict[i]['smoothPreview'] = []

def get_shader(dataDict, nodeList, badNodeList, *args):
    for i in nodeList:
        shape = extend_to_shape(i)
        if shape is None:
            pass
        else:
            try:
                sg = cmds.listConnections(shape, type='shadingEngine')[0]
                if sg == 'initialShadingGroup':
                    dataDict[i]['defaultShader'] = []
                else:
                    dataDict[i]['defaultShader'] = [sg]
                    badNodeList.append(i)
            except TypeError:
                # INTERMEDIATE OBJECT CAN'T GET SHADINIG GROUP
                # NEED TO REMOVE INTERMEDIATE OBJECT FIRST
                pass

def get_geo_suffix(dataDict, nodeList, badNodeList, suffix):

    for i in nodeList:
        currentSuffix = "_" + i.split("_")[-1]
        if currentSuffix in suffix:
            pass
        else:
            dataDict[i]['geoSuffix'] = [i]
            badNodeList.append(i)

def get_locked_channels(dataDict, nodeList, badNodeList, *args):
    for i in nodeList:
        attrs = cmds.listAttr(i)
        for att in attrs:
            try:
                lockState = cmds.getAttr(i + "." + att, lock=True)
                if lockState is True:
                    dataDict[i]['lockedChannels'] = [i]
                    badNodeList.append(i)
                    return
                else:
                    pass
            except ValueError:
                pass

def get_keyframes(dataDict, nodeList, badNodeList, *args):
    for i in nodeList:
        attrs = cmds.listAttr(i)
        for att in attrs:
            try:
                keyState = cmds.keyframe(i + "." + att, q=True)
                if keyState is None:
                    pass
                else:
                    dataDict[i]['keyframes'] = [i]
                    badNodeList.append(i)
                    return
            except ValueError:
                pass


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.messaging.eventhubs;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.azure.core.util.IterableStream;
import com.azure.messaging.eventhubs.models.CreateBatchOptions;
import com.azure.messaging.eventhubs.models.EventPosition;
import com.azure.messaging.eventhubs.models.LastEnqueuedEventProperties;
import com.azure.messaging.eventhubs.models.PartitionContext;
import com.azure.messaging.eventhubs.models.PartitionEvent;
import com.azure.messaging.eventhubs.models.ReceiveOptions;
import com.azure.messaging.eventhubs.models.SendOptions;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * This class contains all code snippets that are used in Event Hubs JavaDocs.
 */
public class EventHubsJavaDocCodeSamples {
    private final EventHubClientBuilder builder = new EventHubClientBuilder();
    private final EventHubConsumerAsyncClient consumer = builder
        .connectionString("fake-string")
        .consumerGroup("consumer-group-name")
        .buildAsyncConsumerClient();

    /**
     * Creates an EventData using application properties.
     */
    public void createEventData() {
        // BEGIN: com.azure.messaging.eventhubs.eventdata.getProperties
        TelemetryEvent telemetry = new TelemetryEvent("temperature", "37");
        byte[] serializedTelemetryData = telemetry.toString().getBytes(UTF_8);

        EventData eventData = new EventData(serializedTelemetryData);
        eventData.getProperties().put("eventType", TelemetryEvent.class.getName());
        // END: com.azure.messaging.eventhubs.eventdata.getProperties
    }

    /**
     * Code snippet for {@link EventHubClientBuilder#shareConnection()}.
     */
    public void sharingConnection() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubclientbuilder.instantiation
        // Toggling `shareConnection` instructs the builder to use the same underlying connection
        // for each consumer or producer created using the same builder instance.
        EventHubClientBuilder builder = new EventHubClientBuilder()
            .connectionString("event-hubs-instance-connection-string")
            .shareConnection();

        // Both the producer and consumer created share the same underlying connection.
        EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();
        EventHubConsumerAsyncClient consumer = builder
            .consumerGroup("my-consumer-group")
            .buildAsyncConsumerClient();
        // END: com.azure.messaging.eventhubs.eventhubclientbuilder.instantiation
    }

    public void instantiateConsumerAsyncClient() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.instantiation
        // The required parameters are `consumerGroup` and a way to authenticate with Event Hubs using credentials.
        EventHubConsumerAsyncClient consumer = new EventHubClientBuilder()
            .connectionString("Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};"
                + "SharedAccessKey={key};EntityPath={eh-name}")
            .consumerGroup("consumer-group-name")
            .buildAsyncConsumerClient();
        // END: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.instantiation

        consumer.close();
    }

    /**
     * Receives event data from a single partition.
     */
    public void receive() {

        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#string-eventposition
        // Obtain partitionId from EventHubConsumerAsyncClient.getPartitionIds()
        String partitionId = "0";
        EventPosition startingPosition = EventPosition.latest();

        // Keep a reference to `subscription`. When the program is finished receiving events, call
        // subscription.dispose(). This will stop fetching events from the Event Hub.
        Disposable subscription = consumer.receiveFromPartition(partitionId, startingPosition)
            .subscribe(partitionEvent -> {
                PartitionContext partitionContext = partitionEvent.getPartitionContext();
                EventData event = partitionEvent.getData();

                System.out.printf("Received event from partition '%s'%n", partitionContext.getPartitionId());
                System.out.printf("Contents of event as string: '%s'%n", event.getBodyAsString());
            }, error -> System.err.print(error.toString()));
        // END: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#string-eventposition

        // When program ends, or you're done receiving all events.
        subscription.dispose();
    }

    /**
     * Receives event data with back pressure.
     */
    public void receiveBackpressure() {
        // Obtain partitionId from EventHubAsyncClient.getPartitionIds()
        String partitionId = "0";

        EventHubConsumerAsyncClient consumer = new EventHubClientBuilder()
            .connectionString("fake-string")
            .consumerGroup("consumer-group-name")
            .buildAsyncConsumerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#string-eventposition-basesubscriber
        consumer.receiveFromPartition(partitionId, EventPosition.latest()).subscribe(new BaseSubscriber<PartitionEvent>() {
            private static final int NUMBER_OF_EVENTS = 5;
            private final AtomicInteger currentNumberOfEvents = new AtomicInteger();

            @Override
            protected void hookOnSubscribe(Subscription subscription) {
                // Tell the Publisher we only want 5 events at a time.
                request(NUMBER_OF_EVENTS);
            }

            @Override
            protected void hookOnNext(PartitionEvent value) {
                // Process the EventData

                // If the number of events we have currently received is a multiple of 5, that means we have reached the
                // last event the Publisher will provide to us. Invoking request(long) here, tells the Publisher that
                // the subscriber is ready to get more events from upstream.
                if (currentNumberOfEvents.incrementAndGet() % 5 == 0) {
                    request(NUMBER_OF_EVENTS);
                }
            }
        });
        // END: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#string-eventposition-basesubscriber
    }

    /**
     * Receives from all partitions.
     */
    public void receiveAll() {
        EventHubConsumerAsyncClient consumer = new EventHubClientBuilder()
            .connectionString("fake-string")
            .consumerGroup("consumer-group-name")
            .buildAsyncConsumerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#boolean
        // Receives events from all partitions from the beginning of each partition.
        consumer.receive(true).subscribe(partitionEvent -> {
            PartitionContext context = partitionEvent.getPartitionContext();
            EventData event = partitionEvent.getData();
            System.out.printf("Event %s is from partition %s%n.", event.getSequenceNumber(), context.getPartitionId());
        });
        // END: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receive#boolean
    }

    /**
     * Receives from all partitions with last enqueued information.
     */
    public void receiveLastEnqueuedInformation() {
        EventHubConsumerAsyncClient consumer = new EventHubClientBuilder()
            .connectionString("event-hub-instance-connection-string")
            .consumerGroup("consumer-group-name")
            .buildAsyncConsumerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receiveFromPartition#string-eventposition-receiveoptions
        // Set `setTrackLastEnqueuedEventProperties` to true to get the last enqueued information from the partition for
        // each event that is received.
        ReceiveOptions receiveOptions = new ReceiveOptions()
            .setTrackLastEnqueuedEventProperties(true);

        // Receives events from partition "0" as they come in.
        consumer.receiveFromPartition("0", EventPosition.earliest(), receiveOptions)
            .subscribe(partitionEvent -> {
                LastEnqueuedEventProperties properties = partitionEvent.getLastEnqueuedEventProperties();
                System.out.printf("Information received at %s. Last enqueued sequence number: %s%n",
                    properties.getRetrievalTime(),
                    properties.getSequenceNumber());
            });
        // END: com.azure.messaging.eventhubs.eventhubconsumerasyncclient.receiveFromPartition#string-eventposition-receiveoptions
    }

    /**
     * Code snippet for creating an EventHubConsumer
     */
    public void instantiateConsumerClient() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerclient.instantiation
        // The required parameters are `consumerGroup`, and a way to authenticate with Event Hubs using credentials.
        EventHubConsumerClient consumer = new EventHubClientBuilder()
            .connectionString(
                "Endpoint={eh-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key};Entity-Path={hub-name}")
            .consumerGroup("$DEFAULT")
            .buildConsumerClient();
        // END: com.azure.messaging.eventhubs.eventhubconsumerclient.instantiation

        consumer.close();
    }

    /**
     * Receives event data from a single partition.
     */
    public void receiveFromSinglePartition() {
        EventHubConsumerClient consumer = new EventHubClientBuilder()
            .connectionString("event-hub-instance-connection-string")
            .consumerGroup("consumer-group-name")
            .buildConsumerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubconsumerclient.receive#string-int-eventposition-duration
        Instant twelveHoursAgo = Instant.now().minus(Duration.ofHours(12));
        EventPosition startingPosition = EventPosition.fromEnqueuedTime(twelveHoursAgo);
        String partitionId = "0";

        // Reads events from partition '0' and returns the first 100 received or until the 30 seconds has elapsed.
        IterableStream<PartitionEvent> events = consumer.receiveFromPartition(partitionId, 100,
            startingPosition, Duration.ofSeconds(30));

        Long lastSequenceNumber = -1L;
        for (PartitionEvent partitionEvent : events) {
            // For each event, perform some sort of processing.
            System.out.print("Event received: " + partitionEvent.getData().getSequenceNumber());
            lastSequenceNumber = partitionEvent.getData().getSequenceNumber();
        }

        // Figure out what the next EventPosition to receive from is based on last event we processed in the stream.
        // If lastSequenceNumber is -1L, then we didn't see any events the first time we fetched events from the
        // partition.
        if (lastSequenceNumber != -1L) {
            EventPosition nextPosition = EventPosition.fromSequenceNumber(lastSequenceNumber, false);

            // Gets the next set of events from partition '0' to consume and process.
            IterableStream<PartitionEvent> nextEvents = consumer.receiveFromPartition(partitionId, 100,
                nextPosition, Duration.ofSeconds(30));
        }
        // END: com.azure.messaging.eventhubs.eventhubconsumerclient.receive#string-int-eventposition-duration
    }

    /**
     * Code snippet demonstrating how to create an {@link EventHubProducerAsyncClient}.
     */
    public void instantiateProducerAsyncClient() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.instantiation
        // The required parameter is a way to authenticate with Event Hubs using credentials.
        // The connectionString provides a way to authenticate with Event Hub.
        EventHubProducerAsyncClient producer = new EventHubClientBuilder()
            .connectionString(
                "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}",
                "event-hub-name")
            .buildAsyncProducerClient();
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.instantiation

        producer.close();
    }

    /**
     * Code snippet demonstrating how to send a batch that automatically routes events to any partition.
     */
    public void batchAutomaticRoutingAsync() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch
        // The required parameter is a way to authenticate with Event Hubs using credentials.
        // The connectionString provides a way to authenticate with Event Hub.
        EventHubProducerAsyncClient producer = new EventHubClientBuilder()
            .connectionString(
                "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}",
                "event-hub-name")
            .buildAsyncProducerClient();

        // Creating a batch without options set, will allow for automatic routing of events to any partition.
        producer.createBatch().flatMap(batch -> {
            batch.tryAdd(new EventData("test-event-1"));
            batch.tryAdd(new EventData("test-event-2"));
            return producer.send(batch);
        }).subscribe(unused -> { },
            error -> System.err.println("Error occurred while sending batch:" + error),
            () -> System.out.println("Send complete."));
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch

        producer.close();
    }

    /**
     * Code snippet demonstrating how to create an EventDataBatch at routes events to a single partition.
     */
    public void batchPartitionIdAsync() {
        EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-partitionId
        // Creating a batch with partitionId set will route all events in that batch to partition `foo`.
        CreateBatchOptions options = new CreateBatchOptions().setPartitionId("foo");
        producer.createBatch(options).flatMap(batch -> {
            batch.tryAdd(new EventData("test-event-1"));
            batch.tryAdd(new EventData("test-event-2"));
            return producer.send(batch);
        }).subscribe(unused -> { },
            error -> System.err.println("Error occurred while sending batch:" + error),
            () -> System.out.println("Send complete."));
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-partitionId

        producer.close();
    }

    /**
     * Code snippet demonstrating how to send events with a partition key.
     */
    public void batchPartitionKeyAsync() {
        EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-partitionKey
        // Creating a batch with partitionKey set will tell the service to hash the partitionKey and decide which
        // partition to send the events to. Events with the same partitionKey are always routed to the same partition.
        CreateBatchOptions options = new CreateBatchOptions().setPartitionKey("bread");
        producer.createBatch(options).flatMap(batch -> {
            batch.tryAdd(new EventData("sourdough"));
            batch.tryAdd(new EventData("rye"));
            return producer.send(batch);
        }).subscribe(unused -> { },
            error -> System.err.println("Error occurred while sending batch:" + error),
            () -> System.out.println("Send complete."));
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-partitionKey
    }

    /**
     * Code snippet demonstrating how to create a size-limited {@link EventDataBatch} and send it.
     */
    public void batchSizeLimitedAsync() {
        final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();
        final EventData firstEvent = new EventData("92".getBytes(UTF_8));
        firstEvent.getProperties().put("telemetry", "latency");
        final EventData secondEvent = new EventData("98".getBytes(UTF_8));
        secondEvent.getProperties().put("telemetry", "cpu-temperature");

        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-int
        final Flux<EventData> telemetryEvents = Flux.just(firstEvent, secondEvent);

        // Setting `setMaximumSizeInBytes` when creating a batch, limits the size of that batch.
        // In this case, all the batches created with these options are limited to 256 bytes.
        final CreateBatchOptions options = new CreateBatchOptions()
            .setMaximumSizeInBytes(256);
        final AtomicReference<EventDataBatch> currentBatch = new AtomicReference<>(
            producer.createBatch(options).block());

        // The sample Flux contains two events, but it could be an infinite stream of telemetry events.
        telemetryEvents.flatMap(event -> {
            final EventDataBatch batch = currentBatch.get();
            if (batch.tryAdd(event)) {
                return Mono.empty();
            }

            return Mono.when(
                producer.send(batch),
                producer.createBatch(options).map(newBatch -> {
                    currentBatch.set(newBatch);

                    // Add the event that did not fit in the previous batch.
                    if (!newBatch.tryAdd(event)) {
                        throw Exceptions.propagate(new IllegalArgumentException(
                            "Event was too large to fit in an empty batch. Max size: " + newBatch.getMaxSizeInBytes()));
                    }

                    return newBatch;
                }));
        }).then()
            .doFinally(signal -> {
                final EventDataBatch batch = currentBatch.getAndSet(null);
                if (batch != null && batch.getCount() > 0) {
                    producer.send(batch).block();
                }
            });
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.createBatch#CreateBatchOptions-int
    }

    /**
     * Code snippet to demonstrate how to send a list of events using
     * {@link EventHubProducerAsyncClient#send(Iterable)}.
     */
    public void sendIterableSampleAsync() {
        final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();
        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.send#Iterable
        List<EventData> events = Arrays.asList(new EventData("maple"), new EventData("aspen"),
            new EventData("oak"));
        producer
            .send(events)
            .subscribe(unused -> { },
                error -> System.err.println("Error occurred while sending events:" + error),
                () -> System.out.println("Send complete."));
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.send#Iterable
    }

    /**
     * Code snippet to demonstrate how to send a list of events using
     * {@link EventHubProducerAsyncClient#send(Iterable, SendOptions)}.
     */
    public void sendIterableWithPartitionKeySampleAsync() {
        final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient();
        // BEGIN: com.azure.messaging.eventhubs.eventhubasyncproducerclient.send#Iterable-SendOptions
        List<EventData> events = Arrays.asList(new EventData("Melbourne"), new EventData("London"),
            new EventData("New York"));
        SendOptions sendOptions = new SendOptions().setPartitionKey("cities");
        producer
            .send(events, sendOptions)
            .subscribe(unused -> { },
                error -> System.err.println("Error occurred while sending events:" + error),
                () -> System.out.println("Send complete."));
        // END: com.azure.messaging.eventhubs.eventhubasyncproducerclient.send#Iterable-SendOptions
    }

    /**
     * Code snippet demonstrating how to create an {@link EventHubProducerClient}.
     */
    public void instantiateProducerClient() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.instantiation
        // The required parameter is a way to authenticate with Event Hubs using credentials.
        // The connectionString provides a way to authenticate with Event Hub.
        EventHubProducerClient producer = new EventHubClientBuilder()
            .connectionString(
                "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}",
                "event-hub-name")
            .buildProducerClient();
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.instantiation

        producer.close();
    }

    /**
     * Code snippet demonstrating how to send a batch that automatically routes events to any partition.
     *
     * @throws IllegalArgumentException if an event is too large for an empty batch.
     */
    public void batchAutomaticRouting() {
        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch
        // The required parameter is a way to authenticate with Event Hubs using credentials.
        // The connectionString provides a way to authenticate with Event Hub.
        EventHubProducerClient producer = new EventHubClientBuilder()
            .connectionString(
                "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}",
                "event-hub-name")
            .buildProducerClient();
        List<EventData> events = Arrays.asList(new EventData("test-event-1"), new EventData("test-event-2"));

        // Creating a batch without options set, will allow for automatic routing of events to any partition.
        EventDataBatch batch = producer.createBatch();
        for (EventData event : events) {
            if (batch.tryAdd(event)) {
                continue;
            }

            producer.send(batch);
            batch = producer.createBatch();
            if (!batch.tryAdd(event)) {
                throw new IllegalArgumentException("Event is too large for an empty batch.");
            }
        }
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch

        producer.close();
    }

    /**
     * Code snippet demonstrating how to create an EventDataBatch at routes events to a single partition.
     */
    public void batchPartitionId() {
        final EventHubProducerClient producer = builder.buildProducerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-partitionId
        // Creating a batch with partitionId set will route all events in that batch to partition `foo`.
        CreateBatchOptions options = new CreateBatchOptions().setPartitionId("foo");

        EventDataBatch batch = producer.createBatch(options);
        batch.tryAdd(new EventData("data-to-partition-foo"));
        producer.send(batch);
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-partitionId
    }

    /**
     * Code snippet demonstrating how to send events with a partition key.
     */
    public void batchPartitionKey() {
        final EventHubProducerClient producer = builder.buildProducerClient();

        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-partitionKey
        List<EventData> events = Arrays.asList(new EventData("sourdough"), new EventData("rye"),
            new EventData("wheat"));

        // Creating a batch with partitionKey set will tell the service to hash the partitionKey and decide which
        // partition to send the events to. Events with the same partitionKey are always routed to the same partition.
        CreateBatchOptions options = new CreateBatchOptions().setPartitionKey("bread");
        EventDataBatch batch = producer.createBatch(options);

        events.forEach(event -> batch.tryAdd(event));
        producer.send(batch);
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-partitionKey
    }

    /**
     * Code snippet demonstrating how to create a size-limited {@link EventDataBatch} and send it.
     *
     * @throws IllegalArgumentException if an event is too large for an empty batch.
     */
    public void batchSizeLimited() {
        final EventHubProducerClient producer = builder.buildProducerClient();
        final EventData firstEvent = new EventData("92".getBytes(UTF_8));
        firstEvent.getProperties().put("telemetry", "latency");
        final EventData secondEvent = new EventData("98".getBytes(UTF_8));
        secondEvent.getProperties().put("telemetry", "cpu-temperature");
        final EventData thirdEvent = new EventData("120".getBytes(UTF_8));
        thirdEvent.getProperties().put("telemetry", "fps");

        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-int

        final List<EventData> telemetryEvents = Arrays.asList(firstEvent, secondEvent, thirdEvent);

        // Setting `setMaximumSizeInBytes` when creating a batch, limits the size of that batch.
        // In this case, all the batches created with these options are limited to 256 bytes.
        final CreateBatchOptions options = new CreateBatchOptions()
            .setMaximumSizeInBytes(256);

        EventDataBatch currentBatch = producer.createBatch(options);

        // For each telemetry event, we try to add it to the current batch.
        // When the batch is full, send it then create another batch to add more events to.
        for (EventData event : telemetryEvents) {
            if (!currentBatch.tryAdd(event)) {
                producer.send(currentBatch);
                currentBatch = producer.createBatch(options);

                // Add the event we couldn't before.
                if (!currentBatch.tryAdd(event)) {
                    throw new IllegalArgumentException("Event is too large for an empty batch.");
                }
            }
        }
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.createBatch#CreateBatchOptions-int
    }

    /**
     * Code snippet to demonstrate how to send a list of events using {@link EventHubProducerClient#send(Iterable)}.
     */
    public void sendIterableSample() {
        final EventHubProducerClient producer = builder.buildProducerClient();
        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.send#Iterable
        List<EventData> events = Arrays.asList(new EventData("maple"), new EventData("aspen"),
            new EventData("oak"));
        producer.send(events);
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.send#Iterable
    }

    /**
     * Code snippet to demonstrate how to send a list of events using
     * {@link EventHubProducerClient#send(Iterable, SendOptions)}.
     */
    public void sendIterableWithPartitionKeySample() {
        final EventHubProducerClient producer = builder.buildProducerClient();
        // BEGIN: com.azure.messaging.eventhubs.eventhubproducerclient.send#Iterable-SendOptions
        List<EventData> events = Arrays.asList(new EventData("Melbourne"), new EventData("London"),
            new EventData("New York"));
        SendOptions sendOptions = new SendOptions().setPartitionKey("cities");
        producer.send(events, sendOptions);
        // END: com.azure.messaging.eventhubs.eventhubproducerclient.send#Iterable-SendOptions
    }

    /**
     * Code snippet for showing how to create a new instance of {@link EventProcessorClient}.
     *
     * @return A new instance of {@link EventProcessorClient}
     */
    // BEGIN: com.azure.messaging.eventhubs.eventprocessorclientbuilder.instantiation
    public EventProcessorClient createEventProcessor() {
        String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
            + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";

        EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
            .consumerGroup("consumer-group")
            .checkpointStore(new SampleCheckpointStore())
            .processEvent(eventContext -> {
                System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId()
                    + "and sequence number of event = " + eventContext.getEventData().getSequenceNumber());
            })
            .processError(errorContext -> {
                System.out.printf("Error occurred in partition processor for partition {}, {}",
                    errorContext.getPartitionContext().getPartitionId(),
                    errorContext.getThrowable());
            })
            .connectionString(connectionString)
            .buildEventProcessorClient();
        return eventProcessorClient;
    }
    // END: com.azure.messaging.eventhubs.eventprocessorclientbuilder.instantiation

    /**
     * Code snippet to show creation of an event processor that receives events in batches.
     */
    public void receiveBatchSample() {
        String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
            + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";

        // BEGIN: com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive
        EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
            .consumerGroup("consumer-group")
            .checkpointStore(new SampleCheckpointStore())
            .processEventBatch(eventBatchContext -> {
                eventBatchContext.getEvents().forEach(eventData -> {
                    System.out.println("Partition id = " + eventBatchContext.getPartitionContext().getPartitionId()
                        + "and sequence number of event = " + eventData.getSequenceNumber());
                });
            }, 50, Duration.ofSeconds(30))
            .processError(errorContext -> {
                System.out.printf("Error occurred in partition processor for partition {}, {}",
                    errorContext.getPartitionContext().getPartitionId(),
                    errorContext.getThrowable());
            })
            .connectionString(connectionString)
            .buildEventProcessorClient();
        // END: com.azure.messaging.eventhubs.eventprocessorclientbuilder.batchreceive
    }

    /**
     * Code snippet for showing how to start and stop an {@link EventProcessorClient}.
     */
    public void startStopSample() {
        String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
            + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
        EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
            .connectionString(connectionString)
            .processEvent(eventContext -> {
                System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and "
                    + "sequence number of event = " + eventContext.getEventData().getSequenceNumber());
            })
            .processError(errorContext -> {
                System.out.printf("Error occurred in partition processor for partition {}, {}",
                    errorContext.getPartitionContext().getPartitionId(),
                    errorContext.getThrowable());
            })
            .consumerGroup("consumer-group")
            .buildEventProcessorClient();

        // BEGIN: com.azure.messaging.eventhubs.eventprocessorclient.startstop
        eventProcessorClient.start();
        // Continue to perform other tasks while the processor is running in the background.
        eventProcessorClient.stop();
        // END: com.azure.messaging.eventhubs.eventprocessorclient.startstop
    }

    private static final class TelemetryEvent {
        private final String name;
        private final String value;

        private TelemetryEvent(String name, String value) {
            this.name = name;
            this.value = value;
        }

        @Override
        public String toString() {
            return String.format("[name]=%s;[value]=%s", name, value);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as XDR from "../../src";
import { keys, each } from "lodash";

describe('XDR.config', function() {

  beforeEach(function() {
    this.types = XDR.config(); // get the xdr object root
    let toDelete = keys(this.types);
    each(toDelete, k => delete this.types[k]);
  });

  it('can define objects that have no dependency', function() {
    XDR.config(xdr => {
      xdr.enum('Color', {
        red: 0,
        green: 1,
        blue: 2,
      });

      xdr.enum('ResultType', {
        ok: 0,
        error: 1
      });
    });

    expect(this.types.Color).to.be.truthy;
    expect(this.types.ResultType).to.be.truthy;
  });

  it('can define objects that have simple dependencies', function() {
    XDR.config(xdr => {
      xdr.union('Result', {
        switchOn: xdr.lookup('ResultType'),
        switches: [
          ["ok", XDR.Void],
          ["error",   "message"],
        ],
        defaultArm: XDR.Void,
        arms: {
          message: new XDR.String(100)
        }
      });

      xdr.enum('ResultType', {
        ok: 0,
        error: 1
      });
    });

    expect(this.types.Result).to.be.truthy;
    expect(this.types.ResultType).to.be.truthy;

    let result = this.types.Result.ok();
    expect(result.switch()).to.eql(this.types.ResultType.ok());

    result = this.types.Result.error("It broke!");
    expect(result.switch()).to.eql(this.types.ResultType.error());
    expect(result.message()).to.eql("It broke!");
  });

  it('can define structs', function() {
    XDR.config(xdr => {
      xdr.struct("Color", [
        ["red", xdr.int()],
        ["green", xdr.int()],
        ["blue", xdr.int()],
      ]);
    });

    expect(this.types.Color).to.be.truthy;

    let result = new this.types.Color({
      red: 0,
      green: 1,
      blue: 2,
    });
    expect(result.red()).to.eql(0);
    expect(result.green()).to.eql(1);
    expect(result.blue()).to.eql(2);
  });

  it('can define typedefs', function() {
    let xdr = XDR.config(xdr => {
      xdr.typedef("Uint256", xdr.opaque(32) );
    });
    expect(xdr.Uint256).to.be.instanceof(XDR.Opaque);
  });

  it('can define consts', function() {
    let xdr = XDR.config(xdr => {
      xdr.typedef("MAX_SIZE", 300 );
    });
    expect(xdr.MAX_SIZE).to.eql(300);
  });

  it('can define arrays', function() {
    let xdr = XDR.config(xdr => {
      xdr.typedef("ArrayOfInts", xdr.array(xdr.int(), 3) );
      xdr.struct('MyStruct', [["red", xdr.int()]]);
      xdr.typedef("ArrayOfEmpty", xdr.array(xdr.lookup("MyStruct"), 5) );
    });

    expect(xdr.ArrayOfInts).to.be.instanceof(XDR.Array);
    expect(xdr.ArrayOfInts._childType).to.eql(XDR.Int);
    expect(xdr.ArrayOfInts._length).to.eql(3);

    expect(xdr.ArrayOfEmpty).to.be.instanceof(XDR.Array);
    expect(xdr.ArrayOfEmpty._childType).to.eql(xdr.MyStruct);
    expect(xdr.ArrayOfEmpty._length).to.eql(5);
  });

  it('can define vararrays', function() {
    let xdr = XDR.config(xdr => {
      xdr.typedef("ArrayOfInts", xdr.varArray(xdr.int(), 3) );
    });

    expect(xdr.ArrayOfInts).to.be.instanceof(XDR.VarArray);
    expect(xdr.ArrayOfInts._childType).to.eql(XDR.Int);
    expect(xdr.ArrayOfInts._maxLength).to.eql(3);
  });

  it('can define options', function() {
    let xdr = XDR.config(xdr => {
      xdr.typedef("OptionalInt", xdr.option(xdr.int()) );
    });

    expect(xdr.OptionalInt).to.be.instanceof(XDR.Option);
    expect(xdr.OptionalInt._childType).to.eql(XDR.Int);
  });

  it('can use sizes defined as an xdr const', function() {
    let xdr = XDR.config(xdr => {
      xdr.const("SIZE", 5);
      xdr.typedef("MyArray",      xdr.array(xdr.int(), xdr.lookup("SIZE")));
      xdr.typedef("MyVarArray",   xdr.varArray(xdr.int(), xdr.lookup("SIZE")));
      xdr.typedef("MyString",     xdr.string(xdr.lookup("SIZE")));
      xdr.typedef("MyOpaque",     xdr.opaque(xdr.lookup("SIZE")));
      xdr.typedef("MyVarOpaque",  xdr.varOpaque(xdr.lookup("SIZE")));
    });

    expect(xdr.MyArray).to.be.instanceof(XDR.Array);
    expect(xdr.MyArray._childType).to.eql(XDR.Int);
    expect(xdr.MyArray._length).to.eql(5);

    expect(xdr.MyVarArray).to.be.instanceof(XDR.VarArray);
    expect(xdr.MyVarArray._childType).to.eql(XDR.Int);
    expect(xdr.MyVarArray._maxLength).to.eql(5);

    expect(xdr.MyString).to.be.instanceof(XDR.String);
    expect(xdr.MyString._maxLength).to.eql(5);

    expect(xdr.MyOpaque).to.be.instanceof(XDR.Opaque);
    expect(xdr.MyOpaque._length).to.eql(5);

    expect(xdr.MyVarOpaque).to.be.instanceof(XDR.VarOpaque);
    expect(xdr.MyVarOpaque._maxLength).to.eql(5);
  });
});


text:
package org.radeox.test.macro;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.radeox.EngineManager;

public class ApiDocMacroTest extends MacroTestSupport
{
	public ApiDocMacroTest(String name)
	{
		super(name);
	}

	public static Test suite()
	{
		return new TestSuite(ApiDocMacroTest.class);
	}

	public void testApi()
	{
		String result = EngineManager.getInstance().render("{api-docs}",
				context);
		// This must be moved to IoC to better test ApiDoc directly.
		assertEquals(
				"ApiDocs are rendered",
				"

Binding	BaseUrl	Converter"
						+ " Name

java131	http://java.sun.com/j2se/1.3.1/docs/api/"
						+ "	Java

java	http://java.sun.com/j2s"
						+ "e/1.4.1/docs/api/	Java

ruby	http://ww"
						+ "w.rubycentral.com/book/ref_c_	Ruby

radeox	htt"
						+ "p://snipsnap.org/docs/api/	Java

nanning	&"
						+ "#104;ttp://nanning.sourceforge.net/apidocs/	Java

java12	http://java.sun.com/j2se/1.2/docs/api/	Java

j2ee	http://java.sun.com/j2ee/sdk_1.3/techdocs/api/	Java

",
				result);
	}

}


text:
package com.amazonaws.services.autoscaling.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes whether instance monitoring is enabled.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InstanceMonitoring implements Serializable, Cloneable {

    /**
     *

     * If True, instance monitoring is enabled.
     *

     */
    private Boolean enabled;

    /**
     *

     * If True, instance monitoring is enabled.
     *

     *
     * @param enabled
     *        If True, instance monitoring is enabled.
     */

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    /**
     *

     * If True, instance monitoring is enabled.
     *

     *
     * @return If True, instance monitoring is enabled.
     */

    public Boolean getEnabled() {
        return this.enabled;
    }

    /**
     *

     * If True, instance monitoring is enabled.
     *

     *
     * @param enabled
     *        If True, instance monitoring is enabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InstanceMonitoring withEnabled(Boolean enabled) {
        setEnabled(enabled);
        return this;
    }

    /**
     *

     * If True, instance monitoring is enabled.
     *

     *
     * @return If True, instance monitoring is enabled.
     */

    public Boolean isEnabled() {
        return this.enabled;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEnabled() != null)
            sb.append("Enabled: ").append(getEnabled());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof InstanceMonitoring == false)
            return false;
        InstanceMonitoring other = (InstanceMonitoring) obj;
        if (other.getEnabled() == null ^ this.getEnabled() == null)
            return false;
        if (other.getEnabled() != null && other.getEnabled().equals(this.getEnabled()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getEnabled() == null) ? 0 : getEnabled().hashCode());
        return hashCode;
    }

    @Override
    public InstanceMonitoring clone() {
        try {
            return (InstanceMonitoring) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package com.comcast.cdn.traffic_control.traffic_monitor.health;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.apache.wicket.ajax.json.JSONArray;
import org.apache.wicket.ajax.json.JSONException;
import org.apache.wicket.ajax.json.JSONObject;

import com.comcast.cdn.traffic_control.traffic_monitor.KeyValue;
import com.comcast.cdn.traffic_control.traffic_monitor.data.DataPoint;
import com.comcast.cdn.traffic_control.traffic_monitor.data.DataSummary;

abstract public class AbstractState implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(AbstractState.class);
	public static final String IS_AVAILABLE_STR = "isAvailable";
	public static final String IS_HEALTHY_STR = "isHealthy";
	private long historyTime = 5*60*1000;

	final String id;
	private final Map<String,List<DataPoint>> stats = new HashMap<String,List<DataPoint>>();
	protected final Set<String> hiddenStats = new HashSet<String>();
	private int index;
	private Event lastEvent = null;

	protected AbstractState(final String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}

	protected void put(final Map<String, String> stati) {
		// TODO : loop all stats, set to null anything not in atsJson
		synchronized(this) {
			for(String key : stati.keySet()) {
				setDp(key, stati.get(key));
			}
//			setDp("queryTime", queryTimeStr, time);
		}
	}
	public void put(final String key, final String v) {
		setDp(key, v);
	}

	protected void setDp(final String key, final String v) {
		List<DataPoint> hist = stats.get(key);
		if(hist == null) {
			hist = new LinkedList<DataPoint>();
			synchronized(this) {
				stats.put(key, hist);
			}
		}
		DataPoint dp = null;
		if(!hist.isEmpty()) {
			dp = hist.get(hist.size()-1);
		}
		if(dp != null && dp.matches(v)) {
			dp.update(index);
			return;
		}
		dp = new DataPoint(v, index);
		hist.add(dp);
	}

	public List<KeyValue> getModelList() {
		final List<KeyValue> al = new ArrayList<KeyValue>();
		final TreeMap<String,List<DataPoint>> st = new TreeMap<String,List<DataPoint>>(stats);
		for(String key : st.keySet()) {
			al.add(getKeyValue(key, this));
		}
		return al;
	}

	abstract protected KeyValue getKeyValue(String key, AbstractState state);

	public Map<String, List<DataPoint>> getStats() {
		return stats;
	}
	protected Map<String, List<DataPoint>> getStats(final int hc, final String[] statList, final boolean wildcard, final boolean hidden) {
		final Map<String, List<DataPoint>> ret = new HashMap<String,List<DataPoint>>();

		synchronized(this) {
			Set<String> statSet;

			if (statList == null) {
				statSet = stats.keySet();
			} else {
				if (!wildcard) {
					statSet = new HashSet<String>(Arrays.asList(statList));
				} else {
					statSet = new HashSet<String>();

					for (String key : stats.keySet()) {
						for (String stat : statList) {
							if (key.toLowerCase().contains(stat.toLowerCase())) {
								statSet.add(key);
								break;
							}
						}
					}
				}
			}

			for (String key : statSet) {
				final List<DataPoint> list;

				if (stats.containsKey(key) && (hidden || !hiddenStats.contains(key))) {
					list = new ArrayList<DataPoint>(stats.get(key));
				} else {
					continue;
				}

				if (hc == 0 || list.size() <= 1) {
					ret.put((String) key, list);
				} else {
					/*
					 * If fromIndex == toIndex, List.subList() will return an empty list.
					 * The only way they will be equal is if the list is empty or
					 * has a single item, which is handled above.
					 */

					final int toIndex = list.size();
					final int fromIndex = Math.max(0, toIndex - hc);

					ret.put((String) key, list.subList(fromIndex, toIndex));
				}
			}
		}

		return ret;
	}
	public List<DataPoint> getDataPoints(final String key) {
		return stats.get(key);
	}
	public boolean hasValue(final String key) {
		final List<DataPoint> dps = getDataPoints(key);
		if(dps == null || dps.isEmpty()) { return false; }
		return true;
	}
	public boolean hasValue(final String key, final int index) {
		final List<DataPoint> dps = getDataPoints(key);
		if(dps == null || dps.isEmpty()) { return false; }
		if(dps.get(dps.size()-1).getIndex() >= index) {
			return true;
		}
		return false;
	}
	public String getLastValue(final String key) {
		final List<DataPoint> dps = getDataPoints(key);
		if(dps == null || dps.isEmpty()) { return null; }
		return dps.get(dps.size()-1).getValue();
	}
	public String getValue(final String key, final long targetIndex) {
		final List<DataPoint> dps = getDataPoints(key);
		if(dps == null || dps.isEmpty()) { return null; }
		for(int i = dps.size()-1; i >= 0; i--) {
			final long dpIndex = dps.get(i).getIndex();
			if(targetIndex > (dpIndex)) { return null; }
			final long span = dps.get(i).getSpan();
			if(targetIndex <= (dpIndex-span)) { continue; }
			final String v = dps.get(i).getValue();
			return v;
		}
		return null;
	}

	public boolean getBool(final String key) {
		try {
			return Boolean.parseBoolean(getLastValue(key));
		} catch (Exception e) {
			return true;
		}
	}
	public long getLong(final String key) {
		try {
			return Long.parseLong(getLastValue(key));
		} catch (Exception e) {
			return 0;
		}
	}
	public double getDouble(final String key) {
		try {
			return Double.parseDouble(getLastValue(key));
		} catch (Exception e) {
			return 0;
		}
	}
	public boolean isAvailable() {
		return getBool(IS_AVAILABLE_STR);
	}
	public Map<String, DataSummary> getSummary(final long startTime, final long endTime, final String[] stats2, final boolean wildcard, final boolean hidden) {
		final Map<String, List<DataPoint>> map = getStats(0, stats2, wildcard, hidden);
		final Map<String, DataSummary> retMap = new  HashMap<String, DataSummary>();
		final long checkPeriod = 5000;
		for(String key : map.keySet()) {
			final List<DataPoint> dpList = map.get(key);
			final DataSummary ds = new DataSummary();
			retMap.put(key, ds);
			for(DataPoint dp : dpList) {
				final int span = dp.getSpan();
				final long lastTime = getTime(dp);
				for(int i = 0; i < span; i++) {
					final long t = lastTime - (checkPeriod * (span - (i+1)));
					if(startTime != 0 && t < startTime) { continue; }
					if(endTime != -1 && t > endTime) { break; }
					try {
						ds.accumulate(dp, t);
					} catch(Exception e) {
						LOGGER.debug(e);
					}
				}
			}
		}
		return retMap;
	}
	protected long getTime(final DataPoint dp) {
		return getTime(dp.getIndex());
	}
	protected long getTime(final long index) {
		synchronized(times) {
			for(int i = 0; i < indexes.size(); i++) {
				if(indexes.get(i).longValue() == index) {
					return times.get(i).longValue();
				}
			}
		}
		return 0;
	}
	private final List<Long> times = new LinkedList<Long>();
	private final List<Long> indexes = new LinkedList<Long>();
	protected void startUpdate() {
		bringUpToDate();

		final long time = System.currentTimeMillis();
		final long removeTime = time - historyTime;
		int removeCount = 0;
		synchronized(times) {
			index++;
			times.add(new Long(time));
			indexes.add(new Long(index));
			while(times.get(0).longValue() < removeTime) {
				removeCount++;
				times.remove(0);
			}
			if(removeCount == 0) {
				return;
			}
			for(int i = 0; i < removeCount; i++) {
				indexes.remove(0);
			}
		}
		final long baseIndex = indexes.get(0);
		for(String key : stats.keySet()) {
			final List<DataPoint> l = stats.get(key);
			if(l.isEmpty()) {
				LOGGER.warn("list empty for "+key + " - "+this.id);
				continue;
			}
			while(l.get(0).getIndex() < baseIndex) {
				if(l.size() == 1) {
					LOGGER.warn(String.format("%s - %s: index %d < baseIndex %d", key, this.id, l.get(0).getIndex(), baseIndex));
					break;
				}
				synchronized(this) {
					l.remove(0);
				}
				if(l.isEmpty()) {
					LOGGER.warn("list empty for "+key + " - "+this.id);
					break;
				}
			}
		}
	}

	private void bringUpToDate() {
		for(String key : stats.keySet()) {
			final List<DataPoint> l = stats.get(key);
			final DataPoint dp = l.get(l.size()-1);
			if(dp.getIndex() != index) {
				put(key, null);
			}
		}
	}
	public void setHistoryTime(final long t) {
		if(t>0) {
			historyTime = t;
		}
	}
	public String getStatusString() {
		String error = getLastValue("error-string");
		if(error == null) {
			error = isAvailable()? "available" : "";
		}
		if(getBool("clearData")) { error = "No query"; }
		return getLastValue("status") + " - " + error;
	}

	public boolean isError() {
		if(getLastValue("error-string") != null) {
			return true;
		}
		return false;
	}

	public void setAvailable(final boolean isAvailable, final String error) {
		final boolean isHealthy = (error == null);
		boolean logChange = true;

		if (!isHealthy) {
			LOGGER.debug(String.format("Error on '%s': %s", id, error));
		}

		if (lastEvent != null && getBool(IS_HEALTHY_STR) == isHealthy && getBool(IS_AVAILABLE_STR) == isAvailable) {
			logChange = false;
		}

		put(IS_AVAILABLE_STR, String.valueOf(isAvailable));
		put(IS_HEALTHY_STR, String.valueOf(isHealthy));

		if (logChange) {
			lastEvent = Event.logStateChange(this.getId(), isAvailable, getStatusString());
		}
	}

	public JSONObject getStatsJson(final int hc, final String[] statList, final boolean wildcard, final boolean hidden) throws JSONException {
		final Map<String, List<DataPoint>> map = getStats(hc, statList, wildcard, hidden);
		final JSONObject ret = new JSONObject();
		for(String key : map.keySet()) {
			final JSONArray a = new JSONArray();
			ret.put(key, a);
			for(DataPoint dp : map.get(key)) {
				if (dp == null)
					continue;

				final JSONObject o = new JSONObject();
				/* Technically, this belongs in DataPoint, however, other logic
				 * relies on a null DataPoint value.  Because the JSON library
				 * discards a key with a null value, let's handle it here. -jse
				 */
				final String value = (dp.getValue() == null) ? "" : dp.getValue();
				o.put("value", value);
				o.put("span", dp.getSpan());
				o.put("time", getTime(dp));
				o.put("index", dp.getIndex());
				a.put(o);
			}
		}
		return ret;
	}

	public int getCurrentIndex() {
		return index;
	}

	public static List<? extends AbstractState> getStates(final Class<? extends AbstractState> c) {
		return null;
	}

}


text:
package com.hmsonline.cassandra.triggers.index;

import org.json.simple.JSONObject;

public interface Indexer {

  /**
   * Indexes the content passed into the method,<br>
   * Assumes single-level/flat structure of the JSON.
   *
   * @param columnFamily
   * @param rowKey
   * @param json
   */
  public void index(String columnFamily, String rowKey, String json);

  /**
   * Indexes the JSONObject content passed into the method.
   *
   * @param columnFamily
   * @param rowKey
   * @param json
   */
  public void index(String columnFamily, String rowKey, JSONObject json);

  /**
   * Removes a row from the index.
   */
  public void delete(String columnFamily, String rowKey);
}


text:
<?php

class Google_Service_Calendar_Error extends Google_Model
{
  public $domain;
  public $reason;

  public function setDomain($domain)
  {
    $this->domain = $domain;
  }
  public function getDomain()
  {
    return $this->domain;
  }
  public function setReason($reason)
  {
    $this->reason = $reason;
  }
  public function getReason()
  {
    return $this->reason;
  }
}


text:
using System.Diagnostics;

namespace System.Net.Sockets
{
    public static class IPEndPointExtensions
    {
        public static Internals.SocketAddress Serialize(EndPoint endpoint)
        {
            Debug.Assert(endpoint is IPEndPoint);

            return new Internals.SocketAddress(((IPEndPoint)endpoint).Address, ((IPEndPoint)endpoint).Port);
        }

        public static EndPoint Create(this EndPoint thisObj, Internals.SocketAddress socketAddress)
        {
            if (socketAddress.Family != thisObj.AddressFamily)
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), thisObj.GetType().FullName, thisObj.AddressFamily.ToString()), "socketAddress");
            }
            if (socketAddress.Size < 8)
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, thisObj.GetType().FullName), "socketAddress");
            }

            return socketAddress.GetIPEndPoint();
        }

        internal static IPEndPoint Snapshot(this IPEndPoint thisObj)
        {
            return new IPEndPoint(thisObj.Address.Snapshot(), thisObj.Port);
        }
    }
}


text:
            <img class="section-1-image" src="<?php echo base_url("assets/images/front_home/" . $front_home->id . "." . $front_home->extension . "?d=" . strtotime($front_home->modified_date)); ?>" onload="frontImageOnload(this);" />

ERICWEEPHOTO

WE ARE SPECIALIZED IN PREWEDDING PHOTOGRAPHY
BASED IN SURABAYA

OUR SELECTED WORKS

        see all of our works

            <?php
                for ($i = 0; $i < sizeof($front_works); $i++) {
                    echo "

front_works_id . "." . $front_works[$i]->front_works_extension . "?" . strtotime($front_works[$i]->modified_date)) . "' data-src='" . base_url("assets/images/front_works/" . $front_works[$i]->front_works_id . "." . $front_works[$i]->front_works_extension . "?" . strtotime($front_works[$i]->modified_date)) . "' onload='imgOnload(this);' />

";
                }
            ?>

WE WANT TO BE YOUR PARTNER

@ericweephoto

ericwicak

0852 3051 5511

CONTACT US

Powered by dnp PROJECT


text: java -jar target/ratel-server-*-SNAPSHOT.jar


text:
package quasar.ejson

import slamdata.Predef.{Char => SChar, Int => _, Map => _, _}
import quasar.contrib.matryoshka.{project, totally}
import quasar.contrib.iota.copkTraverse

import matryoshka._
import matryoshka.implicits._
import scalaz.std.list._
import scalaz.std.option._
import scalaz.syntax.traverse._

object EJson {
  def fromJson[A](f: String => A): Json[A] => EJson[A] = {
    case ObjJson(obj) => ExtEJson(Extension.fromObj(f)(obj))
    case CommonJson(c) => CommonEJson(c)
  }

  def fromCommon[T](c: Common[T])(implicit T: Corecursive.Aux[T, EJson]): T =
    CommonEJson(c).embed

  def fromExt[T](e: Extension[T])(implicit T: Corecursive.Aux[T, EJson]): T =
    ExtEJson(e).embed

  def toJson[A](f: A => Option[String]): EJson[A] => Option[Json[A]] = {
    val handleExt: Extension[A] => Option[Json[A]] = {
      case Map(xs) =>
        xs.traverse {
          case (k, v) => f(k) strengthR v
        } map (kvs => ObjJson(Obj(ListMap(kvs : _*))))

      case Int(i) =>
        some(CommonJson(Dec(BigDecimal(i))))

      case _ => none
    }

    {
      case ExtEJson(ext) => handleExt(ext)
      case CommonEJson(c) => some(CommonJson(c))
    }
  }

  def arr[T](xs: T*)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromCommon(Arr(xs.toList))

  def bool[T](b: Boolean)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromCommon(Bool(b))

  def char[T](c: SChar)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromExt(Char(c))

  def dec[T](d: BigDecimal)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromCommon(Dec(d))

  def int[T](d: BigInt)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromExt(Int(d))

  def map[T](xs: (T, T)*)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromExt(Map(xs.toList))

  def meta[T](v: T, m: T)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromExt(Meta(v, m))

  def nul[T](implicit T: Corecursive.Aux[T, EJson]): T =
    fromCommon(Null())

  def obj[T](xs: (String, T)*)(implicit T: Corecursive.Aux[T, EJson]): T =
    map((xs.map { case (s, t) => str[T](s) -> t }): _*)

  def str[T](s: String)(implicit T: Corecursive.Aux[T, EJson]): T =
    fromCommon(Str(s))

  def isNull[T](ej: T)(implicit T: Recursive.Aux[T, EJson]): Boolean =
    project[T, EJson].composePrism(optics.nul).nonEmpty(ej)

  /** Replaces `Meta` nodes with their value component. */
  def elideMetadata[T](
    implicit T: Recursive.Aux[T, EJson]
  ): EJson[T] => EJson[T] = totally {
    case ExtEJson(Meta(v, _)) => v.project
  }
}


text:
package com.codefolio.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public interface ProjectService {

	List<Map<String, Object>> selectProjectList(Map<String, Object> map) throws Exception;
	String gitStore(Map<String, Object> map,HttpServletRequest request) throws Exception;
	List<String> getfileList(Map<String, Object> map) throws Exception;
	String getSource(Map<String, Object> map) throws Exception;
}


text:
<?php

/**
 * This is the model class for table "u_mail_template_i18n"
 *
 * @author Kévin Walter <walkev13@gmail.com>
 * @version 1.0
 */
class UMailTemplateI18n extends CActiveRecord
{
    /**
     * @see CActiveRecord::scopes()
     */
    public function scopes()
    {
        return array();
    }

    /**
     * @see CActiveRecord::model()
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @see CActiveRecord::tableName()
     */
    public function tableName()
    {
        return 'u_mail_template_i18n';
    }

    /**
     * @see CModel::rules()
     */
    public function rules()
    {
        return array(
            // save
            array('u_mail_template_id, i18n_id, object, message', 'required', 'on' => array('insert', 'update')),
            array('object, message', 'required', 'on' => 'preInsert'),
            array('u_mail_template_id', 'unsafe', 'on' => array('insert', 'update')),
            array('u_mail_template_id', 'type', 'type' => 'integer'),
            array('i18n_id', 'unsafe', 'on' => array('insert', 'update')),
            array('i18n_id', 'length', 'max' => 16),
            array('i18n_id', 'type', 'type' => 'string'),
            array('object', 'length', 'max' => 255),
            array('object', 'type', 'type' => 'string'),
            array('message', 'length', 'max' => 65535),
            array('message', 'type', 'type' => 'string'),

            // search
            array('u_mail_template_id, i18n_id, object, message', 'safe', 'on' => 'search'));
    }

    /**
     * @see CActiveRecord::relations()
     */
    public function relations()
    {
        return array(
            'uMailTemplate' => array(self::BELONGS_TO, 'UMailTemplate', 'u_mail_template_id'),
            'uI18n' => array(self::BELONGS_TO, 'UI18n', 'i18n_id')
        );
    }

    /**
     * @see CModel::attributeLabels()
     */
    public function attributeLabels()
    {
        return array(
            'u_mail_template_id' => Unitkit::t('unitkit', 'u_mail_template_i18n:u_mail_template_id'),
            'i18n_id' => Unitkit::t('unitkit', 'u_mail_template_i18n:i18n_id'),
            'object' => Unitkit::t('unitkit', 'u_mail_template_i18n:object'),
            'message' => Unitkit::t('unitkit', 'u_mail_template_i18n:message')
        );
    }
}


text:
require 'spec_helper'

describe Algebra::Rename::Aliases, '#empty?' do
  subject { object.empty? }

  let(:attribute) { Attribute::Integer.new(:id)  }
  let(:object)    { described_class.new(aliases) }

  context 'when aliases are empty' do
    let(:aliases) { {} }

    it { should be(true) }
  end

  context 'when aliases are not empty' do
    let(:aliases) { { attribute => attribute.rename(:other_id) } }

    it { should be(false) }
  end
end


text:
<component name="libraryTable">
  <library name="Essentials-2.x-SNAPSHOT">
    <CLASSES>
      <root url="jar://$USER_HOME$/Downloads/Plugins/Essentials-2.x-SNAPSHOT.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/FrameAPI.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/Multiverse-Core-2.5.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/NV copy.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/NV.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/PermissionsEx-1.23.3.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/PlotMe-Core.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/PlotSquared.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/ProtocolLib.jar!/" />
      <root url="jar://$USER_HOME$/Downloads/Plugins/Vault.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
title: "HTML inside Kramdown table cells"
excerpt: "The question of how to write a list inside of a table cell with Kramdown recently came up on **Jekyll Talk** --- prompting me to look for a solution."
categories: [notes]
tags: [TIL, web development, Jekyll]
comments: true
support: true
last_modified_at: 2017-09-08T10:33:53-04:00
---

The question of how to write a list inside of a table cell with [**Kramdown**](http://kramdown.gettalong.org/) recently came up in a thread on [Jekyll Talk](http://talk.jekyllrb.com/) --- prompting me to look for a solution.

Unfortunately something like this doesn't work:

```markdown
| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         | - built-in wrapper |
|               |               | - bright color     |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         | - cures scurvy     |
|               |               | - tasty            |
```

**Kramdown** treats each new line as a row and doesn't render the bullet lists properly in the Banana and Oranges rows as can be seen below.

| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         | - built-in wrapper |
|               |               | - bright color     |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         | - cures scurvy     |
|               |               | - tasty            |

Throwing HTML at the problem doesn't quite work either.

```markdown
| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         | <ul><li>built-in wrapper</li><li>bright color</li></ul> |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         | <ul><li>cures scurvy</li><li>tasty</li></ul> |
```

Instead of rendering the HTML, it is escaped and outputted as a single line of text.

| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         |

built-in wrapper

bright color

 |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         |

cures scurvy

tasty

 |

What is needed is a way of telling **Kramdown** to leave the HTML alone and output as is. Thankfully there is such a way using the [`nomarkdown` extension](http://kramdown.gettalong.org/syntax.html#extensions).

Simply wrap the HTML with `{% raw %}{::nomarkdown} ... {:/}{% endraw %}` like so:

```markdown
| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         | {::nomarkdown}<ul><li>built-in wrapper</li><li>bright color</li></ul>{:/} |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         | {::nomarkdown}<ul><li>cures scurvy</li><li>tasty</li></ul>{:/} |
```

And the table will output as expected[^cell-content].

[^cell-content]: Be sure to keep all of your HTML on a single line for this to work properly.

| Fruit         | Price         | Advantages         |
| ------------- | ------------- | ------------------ |
| Bananas       | $1.34         | {::nomarkdown}

built-in wrapper

bright color

{:/} |
| ------------- | ------------- | ------------------ |
| Oranges       | $2.10         | {::nomarkdown}

cures scurvy

tasty

{:/} |

While not as readable as a pure Markdown solution, it gets the job done.

From what I understand [**Pandoc**](http://pandoc.org/) and [**RedCarpet**](https://github.com/vmg/redcarpet) have better support for this sort of thing if you want to use their [flavor of Markdown](http://jekyllrb.com/docs/configuration/#markdown-options).

Since Kramdown is the default renderer used by Jekyll I think I'll just suck it up and stick with this workaround for now :expressionless:.


text:
fn main() {
    // MAX overflow
    let _val = unsafe { 300u16.unchecked_mul(250u16) }; //~ ERROR: overflow executing `unchecked_mul`
}


text:
"use strict"

var h = require('./helpers.js');
var res = require('./resources.js');
var instance = require('./instance.js');

//---  INSTANCE MANAGER   ---

// Takes care of creating objects
class InstanceManager {
	constructor() {
		this.inst = [];
		this.nextid = 0;
		for(var i = 0; i<res.instanceList.length; i++) {
			if(res.instanceList[i].singleInstance) {
				this.AddInstance(i);
			}
		}
		console.log('INFO: Instances loaded: ' + this.inst.length);
	}

	MoveUser(id, from, to) {
		var iFrom = this.GetInstance(from),
			iTo = this.GetInstance(to),
			obj = iFrom.om.Get(id),
			newid = -1;
		if(obj && iFrom && iTo) {
			iFrom.RemoveUser(id);
			newid = iTo.AddUserObj(obj);
		}
		if(newid == -1)
			console.log('ERROR: failed to move user' + id+ ' from '+from+' to '+to);
		return newid;
	}

	AddUser(id, to) {

	}

	GetInstance(id) {
		return h.objectFindByKey(this.inst, 'id', id);
	}

	AddInstance(typeID) {
		if(res.instanceList[typeID].singleInstance==true) {
			if(h.indexFindByKey(this.inst, 'typeID', typeID)!= null) {
				console.log('ERROR: instance type ' + typeID+ ' already exist!');
				return -1;
			}
		}

		var i = new instance.Instance(typeID, this.nextid);
		if(i != -1) {
			this.inst.push(i);
			this.nextid++;
			return this.nextid-1;
		}

		return -1;
	}

	RemoveInstance(id) {
		this.inst[id].splice(h.indexFindByKey(this.inst, 'id', id),1);
	}

	StartInstance(id) {
		this.inst[id].Start();
	}

	StopInstance(id) {
		this.inst[id].Stop();
	}

	Init() {
	}

	Update(dt) {
		for(var i = 0; i < this.inst.length; i++) {
			if(this.inst[i].running) {
				this.inst[i].Update(dt);
			}
		}
	}

};

//---  EXPORTS   ---

module.exports = {
	InstanceManager: InstanceManager
};


text:
class FilesController < ApplicationController
  skip_before_action :authenticate_user!

  #include ActionController::Live

  # TODO: this doesn't work :(
  #def stream
    #response.headers["Content-Type"] = "text/event-stream"
    #100.times {
      #response.stream.write "<p>#{Time.now}</p>"
      #sleep 1
    #}
  #ensure
    #response.stream.close
  #end

  def big_transfer
    respond_to do |format|
      format.html {
        #headers["X-Accel-Buffering"] = "no"
        #headers["Cache-Control"] = "no-cache"
        #headers["Content-Type"] = "text/html; charset=utf-8"
        #headers["Transfer-Encoding"] = "chunked" # Chunked response header
        #headers.delete("Content-Length") # See one line above
        render stream: true
      }
      format.csv {
        headers["X-Accel-Buffering"] = "no"
        headers["Cache-Control"] = "no-cache"
        headers["Content-Type"] = "text/csv; charset=utf-8"
        #headers["Transfer-Encoding"] = "chunked" # Chunked response header
        #headers["Content-Disposition"] =
           #%(attachment; filename="report-#{Time.zone.now.to_date.to_s(:default)}.csv")
        #headers["Last-Modified"] = Time.zone.now.ctime.to_s
        #render stream: true, layout: false
        #self.response_body = build_csv_enumerator(header, data)
        self.response_body = Enumerator.new do |lines|
          sleep 5
          10.times do |x|
            lines << (1..10).to_a.shuffle.join(",")
          end
        end
      }
    end
  ensure
    response.stream.close
  end

  def big_transfer_file
    send_file '/app/app/views/files/huge_file.csv', :type => 'text/csv; charset=utf-8'
  end
end


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level3/core/nodelookupnamespaceuri04";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();
       setImplementationAttribute("namespaceAware", true);

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "hc_staff");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
    	catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*

	Using lookupNamespaceURI on an Entity and Notation node and check if the value returned is Null .

* @author IBM
* @author Neil Delima
* @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core#Node3-lookupNamespaceURI
*/
function nodelookupnamespaceuri04() {
   var success;
    if(checkInitialization(builder, "nodelookupnamespaceuri04") != null) return;
    var doc;
      var docType;
      var entity;
      var notation;
      var entitiesMap;
      var notationsMap;
      var namespaceURI;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "hc_staff");
      docType = doc.doctype;

      entitiesMap = docType.entities;

      notationsMap = docType.notations;

      entity = entitiesMap.getNamedItem("alpha");
      notation = notationsMap.getNamedItem("notation1");
      namespaceURI = entity.lookupNamespaceURI("");
      assertNull("nodelookupnamespaceuri04",namespaceURI);

}

function runTest() {
   nodelookupnamespaceuri04();
}


text:
typedef struct
{	int *elem;
	int length;
	int listsize;
}SqList;

int InitList_Sq(SqList &L)                                    //InitList_Sq() function
{   //Inititial a Sq_List
	L.elem=(int *)malloc(LIST_INIT_SIZE *sizeof(int));
	if (!L.elem) return(0);
	L.length=0;
	L.listsize=LIST_INIT_SIZE;
	return(1);
}//end of InitList_Sq() function

void main()                                                  //main() function
{
    SqList L;
	cout<<"InitList_Sq.cpp"<<endl<<"==============="<<endl<<endl;
    if(!InitList_Sq(L))
       cout<<"Failure to Initialize a Sq_List !"<<endl;
    else
       cout<<"Success to Initialize a Sq_List !"<<endl;
    getch();
}//end of main() function


text:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
app.set('port', process.env.PORT || 3000);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.enable('view cache');
app.set('layout', 'layout');
app.engine('html', require('hogan-express'));

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
// if (app.get('env') === 'development') {
//     app.use(function(err, req, res, next) {
//         res.status(err.status || 500);
//         res.render('error', {
//             message: err.message,
//             error: err
//         });
//     });
// }

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var server = app.listen(app.get('port'), function(){
    console.log('Express server listening on port ' + server.address().port);
});

// module.exports = app;


text:
// Copyright 2019 The gVisor Authors.
//
// 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.

// Package flipcall implements a protocol providing Fast Local Interprocess
// Procedure Calls between mutually-distrusting processes.
package flipcall

import (
	"fmt"
	"math"

	"golang.org/x/sys/unix"
	"gvisor.dev/gvisor/pkg/atomicbitops"
	"gvisor.dev/gvisor/pkg/memutil"
)

// An Endpoint provides the ability to synchronously transfer data and control
// to a connected peer Endpoint, which may be in another process.
//
// Since the Endpoint control transfer model is synchronous, at any given time
// one Endpoint "has control" (designated the active Endpoint), and the other
// is "waiting for control" (designated the inactive Endpoint). Users of the
// flipcall package designate one Endpoint as the client, which is initially
// active, and the other as the server, which is initially inactive. See
// flipcall_example_test.go for usage.
type Endpoint struct {
	// packet is a pointer to the beginning of the packet window. (Since this
	// is a raw OS memory mapping and not a Go object, it does not need to be
	// represented as an unsafe.Pointer.) packet is immutable.
	packet uintptr

	// dataCap is the size of the datagram part of the packet window in bytes.
	// dataCap is immutable.
	dataCap uint32

	// activeState is csClientActive if this is a client Endpoint and
	// csServerActive if this is a server Endpoint.
	activeState uint32

	// inactiveState is csServerActive if this is a client Endpoint and
	// csClientActive if this is a server Endpoint.
	inactiveState uint32

	// shutdown is non-zero if Endpoint.Shutdown() has been called, or if the
	// Endpoint has acknowledged shutdown initiated by the peer.
	shutdown atomicbitops.Uint32

	ctrl endpointControlImpl
}

// EndpointSide indicates which side of a connection an Endpoint belongs to.
type EndpointSide int

const (
	// ClientSide indicates that an Endpoint is a client (initially-active;
	// first method call should be Connect).
	ClientSide EndpointSide = iota

	// ServerSide indicates that an Endpoint is a server (initially-inactive;
	// first method call should be RecvFirst.)
	ServerSide
)

// Init must be called on zero-value Endpoints before first use. If it
// succeeds, ep.Destroy() must be called once the Endpoint is no longer in use.
//
// pwd represents the packet window used to exchange data with the peer
// Endpoint. FD may differ between Endpoints if they are in different
// processes, but must represent the same file. The packet window must
// initially be filled with zero bytes.
func (ep *Endpoint) Init(side EndpointSide, pwd PacketWindowDescriptor, opts ...EndpointOption) error {
	switch side {
	case ClientSide:
		ep.activeState = csClientActive
		ep.inactiveState = csServerActive
	case ServerSide:
		ep.activeState = csServerActive
		ep.inactiveState = csClientActive
	default:
		return fmt.Errorf("invalid EndpointSide: %v", side)
	}
	if pwd.Length < pageSize {
		return fmt.Errorf("packet window size (%d) less than minimum (%d)", pwd.Length, pageSize)
	}
	if pwd.Length > math.MaxUint32 {
		return fmt.Errorf("packet window size (%d) exceeds maximum (%d)", pwd.Length, math.MaxUint32)
	}
	m, err := memutil.MapFile(0, uintptr(pwd.Length), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED, uintptr(pwd.FD), uintptr(pwd.Offset))
	if err != nil {
		return fmt.Errorf("failed to mmap packet window: %v", err)
	}
	ep.packet = m
	ep.dataCap = uint32(pwd.Length) - uint32(PacketHeaderBytes)
	if err := ep.ctrlInit(opts...); err != nil {
		ep.unmapPacket()
		return err
	}
	return nil
}

// NewEndpoint is a convenience function that returns an initialized Endpoint
// allocated on the heap.
func NewEndpoint(side EndpointSide, pwd PacketWindowDescriptor, opts ...EndpointOption) (*Endpoint, error) {
	var ep Endpoint
	if err := ep.Init(side, pwd, opts...); err != nil {
		return nil, err
	}
	return &ep, nil
}

// An EndpointOption configures an Endpoint.
type EndpointOption interface {
	isEndpointOption()
}

// Destroy releases resources owned by ep. No other Endpoint methods may be
// called after Destroy.
func (ep *Endpoint) Destroy() {
	ep.unmapPacket()
}

func (ep *Endpoint) unmapPacket() {
	unix.RawSyscall(unix.SYS_MUNMAP, ep.packet, uintptr(ep.dataCap)+PacketHeaderBytes, 0)
	ep.packet = 0
}

// Shutdown causes concurrent and future calls to ep.Connect(), ep.SendRecv(),
// ep.RecvFirst(), and ep.SendLast(), as well as the same calls in the peer
// Endpoint, to unblock and return ShutdownErrors. It does not wait for
// concurrent calls to return. Successive calls to Shutdown have no effect.
//
// Shutdown is the only Endpoint method that may be called concurrently with
// other methods on the same Endpoint.
func (ep *Endpoint) Shutdown() {
	if ep.shutdown.Swap(1) != 0 {
		// ep.Shutdown() has previously been called.
		return
	}
	ep.ctrlShutdown()
}

// isShutdownLocally returns true if ep.Shutdown() has been called.
func (ep *Endpoint) isShutdownLocally() bool {
	return ep.shutdown.Load() != 0
}

// ShutdownError is returned by most Endpoint methods after Endpoint.Shutdown()
// has been called.
type ShutdownError struct{}

// Error implements error.Error.
func (ShutdownError) Error() string {
	return "flipcall connection shutdown"
}

// DataCap returns the maximum datagram size supported by ep. Equivalently,
// DataCap returns len(ep.Data()).
func (ep *Endpoint) DataCap() uint32 {
	return ep.dataCap
}

// Connection state.
const (
	// The client is, by definition, initially active, so this must be 0.
	csClientActive = 0
	csServerActive = 1
	csShutdown     = 2
)

// Connect blocks until the peer Endpoint has called Endpoint.RecvFirst().
//
// Preconditions:
//   - ep is a client Endpoint.
//   - ep.Connect(), ep.RecvFirst(), ep.SendRecv(), and ep.SendLast() have never
//     been called.
func (ep *Endpoint) Connect() error {
	err := ep.ctrlConnect()
	if err == nil {
		raceBecomeActive()
	}
	return err
}

// RecvFirst blocks until the peer Endpoint calls Endpoint.SendRecv(), then
// returns the datagram length specified by that call.
//
// Preconditions:
//   - ep is a server Endpoint.
//   - ep.SendRecv(), ep.RecvFirst(), and ep.SendLast() have never been called.
func (ep *Endpoint) RecvFirst() (uint32, error) {
	if err := ep.ctrlWaitFirst(); err != nil {
		return 0, err
	}
	raceBecomeActive()
	recvDataLen := ep.dataLen().Load()
	if recvDataLen > ep.dataCap {
		return 0, fmt.Errorf("received packet with invalid datagram length %d (maximum %d)", recvDataLen, ep.dataCap)
	}
	return recvDataLen, nil
}

// SendRecv transfers control to the peer Endpoint, causing its call to
// Endpoint.SendRecv() or Endpoint.RecvFirst() to return with the given
// datagram length, then blocks until the peer Endpoint calls
// Endpoint.SendRecv() or Endpoint.SendLast().
//
// Preconditions:
//   - dataLen <= ep.DataCap().
//   - No previous call to ep.SendRecv() or ep.RecvFirst() has returned an error.
//   - ep.SendLast() has never been called.
//   - If ep is a client Endpoint, ep.Connect() has previously been called and
//     returned nil.
func (ep *Endpoint) SendRecv(dataLen uint32) (uint32, error) {
	return ep.sendRecv(dataLen, false /* mayRetainP */)
}

// SendRecvFast is equivalent to SendRecv, but may prevent the caller's runtime
// P from being released, in which case the calling goroutine continues to
// count against GOMAXPROCS while waiting for the peer Endpoint to return
// control to the caller.
//
// SendRecvFast is appropriate if the peer Endpoint is expected to consistently
// return control in a short amount of time (less than ~10ms).
//
// Preconditions: As for SendRecv.
func (ep *Endpoint) SendRecvFast(dataLen uint32) (uint32, error) {
	return ep.sendRecv(dataLen, true /* mayRetainP */)
}

func (ep *Endpoint) sendRecv(dataLen uint32, mayRetainP bool) (uint32, error) {
	if dataLen > ep.dataCap {
		panic(fmt.Sprintf("attempting to send packet with datagram length %d (maximum %d)", dataLen, ep.dataCap))
	}
	// This store can safely be non-atomic: Under correct operation we should
	// be the only thread writing ep.dataLen(), and ep.ctrlRoundTrip() will
	// synchronize with the receiver. We will not read from ep.dataLen() until
	// after ep.ctrlRoundTrip(), so if the peer is mutating it concurrently then
	// they can only shoot themselves in the foot.
	ep.dataLen().RacyStore(dataLen)
	raceBecomeInactive()
	if err := ep.ctrlRoundTrip(mayRetainP); err != nil {
		return 0, err
	}
	raceBecomeActive()
	recvDataLen := ep.dataLen().Load()
	if recvDataLen > ep.dataCap {
		return 0, fmt.Errorf("received packet with invalid datagram length %d (maximum %d)", recvDataLen, ep.dataCap)
	}
	return recvDataLen, nil
}

// SendLast causes the peer Endpoint's call to Endpoint.SendRecv() or
// Endpoint.RecvFirst() to return with the given datagram length.
//
// Preconditions:
//   - dataLen <= ep.DataCap().
//   - No previous call to ep.SendRecv() or ep.RecvFirst() has returned an error.
//   - ep.SendLast() has never been called.
//   - If ep is a client Endpoint, ep.Connect() has previously been called and
//     returned nil.
func (ep *Endpoint) SendLast(dataLen uint32) error {
	if dataLen > ep.dataCap {
		panic(fmt.Sprintf("attempting to send packet with datagram length %d (maximum %d)", dataLen, ep.dataCap))
	}
	ep.dataLen().RacyStore(dataLen)
	raceBecomeInactive()
	if err := ep.ctrlWakeLast(); err != nil {
		return err
	}
	return nil
}