text:
package whelk.export.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.sql.*;

import io.prometheus.client.Counter;

public class ListMetadataFormats
{
    private final static String IDENTIFIER_PARAM = "identifier";

    private static final Counter failedRequests = Counter.build()
            .name("oaipmh_failed_listmetadataformats_requests_total").help("Total failed ListMetadataFormats requests.")
            .labelNames("error").register();

    /**
     * Verifies the integrity of a OAI-PMH request with the verb 'ListMetadataFormats' and sends a proper response.
     */
    public static void handleListMetadataFormatsRequest(HttpServletRequest request, HttpServletResponse response)
            throws IOException, XMLStreamException, SQLException
    {
        // Parse and verify the parameters allowed for this request
        String identifierUri = request.getParameter(IDENTIFIER_PARAM); // optional

        if (ResponseCommon.errorOnExtraParameters(request, response, IDENTIFIER_PARAM))
            return;

        if (identifierUri != null)
        {
            String id = null;
            try (Connection dbconn = OaiPmh.s_whelk.getStorage().getOuterConnection();
                 PreparedStatement preparedStatement = Helpers.prepareSameAsStatement(dbconn, identifierUri);
                 ResultSet resultSet = preparedStatement.executeQuery())
            {
                if (resultSet.next())
                    id = resultSet.getString("id");
            }

            try (Connection dbconn = OaiPmh.s_whelk.getStorage().getOuterConnection();
                 PreparedStatement preparedStatement = prepareMatchingDocumentStatement(dbconn, id);
                 ResultSet resultSet = preparedStatement.executeQuery())
            {
                // If there was no such document
                if (resultSet.next())
                {
                    boolean recordDeleted = resultSet.getBoolean("deleted");
                    if (recordDeleted)
                    {
                        failedRequests.labels(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST).inc();
                        ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST, "", request, response);
                        return;
                    }
                }
                else {
                    failedRequests.labels(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST).inc();
                    ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_ID_DOES_NOT_EXIST, "", request, response);
                    return;
                }
            }
        }

        // Build the xml response feed
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(response.getOutputStream());

        ResponseCommon.writeOaiPmhHeader(writer, request, true);
        writer.writeStartElement("ListMetadataFormats");

        for ( String metadataPrefix : OaiPmh.supportedFormats.keySet() )
        {
            emitMetadataFormat(metadataPrefix, writer);
        }
        writer.writeEndElement(); // ListMetadataFormats
        ResponseCommon.writeOaiPmhClose(writer, request);
    }

    private static void emitMetadataFormat(String metadataPrefix, XMLStreamWriter writer)
            throws XMLStreamException
    {
        writer.writeStartElement("metadataFormat");
        writer.writeStartElement("metadataPrefix");
        writer.writeCharacters(metadataPrefix);
        writer.writeEndElement(); // metadataPrefix

        OaiPmh.FormatDescription formatDescription = OaiPmh.supportedFormats.get(metadataPrefix);
        if (formatDescription.xmlSchema != null)
        {
            writer.writeStartElement("schema");
            writer.writeCharacters(formatDescription.xmlSchema);
            writer.writeEndElement(); // schema
        }

        if (formatDescription.xmlNamespace != null)
        {
            writer.writeStartElement("metadataNamespace");
            writer.writeCharacters(formatDescription.xmlNamespace);
            writer.writeEndElement(); // metadataNamespace
        }

        writer.writeEndElement(); // metadataFormat
    }

    private static PreparedStatement prepareMatchingDocumentStatement(Connection dbconn, String id)
            throws SQLException
    {
        String selectSQL = "SELECT deleted FROM lddb WHERE id = ? AND manifest->>'collection' <> 'definitions'";
        PreparedStatement preparedStatement = dbconn.prepareStatement(selectSQL);
        preparedStatement.setString(1, id);

        return preparedStatement;
    }
}


text:
package org.apache.loadtests.gridify;

import org.apache.ignite.Ignite;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.loadtests.GridLoadTestStatistics;
import org.apache.ignite.logger.log4j.Log4JLogger;
import org.apache.ignite.spi.communication.CommunicationSpi;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.spi.discovery.DiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.config.GridTestProperties;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
import org.apache.log4j.Level;
import org.junit.Test;

/**
 * Gridify single split load test.
 */
@GridCommonTest(group = "Load Test")
public class GridifySingleSplitLoadTest extends GridCommonAbstractTest {
    /** */
    public GridifySingleSplitLoadTest() {
        super(true);
    }

    /** {@inheritDoc} */
    @Override public String getTestIgniteInstanceName() {
        // Gridify task has empty Ignite instance name by default so we need to change it
        // here.
        return null;
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration() throws Exception {
        IgniteConfiguration cfg = super.getConfiguration();

        /* Uncomment following code if you start it manually. */
            CommunicationSpi commSpi = new TcpCommunicationSpi();

            cfg.setCommunicationSpi(commSpi);

            DiscoverySpi discoSpi = new TcpDiscoverySpi();

            cfg.setDiscoverySpi(discoSpi);
        /*
         */
        @SuppressWarnings("TypeMayBeWeakened")
        Log4JLogger log = (Log4JLogger)cfg.getGridLogger();

        log.getLogger("org.apache.ignite").setLevel(Level.INFO);

        return cfg;
    }

    /**
     * @return Time for load test in minutes.
     */
    private int getTestDurationInMinutes() {
        return Integer.valueOf(GridTestProperties.getProperty("load.test.duration"));
    }

    /**
     * @return Number of threads for the test.
     */
    private int getThreadCount() {
        return Integer.valueOf(GridTestProperties.getProperty("load.test.threadnum"));
    }

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return (getTestDurationInMinutes() + 1) * 60 * 1000;
    }

    /**
     * Load test grid.
     *
     * @throws Exception If task execution failed.
     */
    @Test
    public void testGridifyLoad() throws Exception {
        Ignite ignite = G.ignite(getTestIgniteInstanceName());

        ignite.compute().localDeployTask(GridifyLoadTestTask.class, GridifyLoadTestTask.class.getClassLoader());

        final long end = getTestDurationInMinutes() * 60 * 1000 + System.currentTimeMillis();

        // Warm up.
        new GridifyLoadTestJobTarget().executeLoadTestJob(3);

        info("Load test will be executed for '" + getTestDurationInMinutes() + "' mins.");
        info("Thread count: " + getThreadCount());

        final GridLoadTestStatistics stats = new GridLoadTestStatistics();

        GridTestUtils.runMultiThreaded(new Runnable() {
            @Override public void run() {
                while (end - System.currentTimeMillis() > 0) {
                    int levels = 3;

                    int exp = factorial(levels);

                    long start = System.currentTimeMillis();

                    int res = new GridifyLoadTestJobTarget().executeLoadTestJob(exp);

                    if (res != exp)
                        fail("Received wrong result [expected=" + exp + ", actual=" + res + ']');

                    long taskCnt = stats.onTaskCompleted(null, exp, System.currentTimeMillis() - start);

                    if (taskCnt % 500 == 0)
                        info(stats.toString());
                }
            }

        }, getThreadCount(), "grid-load-test-thread");

        info("Final test statistics: " + stats);
    }

    /**
     * Calculates factorial.
     *
     * @param num Factorial to calculate.
     * @return Factorial for the number passed in.
     */
    private int factorial(int num) {
        assert num > 0;

        return num == 1 ? 1 : num * factorial(num - 1);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by JohnGuthrie on 2/16/17.
 */

module.exports = {
  //  This would be controlled by an environment variable in a real app
  secret: 'mySecret'
};


text:
package edu.ucar.unidata.rosetta.repository.resources;

import edu.ucar.unidata.rosetta.domain.resources.Community;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * Implementation of a community DAO.
 *
 * @author oxelson@ucar.edu
 */
public class JdbcCommunityResourceDao extends JdbcDaoSupport implements CommunityResourceDao {

  /**
   * Looks up and retrieves a list of persisted Community objects.
   *
   * @return A List of all persisted communities.
   * @throws DataAccessException If unable to retrieve persisted communities.
   */
  public List<Community> getCommunities() throws DataAccessException {
    String sql =
        "SELECT communities.id, communities.name, fileTypes.name FROM communities INNER JOIN fileTypes ON communities.fileType = fileTypes.id";
    return getCommunities(sql);
  }

  /**
   * Looks up and retrieves a persisted Community object using the provided name.
   *
   * @param name The name of the community to retrieve.
   * @return The Community object matching the provided name.
   * @throws DataAccessException If unable to retrieve persisted community.
   */
  public Community lookupCommunityByName(String name) throws DataAccessException {
    String sql =
        "SELECT communities.id, communities.name, fileTypes.name FROM communities LEFT JOIN fileTypes ON communities.fileType = fileTypes.id WHERE communities.name = '"
            + name + "'";
    return getJdbcTemplate().query(sql, rs -> {
      Community comm = new Community();
      comm.setName(name);
      while (rs.next()) {
        comm.addToFileType(rs.getString(3));
      }
      return comm;
    });
  }

  /**
   * Lookups and returns a list of persisted Community objects using the provided file type.
   *
   * @param fileType The file type of the community to retrieve.
   * @return A List of persisted Communities matching the provided file type.
   * @throws DataAccessException If unable to retrieve persisted Communities.
   */
  public List<Community> lookupCommunitiesByFileType(String fileType) throws DataAccessException {
    String sql =
        "SELECT communities.id, communities.name, fileTypes.name FROM communities LEFT JOIN fileTypes ON communities.fileType = fileTypes.id WHERE fileTypes.name = '"
            + fileType + "'";
    return getCommunities(sql);
  }

  /**
   * Performs the given SQL query and returns a list of Community objects.
   *
   * @param sql The SQL select query to perform.
   * @return A list of community objects populated according to the SQL query.
   * @throws DataAccessException If unable to execute and retrieve the SQL query successfully.
   */
  private List<Community> getCommunities(String sql) throws DataAccessException {
    return getJdbcTemplate().query(sql, (ResultSetExtractor<List<Community>>) rs -> {
      Map<String, Community> communityMap = new HashMap<>();
      while (rs.next()) {
        String communityName = rs.getString(2);
        if (!communityMap.containsKey(communityName)) {
          // Update Community object.
          Community community = new Community();
          community.setId(rs.getInt(1));
          community.setName(communityName);
          community.addToFileType(rs.getString(3));
          communityMap.put(communityName, community);
        } else {
          // Create new Community object.
          Community community = communityMap.get(communityName);
          community.addToFileType(rs.getString(3));
          communityMap.replace(communityName, community);
        }
      }
      return new ArrayList<>(communityMap.values());
    });
  }
}


text:
var moment = require('moment');

module.exports.weekRange = function(value = new Date()){
  let startDate = moment(value).startOf('week').toDate();
  let endDate = moment(value).endOf('week').toDate();
  return [startDate, endDate];
}


text:
#include <alljoyn/about/AboutClient.h>
#include <alljoyn/about/AnnouncementRegistrar.h>
#include <alljoyn/Init.h>

#include <stdio.h>
#include <signal.h>
#include <iostream>
#include <iomanip>
#include <deque>
#include "AboutClientSessionListener.h"
#include "AboutClientAnnounceHandler.h"
#include "AboutClientSessionJoiner.h"

using namespace ajn;
using namespace services;

static BusAttachment* busAttachment;

static volatile sig_atomic_t s_interrupt = false;

static void CDECL_CALL SigIntHandler(int sig)
{
    QCC_UNUSED(sig);
    s_interrupt = true;
}

#define SERVICE_EXIT_OK       0
#define SERVICE_OPTION_ERROR  1
#define SERVICE_CONFIG_ERROR  2

// when pinging a remote bus wait a max of 5 seconds
#define PING_WAIT_TIME    5000

struct JoinedSession {
    qcc::String busName;
    SessionId id;
    JoinedSession(qcc::String const& busName, SessionId id) : busName(busName), id(id) { }
};

static std::deque<JoinedSession> s_joinedSessions;

void sessionJoinedCallback(qcc::String const& busName, SessionId id)
{
    /*
     * If we start calling remote methods from inside an AllJoyn callback we must
     * call the BusAttachment.EnableConcurrentCallbacks() method. There is a
     * limit to the maximum number of concurrent callbacks that can be called
     * at any time. The default limit is 4 but can be changed when the
     * BusAttachment is created.
     *
     * Depending on how many devices are advertising an Announce signal its possible
     * to quickly join lots of sessions one after another.  If we start calling
     * remote methods from the callback we could cause a deadlock situation where
     * there are no threads to respond to method responses. The threads are all
     * busy up making method calls and waiting on the response they can't not receive.
     *
     * To prevent this deadlock situation we create a list of BusAttachements
     * that have formed a session an the session id.
     *
     * This list of sessions will checked by the main wait loop to see if any
     * new session has been added to the list.  If so it will call all the methods
     * associated with the AboutSerivice in the order the sessions were formed.
     * Once that is done we leave the session.
     */
    s_joinedSessions.push_back(JoinedSession(busName, id));
}

void ViewAboutServiceData(qcc::String const& busName, SessionId id) {
    QStatus status;
    AboutClient* aboutClient = new AboutClient(*busAttachment);
    AboutIconClient* iconClient = NULL;
    bool hasIconInterface = false;
    std::cout << std::endl << busName.c_str() << " AboutClient ObjectDescriptions" << std::endl;
    std::cout << "-----------------------------------" << std::endl;
    AboutClient::ObjectDescriptions objectDescriptions;

    if (aboutClient) {
        status = aboutClient->GetObjectDescriptions(busName.c_str(), objectDescriptions, id);
        if (status != ER_OK) {
            std::cout << "Call to getObjectDescriptions failed: " << QCC_StatusText(status) << std::endl;
        } else {
            for (AboutClient::ObjectDescriptions::const_iterator it = objectDescriptions.begin();
                 it != objectDescriptions.end(); ++it) {
                qcc::String key = it->first;
                std::vector<qcc::String> vector = it->second;
                std::cout << "Object Path = " << key.c_str() << std::endl;
                for (std::vector<qcc::String>::const_iterator itv = vector.begin(); itv != vector.end(); ++itv) {
                    if (key.compare("/About/DeviceIcon") == 0 && itv->compare("org.alljoyn.Icon") == 0) {
                        hasIconInterface = true;
                    }
                    std::cout << "\tInterface = " << itv->c_str() << std::endl;
                }
            }
        }

        std::cout << std::endl << busName.c_str() << " AboutClient AboutData Get Supported Languages" << std::endl;
        std::cout << "-----------------------------------" << std::endl;

        AboutClient::AboutData aboutData;

        std::vector<qcc::String> supportedLanguages;
        status = aboutClient->GetAboutData(busName.c_str(), NULL, aboutData);
        if (status != ER_OK) {
            std::cout << "Call to getAboutData failed: "  << QCC_StatusText(status) << std::endl;
        } else {
            AboutClient::AboutData::iterator it = aboutData.find("SupportedLanguages");
            if (it != aboutData.end()) {
                const MsgArg* stringArray;
                size_t fieldListNumElements;
                status = it->second.Get("as", &fieldListNumElements, &stringArray);
                for (unsigned int i = 0; i < fieldListNumElements; i++) {
                    char* tempString;
                    stringArray[i].Get("s", &tempString);
                    supportedLanguages.push_back(tempString);
                }
            }
        }

        for (std::vector<qcc::String>::iterator it = supportedLanguages.begin(); it != supportedLanguages.end(); ++it) {
            std::cout << std::endl << busName.c_str() << " AboutClient AboutData using language=" << it->c_str() << std::endl;
            std::cout << "-----------------------------------" << std::endl;
            status = aboutClient->GetAboutData(busName.c_str(), it->c_str(), aboutData);
            if (status != ER_OK) {
                std::cout << "Call to getAboutData failed: " << QCC_StatusText(status) << std::endl;
            } else {
                for (AboutClient::AboutData::iterator itx = aboutData.begin(); itx != aboutData.end(); ++itx) {
                    qcc::String key = itx->first;
                    ajn::MsgArg value = itx->second;
                    if (value.typeId == ALLJOYN_STRING) {
                        std::cout << "Key name = " << std::setfill(' ') << std::setw(20) << std::left << key.c_str()
                                  << " value = " << value.v_string.str << std::endl;
                    } else if (value.typeId == ALLJOYN_ARRAY && value.Signature().compare("as") == 0) {
                        std::cout << "Key name = " << std::setfill(' ') << std::setw(20) << std::left << key.c_str() << " values: ";
                        const MsgArg* stringArray;
                        size_t fieldListNumElements;
                        status = value.Get("as", &fieldListNumElements, &stringArray);
                        for (unsigned int i = 0; i < fieldListNumElements; i++) {
                            char* tempString;
                            stringArray[i].Get("s", &tempString);
                            std::cout << tempString << " ";
                        }
                        std::cout << std::endl;
                    } else if (value.typeId == ALLJOYN_BYTE_ARRAY) {
                        std::cout << "Key name = " << std::setfill(' ') << std::setw(20) << std::left << key.c_str()
                                  << " value = " << std::hex << std::uppercase << std::setfill('0');
                        uint8_t* AppIdBuffer;
                        size_t numElements;
                        value.Get("ay", &numElements, &AppIdBuffer);
                        for (size_t i = 0; i < numElements; i++) {
                            std::cout <<  std::setw(2) << (unsigned int)AppIdBuffer[i];
                        }
                        std::cout << std::nouppercase << std::dec << std::endl;
                    }
                }                                     // end of for
            }
        }

        std::cout << std::endl << busName.c_str() << " AboutClient GetVersion" << std::endl;
        std::cout << "-----------------------------------" << std::endl;

        int ver = 0;
        status = aboutClient->GetVersion(busName.c_str(), ver, id);
        if (status == ER_OK) {
            std::cout << "Version = " << ver << std::endl;
        } else {
            std::cout << "Call to to getVersion failed " << QCC_StatusText(status) << std::endl;
        }
    } //if (aboutClient)

    if (hasIconInterface) {
        iconClient = new AboutIconClient(*busAttachment);
        if (iconClient) {
            std::cout << std::endl << busName.c_str() << " AboutIconClient GetUrl" << std::endl;
            std::cout << "-----------------------------------" << std::endl;

            size_t contentSize;
            qcc::String url;
            status = iconClient->GetUrl(busName.c_str(), url, id);
            if (status != ER_OK) {
                std::cout << "Call to getUrl failed: " << QCC_StatusText(status) << std::endl;
            } else {
                std::cout << "url = " << url.c_str() << std::endl;
            }

            std::cout << std::endl << busName.c_str() << " AboutIconClient GetVersion" << std::endl;
            std::cout << "-----------------------------------" << std::endl;

            int ver;
            status = iconClient->GetVersion(busName.c_str(), ver, id);
            if (status != ER_OK) {
                std::cout << "Call to getVersion failed: " << QCC_StatusText(status) << std::endl;
            } else {
                std::cout << "Version = " << ver << std::endl;
            }

            std::cout << std::endl << busName.c_str() << " AboutIconClient GetMimeType" << std::endl;
            std::cout << "-----------------------------------" << std::endl;

            qcc::String mimetype;

            status = iconClient->GetMimeType(busName.c_str(), mimetype, id);
            if (status != ER_OK) {
                std::cout << "Call to getMimetype failed: " << QCC_StatusText(status) << std::endl;
            } else {
                std::cout << "Mimetype : " << mimetype.c_str() << std::endl;
            }

            std::cout << std::endl << busName.c_str() << " AboutIconClient GetSize" << std::endl;
            std::cout << "-----------------------------------" << std::endl;

            status = iconClient->GetSize(busName.c_str(), contentSize, id);
            if (status != ER_OK) {
                std::cout << "Call to getSize failed: " << QCC_StatusText(status) << std::endl;
            } else {
                std::cout << "Size = " << contentSize << std::endl;
            }

            std::cout << std::endl << busName.c_str() << " AboutIconClient GetIcon" << std::endl;
            std::cout << "-----------------------------------" << std::endl;
            AboutIconClient::Icon icon;
            status = iconClient->GetIcon(busName.c_str(), icon, id);
            if (status != ER_OK) {
                std::cout << "Call to GetIcon failed: " << QCC_StatusText(status) << std::endl;
            } else {
                std::cout << "Content size = " << icon.contentSize << std::endl;
                std::cout << "Content :\t";
                for (size_t i = 0; i < contentSize; i++) {
                    if (i % 8 == 0 && i > 0) {
                        std::cout << "\n\t\t";
                    }
                    std::cout << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << (unsigned int)icon.content[i]
                              << std::nouppercase << std::dec;
                }
                std::cout << std::endl;
                std::cout << "Mimetype :\t" << icon.mimetype.c_str() << std::endl;
            }

        } //if (iconClient)
    } //if (isIconInterface)

    if (aboutClient) {
        delete aboutClient;
        aboutClient = NULL;
    }
    if (iconClient) {
        delete iconClient;
        iconClient = NULL;
    }
}

/*
 * Container use to pass the BusName and Port that was discoverd from the
 * Announce signal.
 */
struct PingContext {
    qcc::String busName;
    SessionPort port;
    PingContext(qcc::String bus, SessionPort p) : busName(bus), port(p) { }
};

class AboutClientPingAsyncCB : public BusAttachment::PingAsyncCB {
  public:
    void PingCB(QStatus status, void* context) {

        PingContext* ctx = (PingContext*)context;
        if (ER_OK == status) {
            status = AttemptToJoinSession(ctx->busName, ctx->port);
            if (status != ER_OK) {
                std::cout << "Unable to JoinSession with " << ctx->busName.c_str() << std::endl;
            }
        } else {
            std::cout << "Unable to ping " << ctx->busName.c_str() << ". The Bus is either unreachable or is running an version of AllJoyn older than v14.06." << std::endl;
            std::cout << "Attempting to Join a session with " << ctx->busName.c_str() << ". Just in case the remote device is running an older version of AllJoyn." << std::endl;
            /*
             * If all the services are running Code that is AllJoyn v14.06
             * or newer then nothing needs to be done.  If some of the services
             * are older then AllJoyn v14.06 the only way to find out if the
             * service is reachable is to try and create a session. Unlike calling
             * ping there is no timeout option when calling JoinSessionAsync.
             * We must wait for the default timeout (90 seconds) to know that the
             * service is unreachable.
             */
            status = AttemptToJoinSession(ctx->busName, ctx->port);
            if (status != ER_OK) {
                std::cout << "Unable to JoinSession with " << ctx->busName.c_str() << std::endl;
            }
        }
        delete ctx;
        ctx = NULL;
        delete this;
    }
  private:
    QStatus AttemptToJoinSession(qcc::String busName, SessionPort port) {
        SessionOpts opts(SessionOpts::TRAFFIC_MESSAGES, false, SessionOpts::PROXIMITY_ANY, TRANSPORT_ANY);

        AboutClientSessionListener* aboutClientSessionListener = new AboutClientSessionListener(busName);
        AboutClientSessionJoiner* joincb = new AboutClientSessionJoiner(*busAttachment, busName, sessionJoinedCallback);
        printf("Calling JoinSession BusName = %s port = %d\n", busName.c_str(), port);
        QStatus status = busAttachment->JoinSessionAsync(busName.c_str(), port, aboutClientSessionListener,
                                                         opts, joincb, aboutClientSessionListener);
        return status;
    }
};

void announceHandlerCallback(qcc::String const& busName, unsigned short port)
{
    QStatus status;
    /*
     * create a new PingContextPointer to pass to the PingAsyncCB
     */
    PingContext* pingContext = new PingContext(busName, (SessionPort)port);

    /*
     * Create an instance of the PingAsyncCB that will respond to the PingAsync
     * method call.
     */
    AboutClientPingAsyncCB* pingAsyncCB = new AboutClientPingAsyncCB();

    /*
     * Check that the unique bus name found by the Announce handler is reachable
     * before forming a session.
     *
     * It possible for the Announce signal to contain stale information.
     * By pinging the bus name we are able to determine if it is still present
     * and responsive before joining a session to it.
     *
     * PingAsync is being used in favor of the the regular ping since many announce
     * signals can come in at the same time using the non Async version of ping
     * could result in running out of concurrent callback threads which results
     * in a deadlock.
     */
    printf("Calling PingAsync BusName = %s\n", busName.c_str());
    status = busAttachment->PingAsync(busName.c_str(), PING_WAIT_TIME, pingAsyncCB, pingContext);
    /*
     * The PingAsync call failed make sure pointers are cleaned up so no memory
     * leaks occur.
     */
    if (ER_OK != status) {
        std::cout << "Unable to ping " << busName.c_str() << " reason reported: "
                  << QCC_StatusText(status);
        delete pingContext;
        pingContext = NULL;
        delete pingAsyncCB;
        pingAsyncCB = NULL;
    }
}

/** Wait for SIGINT before continuing. */
void WaitForSigInt(void)
{
    QStatus status;
    while (s_interrupt == false) {
#ifdef _WIN32
        Sleep(10);
#else
        usleep(10 * 1000);
#endif
        while ((!s_joinedSessions.empty()) && s_interrupt == false) {
            /*
             * for each session joined display all of the data associated with the
             * AboutService and the AboutIconService.  Once we have displayed the
             * about service information we simply leave the session.
             */
            ViewAboutServiceData(s_joinedSessions.front().busName, s_joinedSessions.front().id);
            status = busAttachment->LeaveSession(s_joinedSessions.front().id);
            std::cout << "Leaving session id = " << s_joinedSessions.front().id << " with " << s_joinedSessions.front().busName.c_str() << " status: " << QCC_StatusText(status) << std::endl;
            s_joinedSessions.pop_front();
        }
    }
}

/**
 *  client main function.
 *
 * @return
 *      - 0 if successful.
 *      - 1 if error.
 */
int CDECL_CALL main(int argc, char** argv, char** envArg)
{
    QCC_UNUSED(argc);
    QCC_UNUSED(argv);
    QCC_UNUSED(envArg);

    if (AllJoynInit() != ER_OK) {
        return 1;
    }
#ifdef ROUTER
    if (AllJoynRouterInit() != ER_OK) {
        AllJoynShutdown();
        return 1;
    }
#endif

    QStatus status = ER_OK;
    std::cout << "AllJoyn Library version: " << ajn::GetVersion() << std::endl;
    std::cout << "AllJoyn Library build info: " << ajn::GetBuildInfo() << std::endl;

    // Uncomment the following lines to view About Service debug information.
    //QCC_SetLogLevels("ALLJOYN_ABOUT_CLIENT=7");
    //QCC_SetLogLevels("ALLJOYN_ABOUT_ICON_CLIENT=7");
    //QCC_SetLogLevels("ALLJOYN_ABOUT_ANNOUNCE_HANDLER=7");
    //QCC_SetLogLevels("ALLJOYN_ABOUT_ANNOUNCEMENT_REGISTRAR=7");

    // Install SIGINT handler
    signal(SIGINT, SigIntHandler);

    busAttachment = new BusAttachment("AboutClientMain", true);

    status = busAttachment->Start();
    if (status == ER_OK) {
        std::cout << "BusAttachment started." << std::endl;
    } else {
        std::cout << "Unable to start BusAttachment. Status: " << QCC_StatusText(status) << std::endl;
        return 1;
    }

    status = busAttachment->Connect();

    if (ER_OK == status) {
        std::cout << "Daemon Connect succeeded." << std::endl;
    } else {
        std::cout << "Failed to connect daemon. Status: " << QCC_StatusText(status) << std::endl;
        return 1;
    }

    AboutClientAnnounceHandler* announceHandler = new AboutClientAnnounceHandler(announceHandlerCallback);
    const char* interfaces[] = { "org.alljoyn.About", "org.alljoyn.Icon" };
    AnnouncementRegistrar::RegisterAnnounceHandler(*busAttachment, *announceHandler,
                                                   interfaces, sizeof(interfaces) / sizeof(interfaces[0]));

    // Perform the service asynchronously until the user signals for an exit.
    if (ER_OK == status) {
        WaitForSigInt();
    }

    AnnouncementRegistrar::UnRegisterAnnounceHandler(*busAttachment, *announceHandler, interfaces, sizeof(interfaces) / sizeof(interfaces[0]));
    delete announceHandler;

    busAttachment->Stop();
    busAttachment->Join();
    delete busAttachment;

#ifdef ROUTER
    AllJoynRouterShutdown();
#endif
    AllJoynShutdown();
    return 0;

} /* main() */


text:
/*
 * Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
 * From ASN.1 module "IEEE1609dot2BaseTypes"
 * 	found in "1609dot2-base-types.asn"
 * 	`asn1c -gen-OER`
 */

#ifndef	_Signature_H_
#define	_Signature_H_

#include <asn_application.h>

/* Including external dependencies */
#include "EcdsaP256Signature.h"
#include <constr_CHOICE.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Dependencies */
typedef enum Signature_PR {
	Signature_PR_NOTHING,	/* No components present */
	Signature_PR_ecdsaNistP256Signature,
	Signature_PR_ecdsaBrainpoolP256r1Signature
	/* Extensions may appear below */

} Signature_PR;

/* Signature */
typedef struct Signature {
	Signature_PR present;
	union Signature_u {
		EcdsaP256Signature_t	 ecdsaNistP256Signature;
		EcdsaP256Signature_t	 ecdsaBrainpoolP256r1Signature;
		/*
		 * This type is extensible,
		 * possible extensions are below.
		 */
	} choice;

	/* Context for parsing across buffer boundaries */
	asn_struct_ctx_t _asn_ctx;
} Signature_t;

/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_Signature;
extern asn_CHOICE_specifics_t asn_SPC_Signature_specs_1;
extern asn_TYPE_member_t asn_MBR_Signature_1[2];

#ifdef __cplusplus
}
#endif

#endif	/* _Signature_H_ */
#include <asn_internal.h>


text:
using System;
using System.Collections.Generic;
using WindowsInput.Native;

namespace WindowsInput
{
    /// <summary>
    /// The service contract for a keyboard simulator for the Windows platform.
    /// </summary>
    public interface IKeyboardSimulator
    {
        /// <summary>
        /// Gets the <see cref="IMouseSimulator"/> instance for simulating Mouse input.
        /// </summary>
        /// <value>The <see cref="IMouseSimulator"/> instance.</value>
        IMouseSimulator Mouse { get; }

        /// <summary>
        /// Simulates the key down gesture for the specified key.
        /// </summary>
        /// <param name="keyCode">The <see cref="VirtualKeyCode"/> for the key.</param>
        IKeyboardSimulator KeyDown(VirtualKeyCode keyCode);

        /// <summary>
        /// Simulates the key press gesture for the specified key.
        /// </summary>
        /// <param name="keyCode">The <see cref="VirtualKeyCode"/> for the key.</param>
        IKeyboardSimulator KeyPress(VirtualKeyCode keyCode);

        /// <summary>
        /// Simulates a key press for each of the specified key codes in the order they are specified.
        /// </summary>
        /// <param name="keyCodes"></param>
        IKeyboardSimulator KeyPress(params VirtualKeyCode[] keyCodes);

        /// <summary>
        /// Simulates the key up gesture for the specified key.
        /// </summary>
        /// <param name="keyCode">The <see cref="VirtualKeyCode"/> for the key.</param>
        IKeyboardSimulator KeyUp(VirtualKeyCode keyCode);

        /// <summary>
        /// Simulates a modified keystroke where there are multiple modifiers and multiple keys like CTRL-ALT-K-C where CTRL and ALT are the modifierKeys and K and C are the keys.
        /// The flow is Modifiers KeyDown in order, Keys Press in order, Modifiers KeyUp in reverse order.
        /// </summary>
        /// <param name="modifierKeyCodes">The list of <see cref="VirtualKeyCode"/>s for the modifier keys.</param>
        /// <param name="keyCodes">The list of <see cref="VirtualKeyCode"/>s for the keys to simulate.</param>
        IKeyboardSimulator ModifiedKeyStroke(IEnumerable<VirtualKeyCode> modifierKeyCodes, IEnumerable<VirtualKeyCode> keyCodes);

        /// <summary>
        /// Simulates a modified keystroke where there are multiple modifiers and one key like CTRL-ALT-C where CTRL and ALT are the modifierKeys and C is the key.
        /// The flow is Modifiers KeyDown in order, Key Press, Modifiers KeyUp in reverse order.
        /// </summary>
        /// <param name="modifierKeyCodes">The list of <see cref="VirtualKeyCode"/>s for the modifier keys.</param>
        /// <param name="keyCode">The <see cref="VirtualKeyCode"/> for the key.</param>
        IKeyboardSimulator ModifiedKeyStroke(IEnumerable<VirtualKeyCode> modifierKeyCodes, VirtualKeyCode keyCode);

        /// <summary>
        /// Simulates a modified keystroke where there is one modifier and multiple keys like CTRL-K-C where CTRL is the modifierKey and K and C are the keys.
        /// The flow is Modifier KeyDown, Keys Press in order, Modifier KeyUp.
        /// </summary>
        /// <param name="modifierKey">The <see cref="VirtualKeyCode"/> for the modifier key.</param>
        /// <param name="keyCodes">The list of <see cref="VirtualKeyCode"/>s for the keys to simulate.</param>
        IKeyboardSimulator ModifiedKeyStroke(VirtualKeyCode modifierKey, IEnumerable<VirtualKeyCode> keyCodes);

        /// <summary>
        /// Simulates a simple modified keystroke like CTRL-C where CTRL is the modifierKey and C is the key.
        /// The flow is Modifier KeyDown, Key Press, Modifier KeyUp.
        /// </summary>
        /// <param name="modifierKeyCode">The <see cref="VirtualKeyCode"/> for the  modifier key.</param>
        /// <param name="keyCode">The <see cref="VirtualKeyCode"/> for the key.</param>
        IKeyboardSimulator ModifiedKeyStroke(VirtualKeyCode modifierKeyCode, VirtualKeyCode keyCode);

        /// <summary>
        /// Calls the Win32 SendInput method to simulate a KeyDown.
        /// </summary>
        /// <param name="dikCode">The <see cref="DirectInputKeyCode"/> to press</param>
        IKeyboardSimulator KeyDown(DirectInputKeyCode dikCode);

        /// <summary>
        /// Calls the Win32 SendInput method to simulate a KeyUp.
        /// </summary>
        /// <param name="dikCode">The <see cref="DirectInputKeyCode"/> to lift up</param>
        IKeyboardSimulator KeyUp(DirectInputKeyCode dikCode);

        /// <summary>
        /// Calls the Win32 SendInput method with a KeyDown and KeyUp message in the same input sequence in order to simulate a Key PRESS.
        /// </summary>
        /// <param name="dikCode">The <see cref="DirectInputKeyCode"/> to press</param>
        IKeyboardSimulator KeyPress(DirectInputKeyCode dikCode);

        /// <summary>
        /// Simulates a simple modified keystroke like CTRL-C where CTRL is the modifierKey and C is the key.
        /// The flow is Modifier KeyDown, Key Press, Modifier KeyUp.
        /// </summary>
        /// <param name="modifierDikCode">The modifier key</param>
        /// <param name="dikCode">The key to simulate</param>
        IKeyboardSimulator ModifiedKeyStroke(DirectInputKeyCode modifierDikCode, DirectInputKeyCode dikCode);

        /// <summary>
        /// Simulates a modified keystroke where there are multiple modifiers and one key like CTRL-ALT-C where CTRL and ALT are the modifierKeys and C is the key.
        /// The flow is Modifiers KeyDown in order, Key Press, Modifiers KeyUp in reverse order.
        /// </summary>
        /// <param name="modifierDikCodes">The list of modifier keys</param>
        /// <param name="dikCode">The key to simulate</param>
        IKeyboardSimulator ModifiedKeyStroke(IEnumerable<DirectInputKeyCode> modifierDikCodes, DirectInputKeyCode dikCode);

        /// <summary>
        /// Simulates a modified keystroke where there is one modifier and multiple keys like CTRL-K-C where CTRL is the modifierKey and K and C are the keys.
        /// The flow is Modifier KeyDown, Keys Press in order, Modifier KeyUp.
        /// </summary>
        /// <param name="modifierDikCode">The modifier key</param>
        /// <param name="dikCodes">The list of keys to simulate</param>
        IKeyboardSimulator ModifiedKeyStroke(DirectInputKeyCode modifierDikCode, IEnumerable<DirectInputKeyCode> dikCodes);

        /// <summary>
        /// Simulates a modified keystroke where there are multiple modifiers and multiple keys like CTRL-ALT-K-C where CTRL and ALT are the modifierKeys and K and C are the keys.
        /// The flow is Modifiers KeyDown in order, Keys Press in order, Modifiers KeyUp in reverse order.
        /// </summary>
        /// <param name="modifierDikCodes">The list of modifier keys</param>
        /// <param name="dikCodes">The list of keys to simulate</param>
        IKeyboardSimulator ModifiedKeyStroke(IEnumerable<DirectInputKeyCode> modifierDikCodes, IEnumerable<DirectInputKeyCode> dikCodes);

        /// <summary>
        /// Simulates uninterrupted text entry via the keyboard.
        /// </summary>
        /// <param name="text">The text to be simulated.</param>
        IKeyboardSimulator TextEntry(string text);

        /// <summary>
        /// Simulates a single character text entry via the keyboard.
        /// </summary>
        /// <param name="character">The unicode character to be simulated.</param>
        IKeyboardSimulator TextEntry(char character);

        /// <summary>
        /// Sleeps the executing thread to create a pause between simulated inputs.
        /// </summary>
        /// <param name="millsecondsTimeout">The number of milliseconds to wait.</param>
        IKeyboardSimulator Sleep(int millsecondsTimeout);

        /// <summary>
        /// Sleeps the executing thread to create a pause between simulated inputs.
        /// </summary>
        /// <param name="timeout">The time to wait.</param>
        IKeyboardSimulator Sleep(TimeSpan timeout);
    }
}


text:
.class public abstract Landroid/hardware/camera2/utils/TypeReference;
.super Ljava/lang/Object;
.source "TypeReference.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/hardware/camera2/utils/TypeReference$SpecializedTypeReference;,
        Landroid/hardware/camera2/utils/TypeReference$SpecializedBaseTypeReference;
    }
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<T:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/lang/Object;"
    }
.end annotation

# instance fields
.field private final mHash:I

.field private final mType:Ljava/lang/reflect/Type;

# direct methods
.method protected constructor <init>()V
    .registers 4

    .prologue
    .line 58
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 59
    invoke-virtual {p0}, Landroid/hardware/camera2/utils/TypeReference;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getGenericSuperclass()Ljava/lang/reflect/Type;

    move-result-object v0

    check-cast v0, Ljava/lang/reflect/ParameterizedType;

    .line 62
    .local v0, "thisType":Ljava/lang/reflect/ParameterizedType;
    invoke-interface {v0}, Ljava/lang/reflect/ParameterizedType;->getActualTypeArguments()[Ljava/lang/reflect/Type;

    move-result-object v1

    const/4 v2, 0x0

    aget-object v1, v1, v2

    iput-object v1, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    .line 73
    iget-object v1, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-static {v1}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable(Ljava/lang/reflect/Type;)Z

    move-result v1

    if-eqz v1, :cond_27

    .line 74
    new-instance v1, Ljava/lang/IllegalArgumentException;

    .line 75
    const-string/jumbo v2, "Including a type variable in a type reference is not allowed"

    .line 74
    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 77
    :cond_27
    iget-object v1, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-virtual {v1}, Ljava/lang/Object;->hashCode()I

    move-result v1

    iput v1, p0, Landroid/hardware/camera2/utils/TypeReference;->mHash:I

    .line 58
    return-void
.end method

.method private constructor <init>(Ljava/lang/reflect/Type;)V
    .registers 4
    .param p1, "type"    # Ljava/lang/reflect/Type;

    .prologue
    .line 87
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 88
    iput-object p1, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    .line 89
    iget-object v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable(Ljava/lang/reflect/Type;)Z

    move-result v0

    if-eqz v0, :cond_16

    .line 90
    new-instance v0, Ljava/lang/IllegalArgumentException;

    .line 91
    const-string/jumbo v1, "Including a type variable in a type reference is not allowed"

    .line 90
    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 93
    :cond_16
    iget-object v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-virtual {v0}, Ljava/lang/Object;->hashCode()I

    move-result v0

    iput v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mHash:I

    .line 87
    return-void
.end method

.method synthetic constructor <init>(Ljava/lang/reflect/Type;Landroid/hardware/camera2/utils/TypeReference;)V
    .registers 3
    .param p1, "type"    # Ljava/lang/reflect/Type;

    .prologue
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    invoke-direct {p0, p1}, Landroid/hardware/camera2/utils/TypeReference;-><init>(Ljava/lang/reflect/Type;)V

    return-void
.end method

.method public static containsTypeVariable(Ljava/lang/reflect/Type;)Z
    .registers 11
    .param p0, "type"    # Ljava/lang/reflect/Type;

    .prologue
    const/4 v4, 0x1

    const/4 v6, 0x0

    .line 272
    if-nez p0, :cond_5

    .line 274
    return v6

    .line 275
    :cond_5
    instance-of v5, p0, Ljava/lang/reflect/TypeVariable;

    if-eqz v5, :cond_a

    .line 279
    return v4

    .line 280
    :cond_a
    instance-of v5, p0, Ljava/lang/Class;

    if-eqz v5, :cond_22

    move-object v1, p0

    .line 289
    check-cast v1, Ljava/lang/Class;

    .line 292
    .local v1, "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    invoke-virtual {v1}, Ljava/lang/Class;->getTypeParameters()[Ljava/lang/reflect/TypeVariable;

    move-result-object v5

    array-length v5, v5

    if-eqz v5, :cond_19

    .line 293
    return v4

    .line 307
    :cond_19
    invoke-virtual {v1}, Ljava/lang/Class;->getDeclaringClass()Ljava/lang/Class;

    move-result-object v4

    invoke-static {v4}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable(Ljava/lang/reflect/Type;)Z

    move-result v4

    return v4

    .line 309
    .end local v1    # "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    :cond_22
    instance-of v5, p0, Ljava/lang/reflect/ParameterizedType;

    if-eqz v5, :cond_3e

    move-object v2, p0

    .line 319
    check-cast v2, Ljava/lang/reflect/ParameterizedType;

    .line 322
    .local v2, "p":Ljava/lang/reflect/ParameterizedType;
    invoke-interface {v2}, Ljava/lang/reflect/ParameterizedType;->getActualTypeArguments()[Ljava/lang/reflect/Type;

    move-result-object v7

    array-length v8, v7

    move v5, v6

    :goto_2f
    if-ge v5, v8, :cond_3d

    aget-object v0, v7, v5

    .line 323
    .local v0, "arg":Ljava/lang/reflect/Type;
    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable(Ljava/lang/reflect/Type;)Z

    move-result v9

    if-eqz v9, :cond_3a

    .line 324
    return v4

    .line 322
    :cond_3a
    add-int/lit8 v5, v5, 0x1

    goto :goto_2f

    .line 328
    .end local v0    # "arg":Ljava/lang/reflect/Type;
    :cond_3d
    return v6

    .line 329
    .end local v2    # "p":Ljava/lang/reflect/ParameterizedType;
    :cond_3e
    instance-of v5, p0, Ljava/lang/reflect/WildcardType;

    if-eqz v5, :cond_58

    move-object v3, p0

    .line 330
    check-cast v3, Ljava/lang/reflect/WildcardType;

    .line 349
    .local v3, "wild":Ljava/lang/reflect/WildcardType;
    invoke-interface {v3}, Ljava/lang/reflect/WildcardType;->getLowerBounds()[Ljava/lang/reflect/Type;

    move-result-object v5

    invoke-static {v5}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable([Ljava/lang/reflect/Type;)Z

    move-result v5

    if-nez v5, :cond_57

    .line 350
    invoke-interface {v3}, Ljava/lang/reflect/WildcardType;->getUpperBounds()[Ljava/lang/reflect/Type;

    move-result-object v4

    invoke-static {v4}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable([Ljava/lang/reflect/Type;)Z

    move-result v4

    .line 349
    :cond_57
    return v4

    .line 353
    .end local v3    # "wild":Ljava/lang/reflect/WildcardType;
    :cond_58
    return v6
.end method

.method private static containsTypeVariable([Ljava/lang/reflect/Type;)Z
    .registers 6
    .param p0, "typeArray"    # [Ljava/lang/reflect/Type;

    .prologue
    const/4 v2, 0x0

    .line 425
    if-nez p0, :cond_4

    .line 426
    return v2

    .line 429
    :cond_4
    array-length v3, p0

    move v1, v2

    :goto_6
    if-ge v1, v3, :cond_15

    aget-object v0, p0, v1

    .line 430
    .local v0, "type":Ljava/lang/reflect/Type;
    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->containsTypeVariable(Ljava/lang/reflect/Type;)Z

    move-result v4

    if-eqz v4, :cond_12

    .line 431
    const/4 v1, 0x1

    return v1

    .line 429
    :cond_12
    add-int/lit8 v1, v1, 0x1

    goto :goto_6

    .line 435
    .end local v0    # "type":Ljava/lang/reflect/Type;
    :cond_15
    return v2
.end method

.method public static createSpecializedTypeReference(Ljava/lang/Class;)Landroid/hardware/camera2/utils/TypeReference;
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<T:",
            "Ljava/lang/Object;",
            ">(",
            "Ljava/lang/Class",
            "<TT;>;)",
            "Landroid/hardware/camera2/utils/TypeReference",
            "<TT;>;"
        }
    .end annotation

    .prologue
    .line 123
    .local p0, "klass":Ljava/lang/Class;, "Ljava/lang/Class<TT;>;"
    new-instance v0, Landroid/hardware/camera2/utils/TypeReference$SpecializedTypeReference;

    invoke-direct {v0, p0}, Landroid/hardware/camera2/utils/TypeReference$SpecializedTypeReference;-><init>(Ljava/lang/Class;)V

    return-object v0
.end method

.method public static createSpecializedTypeReference(Ljava/lang/reflect/Type;)Landroid/hardware/camera2/utils/TypeReference;
    .registers 2
    .param p0, "type"    # Ljava/lang/reflect/Type;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/reflect/Type;",
            ")",
            "Landroid/hardware/camera2/utils/TypeReference",
            "<*>;"
        }
    .end annotation

    .prologue
    .line 140
    new-instance v0, Landroid/hardware/camera2/utils/TypeReference$SpecializedBaseTypeReference;

    invoke-direct {v0, p0}, Landroid/hardware/camera2/utils/TypeReference$SpecializedBaseTypeReference;-><init>(Ljava/lang/reflect/Type;)V

    return-object v0
.end method

.method private static final getArrayClass(Ljava/lang/Class;)Ljava/lang/Class;
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/Class",
            "<*>;)",
            "Ljava/lang/Class",
            "<*>;"
        }
    .end annotation

    .prologue
    .line 200
    .local p0, "componentType":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    const/4 v0, 0x0

    invoke-static {p0, v0}, Ljava/lang/reflect/Array;->newInstance(Ljava/lang/Class;I)Ljava/lang/Object;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v0

    return-object v0
.end method

.method private static getComponentType(Ljava/lang/reflect/Type;)Ljava/lang/reflect/Type;
    .registers 4
    .param p0, "type"    # Ljava/lang/reflect/Type;

    .prologue
    .line 217
    const-string/jumbo v0, "type must not be null"

    invoke-static {p0, v0}, Lcom/android/internal/util/Preconditions;->checkNotNull(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 219
    instance-of v0, p0, Ljava/lang/Class;

    if-eqz v0, :cond_11

    .line 220
    check-cast p0, Ljava/lang/Class;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-virtual {p0}, Ljava/lang/Class;->getComponentType()Ljava/lang/Class;

    move-result-object v0

    return-object v0

    .line 221
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_11
    instance-of v0, p0, Ljava/lang/reflect/ParameterizedType;

    if-eqz v0, :cond_17

    .line 222
    const/4 v0, 0x0

    return-object v0

    .line 223
    :cond_17
    instance-of v0, p0, Ljava/lang/reflect/GenericArrayType;

    if-eqz v0, :cond_22

    .line 224
    check-cast p0, Ljava/lang/reflect/GenericArrayType;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-interface {p0}, Ljava/lang/reflect/GenericArrayType;->getGenericComponentType()Ljava/lang/reflect/Type;

    move-result-object v0

    return-object v0

    .line 225
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_22
    instance-of v0, p0, Ljava/lang/reflect/WildcardType;

    if-eqz v0, :cond_2f

    .line 227
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    const-string/jumbo v1, "TODO: support wild card components"

    invoke-direct {v0, v1}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 228
    :cond_2f
    instance-of v0, p0, Ljava/lang/reflect/TypeVariable;

    if-eqz v0, :cond_3c

    .line 229
    new-instance v0, Ljava/lang/AssertionError;

    const-string/jumbo v1, "Type variables are not allowed in type references"

    invoke-direct {v0, v1}, Ljava/lang/AssertionError;-><init>(Ljava/lang/Object;)V

    throw v0

    .line 232
    :cond_3c
    new-instance v0, Ljava/lang/AssertionError;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "Unhandled branch to get component type for type "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/AssertionError;-><init>(Ljava/lang/Object;)V

    throw v0
.end method

.method private static final getRawType(Ljava/lang/reflect/Type;)Ljava/lang/Class;
    .registers 4
    .param p0, "type"    # Ljava/lang/reflect/Type;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/reflect/Type;",
            ")",
            "Ljava/lang/Class",
            "<*>;"
        }
    .end annotation

    .prologue
    .line 163
    if-nez p0, :cond_b

    .line 164
    new-instance v0, Ljava/lang/NullPointerException;

    const-string/jumbo v1, "type must not be null"

    invoke-direct {v0, v1}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 167
    :cond_b
    instance-of v0, p0, Ljava/lang/Class;

    if-eqz v0, :cond_12

    .line 168
    check-cast p0, Ljava/lang/Class;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    return-object p0

    .line 169
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_12
    instance-of v0, p0, Ljava/lang/reflect/ParameterizedType;

    if-eqz v0, :cond_1f

    .line 170
    check-cast p0, Ljava/lang/reflect/ParameterizedType;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-interface {p0}, Ljava/lang/reflect/ParameterizedType;->getRawType()Ljava/lang/reflect/Type;

    move-result-object v0

    check-cast v0, Ljava/lang/Class;

    return-object v0

    .line 171
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_1f
    instance-of v0, p0, Ljava/lang/reflect/GenericArrayType;

    if-eqz v0, :cond_32

    .line 172
    check-cast p0, Ljava/lang/reflect/GenericArrayType;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-interface {p0}, Ljava/lang/reflect/GenericArrayType;->getGenericComponentType()Ljava/lang/reflect/Type;

    move-result-object v0

    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->getRawType(Ljava/lang/reflect/Type;)Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->getArrayClass(Ljava/lang/Class;)Ljava/lang/Class;

    move-result-object v0

    return-object v0

    .line 173
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_32
    instance-of v0, p0, Ljava/lang/reflect/WildcardType;

    if-eqz v0, :cond_41

    .line 175
    check-cast p0, Ljava/lang/reflect/WildcardType;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-interface {p0}, Ljava/lang/reflect/WildcardType;->getUpperBounds()[Ljava/lang/reflect/Type;

    move-result-object v0

    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->getRawType([Ljava/lang/reflect/Type;)Ljava/lang/Class;

    move-result-object v0

    return-object v0

    .line 176
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_41
    instance-of v0, p0, Ljava/lang/reflect/TypeVariable;

    if-eqz v0, :cond_4e

    .line 177
    new-instance v0, Ljava/lang/AssertionError;

    const-string/jumbo v1, "Type variables are not allowed in type references"

    invoke-direct {v0, v1}, Ljava/lang/AssertionError;-><init>(Ljava/lang/Object;)V

    throw v0

    .line 180
    :cond_4e
    new-instance v0, Ljava/lang/AssertionError;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "Unhandled branch to get raw type for type "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/AssertionError;-><init>(Ljava/lang/Object;)V

    throw v0
.end method

.method private static final getRawType([Ljava/lang/reflect/Type;)Ljava/lang/Class;
    .registers 6
    .param p0, "types"    # [Ljava/lang/reflect/Type;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "([",
            "Ljava/lang/reflect/Type;",
            ")",
            "Ljava/lang/Class",
            "<*>;"
        }
    .end annotation

    .prologue
    const/4 v4, 0x0

    .line 185
    if-nez p0, :cond_4

    .line 186
    return-object v4

    .line 189
    :cond_4
    const/4 v2, 0x0

    array-length v3, p0

    :goto_6
    if-ge v2, v3, :cond_14

    aget-object v1, p0, v2

    .line 190
    .local v1, "type":Ljava/lang/reflect/Type;
    invoke-static {v1}, Landroid/hardware/camera2/utils/TypeReference;->getRawType(Ljava/lang/reflect/Type;)Ljava/lang/Class;

    move-result-object v0

    .line 191
    .local v0, "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    if-eqz v0, :cond_11

    .line 192
    return-object v0

    .line 189
    :cond_11
    add-int/lit8 v2, v2, 0x1

    goto :goto_6

    .line 196
    .end local v0    # "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    .end local v1    # "type":Ljava/lang/reflect/Type;
    :cond_14
    return-object v4
.end method

.method private static toString(Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V
    .registers 6
    .param p0, "type"    # Ljava/lang/reflect/Type;
    .param p1, "out"    # Ljava/lang/StringBuilder;

    .prologue
    .line 370
    if-nez p0, :cond_3

    .line 371
    return-void

    .line 372
    :cond_3
    instance-of v3, p0, Ljava/lang/reflect/TypeVariable;

    if-eqz v3, :cond_11

    .line 374
    check-cast p0, Ljava/lang/reflect/TypeVariable;

    .end local p0    # "type":Ljava/lang/reflect/Type;
    invoke-interface {p0}, Ljava/lang/reflect/TypeVariable;->getName()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {p1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 369
    :goto_10
    return-void

    .line 375
    .restart local p0    # "type":Ljava/lang/reflect/Type;
    :cond_11
    instance-of v3, p0, Ljava/lang/Class;

    if-eqz v3, :cond_27

    move-object v1, p0

    .line 376
    check-cast v1, Ljava/lang/Class;

    .line 378
    .local v1, "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {p1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 379
    invoke-virtual {v1}, Ljava/lang/Class;->getTypeParameters()[Ljava/lang/reflect/TypeVariable;

    move-result-object v3

    invoke-static {v3, p1}, Landroid/hardware/camera2/utils/TypeReference;->toString([Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V

    goto :goto_10

    .line 380
    .end local v1    # "klass":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    :cond_27
    instance-of v3, p0, Ljava/lang/reflect/ParameterizedType;

    if-eqz v3, :cond_43

    move-object v2, p0

    .line 382
    check-cast v2, Ljava/lang/reflect/ParameterizedType;

    .line 384
    .local v2, "p":Ljava/lang/reflect/ParameterizedType;
    invoke-interface {v2}, Ljava/lang/reflect/ParameterizedType;->getRawType()Ljava/lang/reflect/Type;

    move-result-object v3

    check-cast v3, Ljava/lang/Class;

    invoke-virtual {v3}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {p1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 385
    invoke-interface {v2}, Ljava/lang/reflect/ParameterizedType;->getActualTypeArguments()[Ljava/lang/reflect/Type;

    move-result-object v3

    invoke-static {v3, p1}, Landroid/hardware/camera2/utils/TypeReference;->toString([Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V

    goto :goto_10

    .line 386
    .end local v2    # "p":Ljava/lang/reflect/ParameterizedType;
    :cond_43
    instance-of v3, p0, Ljava/lang/reflect/GenericArrayType;

    if-eqz v3, :cond_58

    move-object v0, p0

    .line 387
    check-cast v0, Ljava/lang/reflect/GenericArrayType;

    .line 389
    .local v0, "gat":Ljava/lang/reflect/GenericArrayType;
    invoke-interface {v0}, Ljava/lang/reflect/GenericArrayType;->getGenericComponentType()Ljava/lang/reflect/Type;

    move-result-object v3

    invoke-static {v3, p1}, Landroid/hardware/camera2/utils/TypeReference;->toString(Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V

    .line 390
    const-string/jumbo v3, "[]"

    invoke-virtual {p1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    goto :goto_10

    .line 393
    .end local v0    # "gat":Ljava/lang/reflect/GenericArrayType;
    :cond_58
    invoke-virtual {p0}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {p1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    goto :goto_10
.end method

.method private static toString([Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V
    .registers 4
    .param p0, "types"    # [Ljava/lang/reflect/Type;
    .param p1, "out"    # Ljava/lang/StringBuilder;

    .prologue
    .line 398
    if-nez p0, :cond_3

    .line 399
    return-void

    .line 400
    :cond_3
    array-length v1, p0

    if-nez v1, :cond_7

    .line 401
    return-void

    .line 404
    :cond_7
    const-string/jumbo v1, "<"

    invoke-virtual {p1, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 406
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_e
    array-length v1, p0

    if-ge v0, v1, :cond_24

    .line 407
    aget-object v1, p0, v0

    invoke-static {v1, p1}, Landroid/hardware/camera2/utils/TypeReference;->toString(Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V

    .line 408
    array-length v1, p0

    add-int/lit8 v1, v1, -0x1

    if-eq v0, v1, :cond_21

    .line 409
    const-string/jumbo v1, ", "

    invoke-virtual {p1, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 406
    :cond_21
    add-int/lit8 v0, v0, 0x1

    goto :goto_e

    .line 413
    :cond_24
    const-string/jumbo v1, ">"

    invoke-virtual {p1, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 397
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .registers 4
    .param p1, "o"    # Ljava/lang/Object;

    .prologue
    .line 246
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    instance-of v0, p1, Landroid/hardware/camera2/utils/TypeReference;

    if-eqz v0, :cond_f

    iget-object v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    check-cast p1, Landroid/hardware/camera2/utils/TypeReference;

    .end local p1    # "o":Ljava/lang/Object;
    iget-object v1, p1, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-virtual {v0, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v0

    :goto_e
    return v0

    .restart local p1    # "o":Ljava/lang/Object;
    :cond_f
    const/4 v0, 0x0

    goto :goto_e
.end method

.method public getComponentType()Landroid/hardware/camera2/utils/TypeReference;
    .registers 4
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Landroid/hardware/camera2/utils/TypeReference",
            "<*>;"
        }
    .end annotation

    .prologue
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    const/4 v1, 0x0

    .line 209
    iget-object v2, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-static {v2}, Landroid/hardware/camera2/utils/TypeReference;->getComponentType(Ljava/lang/reflect/Type;)Ljava/lang/reflect/Type;

    move-result-object v0

    .line 211
    .local v0, "componentType":Ljava/lang/reflect/Type;
    if-eqz v0, :cond_d

    .line 212
    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->createSpecializedTypeReference(Ljava/lang/reflect/Type;)Landroid/hardware/camera2/utils/TypeReference;

    move-result-object v1

    .line 211
    :cond_d
    return-object v1
.end method

.method public final getRawType()Ljava/lang/Class;
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/lang/Class",
            "<-TT;>;"
        }
    .end annotation

    .prologue
    .line 159
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    iget-object v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    invoke-static {v0}, Landroid/hardware/camera2/utils/TypeReference;->getRawType(Ljava/lang/reflect/Type;)Ljava/lang/Class;

    move-result-object v0

    return-object v0
.end method

.method public getType()Ljava/lang/reflect/Type;
    .registers 2

    .prologue
    .line 84
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    iget-object v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mType:Ljava/lang/reflect/Type;

    return-object v0
.end method

.method public hashCode()I
    .registers 2

    .prologue
    .line 254
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    iget v0, p0, Landroid/hardware/camera2/utils/TypeReference;->mHash:I

    return v0
.end method

.method public toString()Ljava/lang/String;
    .registers 3

    .prologue
    .line 361
    .local p0, "this":Landroid/hardware/camera2/utils/TypeReference;, "Landroid/hardware/camera2/utils/TypeReference<TT;>;"
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    .line 362
    .local v0, "builder":Ljava/lang/StringBuilder;
    const-string/jumbo v1, "TypeReference<"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 363
    invoke-virtual {p0}, Landroid/hardware/camera2/utils/TypeReference;->getType()Ljava/lang/reflect/Type;

    move-result-object v1

    invoke-static {v1, v0}, Landroid/hardware/camera2/utils/TypeReference;->toString(Ljava/lang/reflect/Type;Ljava/lang/StringBuilder;)V

    .line 364
    const-string/jumbo v1, ">"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 366
    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method


text:
#include <stdlib.h>

#include "avl-tree.h"

/* malloc() / free() testing */

#ifdef ALLOC_TESTING
#include "alloc-testing.h"
#endif

/* AVL Tree (balanced binary search tree) */

struct _AVLTreeNode {
	AVLTreeNode *children[2];
	AVLTreeNode *parent;
	AVLTreeKey key;
	AVLTreeValue value;
	int height;
};

struct _AVLTree {
	AVLTreeNode *root_node;
	AVLTreeCompareFunc compare_func;
	unsigned int num_nodes;
};

AVLTree *avl_tree_new(AVLTreeCompareFunc compare_func)
{
	AVLTree *new_tree;

	new_tree = (AVLTree *) malloc(sizeof(AVLTree));

	if (new_tree == NULL) {
		return NULL;
	}

	new_tree->root_node = NULL;
	new_tree->compare_func = compare_func;
	new_tree->num_nodes = 0;

	return new_tree;
}

static void avl_tree_free_subtree(AVLTree *tree, AVLTreeNode *node)
{
	if (node == NULL) {
		return;
	}

	avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_LEFT]);
	avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_RIGHT]);

	free(node);
}

void avl_tree_free(AVLTree *tree)
{
	/* Destroy all nodes */

	avl_tree_free_subtree(tree, tree->root_node);

	/* Free back the main tree data structure */

	free(tree);
}

int avl_tree_subtree_height(AVLTreeNode *node)
{
	if (node == NULL) {
		return 0;
	} else {
		return node->height;
	}
}

/* Update the "height" variable of a node, from the heights of its
 * children.  This does not update the height variable of any parent
 * nodes. */

static void avl_tree_update_height(AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	int left_height, right_height;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];
	left_height = avl_tree_subtree_height(left_subtree);
	right_height = avl_tree_subtree_height(right_subtree);

	if (left_height > right_height) {
		node->height = left_height + 1;
	} else {
		node->height = right_height + 1;
	}
}

/* Find what side a node is relative to its parent */

static AVLTreeNodeSide avl_tree_node_parent_side(AVLTreeNode *node)
{
	if (node->parent->children[AVL_TREE_NODE_LEFT] == node) {
		return AVL_TREE_NODE_LEFT;
	} else {
		return AVL_TREE_NODE_RIGHT;
	}
}

/* Replace node1 with node2 at its parent. */

static void avl_tree_node_replace(AVLTree *tree, AVLTreeNode *node1,
                                  AVLTreeNode *node2)
{
	int side;

	/* Set the node's parent pointer. */

	if (node2 != NULL) {
		node2->parent = node1->parent;
	}

	/* The root node? */

	if (node1->parent == NULL) {
		tree->root_node = node2;
	} else {
		side = avl_tree_node_parent_side(node1);
		node1->parent->children[side] = node2;

		avl_tree_update_height(node1->parent);
	}
}

/* Rotate a section of the tree.  'node' is the node at the top
 * of the section to be rotated.  'direction' is the direction in
 * which to rotate the tree: left or right, as shown in the following
 * diagram:
 *
 * Left rotation:              Right rotation:
 *
 *      B                             D
 *     / \                           / \
 *    A   D                         B   E
 *       / \                       / \
 *      C   E                     A   C

 * is rotated to:              is rotated to:
 *
 *        D                           B
 *       / \                         / \
 *      B   E                       A   D
 *     / \                             / \
 *    A   C                           C   E
 */

static AVLTreeNode *avl_tree_rotate(AVLTree *tree, AVLTreeNode *node,
                                    AVLTreeNodeSide direction)
{
	AVLTreeNode *new_root;

	/* The child of this node will take its place:
	   for a left rotation, it is the right child, and vice versa. */

	new_root = node->children[1-direction];

	/* Make new_root the root, update parent pointers. */

	avl_tree_node_replace(tree, node, new_root);

	/* Rearrange pointers */

	node->children[1-direction] = new_root->children[direction];
	new_root->children[direction] = node;

	/* Update parent references */

	node->parent = new_root;

	if (node->children[1-direction] != NULL) {
		node->children[1-direction]->parent = node;
	}

	/* Update heights of the affected nodes */

	avl_tree_update_height(new_root);
	avl_tree_update_height(node);

	return new_root;
}

/* Balance a particular tree node.
 *
 * Returns the root node of the new subtree which is replacing the
 * old one. */

static AVLTreeNode *avl_tree_node_balance(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	AVLTreeNode *child;
	int diff;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];

	/* Check the heights of the child trees.  If there is an unbalance
	 * (difference between left and right > 2), then rotate nodes
	 * around to fix it */

	diff = avl_tree_subtree_height(right_subtree)
	     - avl_tree_subtree_height(left_subtree);

	if (diff >= 2) {

		/* Biased toward the right side too much. */

		child = right_subtree;

		if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])
		  < avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])) {

			/* If the right child is biased toward the left
			 * side, it must be rotated right first (double
			 * rotation) */

			avl_tree_rotate(tree, right_subtree,
			                AVL_TREE_NODE_RIGHT);
		}

		/* Perform a left rotation.  After this, the right child will
		 * take the place of this node.  Update the node pointer. */

		node = avl_tree_rotate(tree, node, AVL_TREE_NODE_LEFT);

	} else if (diff <= -2) {

		/* Biased toward the left side too much. */

		child = node->children[AVL_TREE_NODE_LEFT];

		if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])
		  < avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])) {

			/* If the left child is biased toward the right
			 * side, it must be rotated right left (double
			 * rotation) */

			avl_tree_rotate(tree, left_subtree,
			                AVL_TREE_NODE_LEFT);
		}

		/* Perform a right rotation.  After this, the left child will
		 * take the place of this node.  Update the node pointer. */

		node = avl_tree_rotate(tree, node, AVL_TREE_NODE_RIGHT);
	}

	/* Update the height of this node */

	avl_tree_update_height(node);

	return node;
}

/* Walk up the tree from the given node, performing any needed rotations */

static void avl_tree_balance_to_root(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *rover;

	rover = node;

	while (rover != NULL) {

		/* Balance this node if necessary */

		rover = avl_tree_node_balance(tree, rover);

		/* Go to this node's parent */

		rover = rover->parent;
	}
}

AVLTreeNode *avl_tree_insert(AVLTree *tree, AVLTreeKey key, AVLTreeValue value)
{
	AVLTreeNode **rover;
	AVLTreeNode *new_node;
	AVLTreeNode *previous_node;

	/* Walk down the tree until we reach a NULL pointer */

	rover = &tree->root_node;
	previous_node = NULL;

	while (*rover != NULL) {
		previous_node = *rover;
		if (tree->compare_func(key, (*rover)->key) < 0) {
			rover = &((*rover)->children[AVL_TREE_NODE_LEFT]);
		} else {
			rover = &((*rover)->children[AVL_TREE_NODE_RIGHT]);
		}
	}

	/* Create a new node.  Use the last node visited as the parent link. */

	new_node = (AVLTreeNode *) malloc(sizeof(AVLTreeNode));

	if (new_node == NULL) {
		return NULL;
	}

	new_node->children[AVL_TREE_NODE_LEFT] = NULL;
	new_node->children[AVL_TREE_NODE_RIGHT] = NULL;
	new_node->parent = previous_node;
	new_node->key = key;
	new_node->value = value;
	new_node->height = 1;

	/* Insert at the NULL pointer that was reached */

	*rover = new_node;

	/* Rebalance the tree, starting from the previous node. */

	avl_tree_balance_to_root(tree, previous_node);

	/* Keep track of the number of entries */

	++tree->num_nodes;

	return new_node;
}

/* Find the nearest node to the given node, to replace it.
 * The node returned is unlinked from the tree.
 * Returns NULL if the node has no children. */

static AVLTreeNode *avl_tree_node_get_replacement(AVLTree *tree,
                                                  AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	AVLTreeNode *result;
	AVLTreeNode *child;
	int left_height, right_height;
	int side;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];

	/* No children? */

	if (left_subtree == NULL && right_subtree == NULL) {
		return NULL;
	}

	/* Pick a node from whichever subtree is taller.  This helps to
	 * keep the tree balanced. */

	left_height = avl_tree_subtree_height(left_subtree);
	right_height = avl_tree_subtree_height(right_subtree);

	if (left_height < right_height) {
		side = AVL_TREE_NODE_RIGHT;
	} else {
		side = AVL_TREE_NODE_LEFT;
	}

	/* Search down the tree, back towards the center. */

	result = node->children[side];

	while (result->children[1-side] != NULL) {
		result = result->children[1-side];
	}

	/* Unlink the result node, and hook in its remaining child
	 * (if it has one) to replace it. */

	child = result->children[side];
	avl_tree_node_replace(tree, result, child);

	/* Update the subtree height for the result node's old parent. */

	avl_tree_update_height(result->parent);

	return result;
}

/* Remove a node from a tree */

void avl_tree_remove_node(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *swap_node;
	AVLTreeNode *balance_startpoint;
	int i;

	/* The node to be removed must be swapped with an "adjacent"
	 * node, ie. one which has the closest key to this one. Find
	 * a node to swap with. */

	swap_node = avl_tree_node_get_replacement(tree, node);

	if (swap_node == NULL) {

		/* This is a leaf node and has no children, therefore
		 * it can be immediately removed. */

		/* Unlink this node from its parent. */

		avl_tree_node_replace(tree, node, NULL);

		/* Start rebalancing from the parent of the original node */

		balance_startpoint = node->parent;

	} else {
		/* We will start rebalancing from the old parent of the
		 * swap node.  Sometimes, the old parent is the node we
		 * are removing, in which case we must start rebalancing
		 * from the swap node. */

		if (swap_node->parent == node) {
			balance_startpoint = swap_node;
		} else {
			balance_startpoint = swap_node->parent;
		}

		/* Copy references in the node into the swap node */

		for (i=0; i<2; ++i) {
			swap_node->children[i] = node->children[i];

			if (swap_node->children[i] != NULL) {
				swap_node->children[i]->parent = swap_node;
			}
		}

		swap_node->height = node->height;

		/* Link the parent's reference to this node */

		avl_tree_node_replace(tree, node, swap_node);
	}

	/* Destroy the node */

	free(node);

	/* Keep track of the number of nodes */

	--tree->num_nodes;

	/* Rebalance the tree */

	avl_tree_balance_to_root(tree, balance_startpoint);
}

/* Remove a node by key */

int avl_tree_remove(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;

	/* Find the node to remove */

	node = avl_tree_lookup_node(tree, key);

	if (node == NULL) {
		/* Not found in tree */

		return 0;
	}

	/* Remove the node */

	avl_tree_remove_node(tree, node);

	return 1;
}

AVLTreeNode *avl_tree_lookup_node(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;
	int diff;

	/* Search down the tree and attempt to find the node which
	 * has the specified key */

	node = tree->root_node;

	while (node != NULL) {

		diff = tree->compare_func(key, node->key);

		if (diff == 0) {

			/* Keys are equal: return this node */

			return node;

		} else if (diff < 0) {
			node = node->children[AVL_TREE_NODE_LEFT];
		} else {
			node = node->children[AVL_TREE_NODE_RIGHT];
		}
	}

	/* Not found */

	return NULL;
}

AVLTreeValue avl_tree_lookup(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;

	/* Find the node */

	node = avl_tree_lookup_node(tree, key);

	if (node == NULL) {
		return AVL_TREE_NULL;
	} else {
		return node->value;
	}
}

AVLTreeNode *avl_tree_root_node(AVLTree *tree)
{
	return tree->root_node;
}

AVLTreeKey avl_tree_node_key(AVLTreeNode *node)
{
	return node->key;
}

AVLTreeValue avl_tree_node_value(AVLTreeNode *node)
{
	return node->value;
}

AVLTreeNode *avl_tree_node_child(AVLTreeNode *node, AVLTreeNodeSide side)
{
	if (side == AVL_TREE_NODE_LEFT || side == AVL_TREE_NODE_RIGHT) {
		return node->children[side];
	} else {
		return NULL;
	}
}

AVLTreeNode *avl_tree_node_parent(AVLTreeNode *node)
{
	return node->parent;
}

unsigned int avl_tree_num_entries(AVLTree *tree)
{
	return tree->num_nodes;
}

static void avl_tree_to_array_add_subtree(AVLTreeNode *subtree,
                                         AVLTreeValue *array,
                                         int *index)
{
	if (subtree == NULL) {
		return;
	}

	/* Add left subtree first */

	avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_LEFT],
	                              array, index);

	/* Add this node */

	array[*index] = subtree->key;
	++*index;

	/* Finally add right subtree */

	avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_RIGHT],
	                              array, index);
}

AVLTreeValue *avl_tree_to_array(AVLTree *tree)
{
	AVLTreeValue *array;
	int index;

	/* Allocate the array */

	array = malloc(sizeof(AVLTreeValue) * tree->num_nodes);

	if (array == NULL) {
		return NULL;
	}

	index = 0;

	/* Add all keys */

	avl_tree_to_array_add_subtree(tree->root_node, array, &index);

	return array;
}


text:
const should = require('should');
const request = require('supertest');
const chai = require('chai');
const server = require('../../../app');
const schemaController = require('../../../api/controllers/json_schema');
const pscSchema = require('../../../data/mockSchemas/test-psc.json');
const documentSchema = require('../../../data/targetSchemas/document.json');
const corpusSchema = require('../../../data/targetSchemas/corpus.json');
const textDocumentSurfaceSchema = require('../../../data/targetSchemas/document_surface1d.json');
const faceDetectNotValidSchema = require('../../../data/mockSchemas/face_detect_invalid.json');
const tokenSchema = require('../../../data/mockSchemas/token.json');
const tokenNotValidSchema = require('../../../data/mockSchemas/token_invalid.json');

describe('controllers', function () {

  describe('json_schema', function () {

    describe('Unit tests on json_schema controller', function () {

      it('should return true validateMetaschema with test-psc schema', function () {
        const resp = schemaController.validateMetaschema(pscSchema);
        resp.should.eql(true);

      });

      it('should return true validateTargetType with test-psc schema', function () {
        const resp = schemaController.validateTargetType(pscSchema);
        resp.should.eql(true);
      });

      it('should return true validateSubSchema with test-psc schema', function () {
        const resp = schemaController.validateSubSchema(pscSchema, documentSchema);
        resp.should.eql(true);
      });

      it('should return true validateSearchEngineConstraints with test-psc schema', function () {
        const resp = schemaController.validateSearchEngineConstraints(pscSchema);
        resp.should.eql(true);
      });

      it('should return true validatePscConstraints with test-psc schema', function () {
        const resp = schemaController.validatePscConstraints(pscSchema);
        resp.should.eql(true);
      });

      it('should return true isSupersetOfPrimitiveArray with ([], [])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray([], []);
        resp.should.eql(true);
      });

      it('should return false isSupersetOfPrimitiveArray with ([], ["12"])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray([], ["12"]);
        resp.should.eql(false);
      });

      it('should return false isSupersetOfPrimitiveArray with (["23"], ["12"]])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray(["23"], ["12"]);
        resp.should.eql(false);
      });

      it('should return true isSupersetOfPrimitiveArray with (["23"], []])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray(["23"], []);
        resp.should.eql(true);
      });

      it('should return true isSupersetOfPrimitiveArray with (["23"], ["23"])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray(["23"], ["23"]);
        resp.should.eql(true);
      });

      it('should return true isSupersetOfPrimitiveArray with (["23", "24"], ["23"])', function () {
        const resp = schemaController.isSupersetOfPrimitiveArray(["23", "24"], ["23"]);
        resp.should.eql(true);
      });

      it('should return true isSchemaOfSimpleList with list of integer', function () {
        let primitiveListSchema = {
            "type": "array",
            "items": { "type": "integer" }
        }
        const resp = schemaController.isSchemaOfSimpleList(primitiveListSchema)
        resp.should.eql(true);
      });

      it('should return true isSchemaOfSimpleList with list of flat objects', function () {
        let surface1dOffsetsSchema = {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "begin": {
                "type": "integer",
                "minimum": 0
              },
              "end": {
                "type": "integer",
                "minimum": 0
              }
            }
          }
        }
        const resp = schemaController.isSchemaOfSimpleList(surface1dOffsetsSchema)
        resp.should.eql(true);
      });

      it('should return false isSchemaOfSimpleList with list of nested objects', function () {
        let surface1dOffsetsSchema = {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "offsets": {
                "type": "object",
                "properties": {
                  "begin": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "end": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              }
            }
          }
        }
        const resp = schemaController.isSchemaOfSimpleList(surface1dOffsetsSchema)
        resp.should.eql(false);
      });

      it('should return false isSchemaOfSimpleList with nested lists', function () {
        let surface1dOffsetsSchema = {
          "type": "array",
          "items": {
            "type": "array",
            "minItems": 1,
            "items": { "type": "integer" }
          }
        }
        const resp = schemaController.isSchemaOfSimpleList(surface1dOffsetsSchema)
        resp.should.eql(false);
      });

    });

    describe('POST /schema/validate', function () {

      it('should return an error 400 if body is missing', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(400)
          .end(function (err, res) {
            should.not.exist(err);
            done();
          });
      });

      it('should return an error 400 if schema is missing from body', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({})
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(400)
          .end(function (err, res) {
            should.not.exist(err);
            done();
          });
      });

      it('should return an error 422 if schema is an invalid json schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: { "required" : "yolo" }})
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(422)
          .end(function (err, res) {
            should.not.exist(err);
            done();
          });
      });

      it('should return { isValid : true } if schema is psc-test schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: pscSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            res.body.should.eql({ isValid: true });
            done();
          });
      });

      it('should return { isValid : true } if schema is document schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: documentSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            res.body.should.eql({ isValid: true });
            done();
          });
      });

      it('should return { isValid : true } if schema is corpus schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: corpusSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            res.body.should.eql({ isValid: true });
            done();
          });
      });

      it('should return { isValid : true } if schema is document_surface1d schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: textDocumentSurfaceSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            res.body.should.eql({ isValid: true });
            done();
          });
      });

      it('should return { isValid : false } if schema is face_detect_invalid schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: faceDetectNotValidSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            should.exist(res.body.isValid);
            res.body.isValid.should.eql(false);
            done();
          });
      });

      it('should return { isValid : true } if schema is token schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: tokenSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            res.body.should.eql({ isValid: true });
            done();
          });
      });

      it('should return { isValid : false } if schema is token_invalid schema', function (done) {

        request(server)
          .post('/psc-schema-validation-service/schema/validate')
          .send({ schema: tokenNotValidSchema })
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function (err, res) {
            should.not.exist(err);
            should.exist(res.body.isValid);
            res.body.isValid.should.eql(false);
            done();
          });
      });

    });

  });

});


text:
package org.teatrove.tea.engine;

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

import org.teatrove.tea.compiler.CompileListener;

/**
 *
 * @author Jonathan Colwell
 */
public interface TemplateCompileListener extends CompileListener {

    public Map<String, List<TemplateIssue>> getTemplateIssues();
    public Map<String, List<TemplateIssue>> getTemplateErrors();
    public Map<String, List<TemplateIssue>> getTemplateWarnings();

    /**
     * Close listener to dispose of any resources (i.e. open files) that the
     * error listener is hanging on to.
     */
    public void close();
}


text:
package it.unibz.inf.ontop.quest.scenarios;

import org.openrdf.repository.Repository;

import it.unibz.inf.ontop.sesame.SesameVirtualRepo;

public abstract class QuestVirtualScenarioParent extends QuestScenarioParent {

	public QuestVirtualScenarioParent(String testURI, String name,
			String queryFileURL, String resultFileURL, String owlFileURL,
			String obdaFileURL, String parameterFileURL) {
		super(testURI, name, queryFileURL, resultFileURL, owlFileURL, obdaFileURL, parameterFileURL);
	}

	@Override
	protected Repository createRepository() throws Exception {
//		try {
			SesameVirtualRepo repo = new SesameVirtualRepo(getName(), owlFileURL, obdaFileURL, parameterFileURL);
			repo.initialize();
			return repo;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
	}
}


text:
<ion-view id="chat" title=" {{chat.recepientname}}">

    <ion-content class="has-header has-footer bg-lightgrey" delegate-handle="chatScroll">

{{user.name}}

{{chat.recepientname}}

    </ion-content>

    <ion-footer-bar class="bar-light item-input-inset" style="border-top:1px solid #138D75;" ng-form="chatForm" novalidate>
        <button class="button button-clear button-icon ion-camera" ng-click="sendPhoto()">
    </button>

        <textarea id="textChat" ng-model="input" placeholder="Chat with {{chat.recepientname}}" required minlength="1" maxlength="1500" style="width:100%;resize: none;" msd-elastic></textarea>

        <button class="button button-clear button-icon ion-android-send button-calm" ng-class="chatForm.$invalid == false ? 'button-calm' : 'button-outline'" ng-click="sendChat(input)" ng-disabled="chatForm.$invalid">
    </button>
    </ion-footer-bar>
</ion-view>