text:
package com.galvin.interview;

/**
 * This class is an Array List implementation of the List interface.
 *
 * Your task is to implements the two add() and one remove methods below,
 * without breaking any of the existing functionality.
 */
public class ArrayList implements List {
    //the initial capacity for a new list, if none is specified
    private static final int DEFAULT_SIZE = 10;

    //the rate at which to grow the array when we run out of room. For example,
    // if we have a list of ten items, and added an eleventh, the data array
    // would be resized to 10 * GROWTH_FACTOR = 20.
    private static final int GROWTH_FACTOR = 2;

    // the array backing the list implementation
    private Object[] data;

    //the index that the next element will be insterted into. As a nice
    //side-effect, this is also the current size of the list.
    private int nextFreeIndex = 0;

    public ArrayList() {
        this( DEFAULT_SIZE );
    }

    public ArrayList( int initialCapacity ) {
        data = new Object[ initialCapacity ];
    }

    @Override
    public void add( Object target ) {
        growArrayIfNecessary();
        data[nextFreeIndex] = target;
        nextFreeIndex++;
    }

    @Override
    public void add( int index, Object target ) {
        if( index > nextFreeIndex ) {
            throw new ArrayIndexOutOfBoundsException( "Size of array exceeded" );
        }
        else if( index < 0 ) {
            throw new ArrayIndexOutOfBoundsException( "Negative index provided" );
        }
        else if( index == nextFreeIndex ) {
            add( target );
        }
        else {
            growArrayIfNecessary();
            for( int i = nextFreeIndex; i >= index && i > 0; i-- ) {
                data[i] = data[i - 1];
            }
            data[index] = target;
            nextFreeIndex++;
        }
    }

    @Override
    public void set( int index, Object target ) {
        if( index >= nextFreeIndex ) {
            throw new ArrayIndexOutOfBoundsException( "Size of array exceeded" );
        }
        else if( index < 0 ) {
            throw new ArrayIndexOutOfBoundsException( "Size of array exceeded" );
        }
        else {
            data[index] = target;
        }
    }

    @Override
    public Object get( int index ) {
        checkIndex( index );
        return data[index];
    }

    @Override
    public int indexOf( Object target ) {
        for( int i = 0; i < nextFreeIndex; i++ ) {
            if( equals( target, data[i] ) ) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public boolean contains( Object target ) {
        return indexOf( target ) != -1;
    }

    @Override
    public Object[] toArray() {
        int size = size();
        Object[] result = new Object[ size ];
        for( int i = 0; i < size; i++ ) {
            result[i] = data[i];
        }
        return result;
    }

    @Override
    public List sublist( int fromIndex, int toIndex ) {
        checkSublistIndex( fromIndex );
        checkSublistIndex( toIndex );
        if( fromIndex > toIndex ) {
            throw new IllegalArgumentException( "From index [" + fromIndex + " cannot be larger than to index [" + toIndex + "]" );
        }

        List result = new ArrayList();

        int size = toIndex - fromIndex;
        if( size > 0 ) {
            for( int i = fromIndex; i < toIndex; i++ ) {
                result.add( data[i] );
            }
        }

        return result;
    }

    @Override
    public void remove( Object target ) {
        int index = indexOf( target );
        if( index >= 0 ) {
            remove( index );
        }
    }

    @Override
    public void remove( int index ) {
        checkIndex( index );
        for( int i = index; i < nextFreeIndex; i++ ) {
            if( i + 1 < data.length ) {
                data[i] = data[i + 1];
            }
        }
        nextFreeIndex--;
        data[nextFreeIndex] = null;
    }

    @Override
    public void clear() {
        for( int i = 0; i < nextFreeIndex; i++ ) {
            data[i] = null;
        }
        nextFreeIndex = 0;
    }

    @Override
    public int size() {
        return nextFreeIndex;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    /// utility methods ///

    private void checkIndex( int index ) throws ArrayIndexOutOfBoundsException {
        if( index < 0 || index >= nextFreeIndex ) {
            throw new ArrayIndexOutOfBoundsException( "Size of array exceeded" );
        }
    }

    private void checkSublistIndex( int index ) throws ArrayIndexOutOfBoundsException {
        if( index < 0 || index > nextFreeIndex ) {
            throw new ArrayIndexOutOfBoundsException( "Size of array exceeded" );
        }
    }

    private void growArrayIfNecessary() {
        if( nextFreeIndex >= data.length ) {
            Object[] newData = new Object[ data.length * GROWTH_FACTOR ];
            for( int i = 0; i < data.length; i++ ) {
                newData[i] = data[i];
                data[i] = null;
            }
            data = newData;
            newData = null;
        }
    }

    private boolean equals( Object one, Object two ) {
        if( one == null && two == null ){
            return true;
        } else if( one == null && two != null ) {
            return false;
        } else if( one != null && two == null ) {
            return false;
        } else {
            return one.equals( two );
        }
    }
}


text:
var tokenRegex = /\{(.+?)\}/g;

function templater(source, scope){
    var result = source.replace(
        tokenRegex,
        function(match, key) {
            return typeof scope[key] !== 'undefined' ? scope[key] : match;
        }
    );

    return result;
}

module.exports = templater;

redpajama_set_name: RedPajamaGithub


text:
    <title>ProgressIDE</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="keywords" content="Component, Component based development, CBD, CBSE, tool, IDE, integrated development environment"/>

    <link rel="Stylesheet" type="text/css" href="styles/mainStyle.css" />

					            		nbsp;

				Download PRIDE

				public release

					PRIDE

An environment dedicated to the development of distributed embedded systems

PRIDE 0.5.0 ready for download

16 June 2011

PRIDE 0.5.0 is now available for Windows

PRIDE WICSA video

22 February 2011

PRIDE video that will be submitted to WICSA 2011 is now available. View

PRIDE 0.4.1 ready for download

02 February 2011

PRIDE 0.4.1 is now available

			<object width='800' height='460'>
				<param name='movie' value='http://www.youtube.com/v/Y1dkUCuqzrA?fs=1&hl=hr_HR&hd=1'></param>
				<param name='allowFullScreen' value='true'></param>
				<param name='allowscriptaccess' value='always'></param>
				<embed src='http://www.youtube.com/v/Y1dkUCuqzrA?fs=1&hl=en_US;hd=1' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='800' height='460'></embed>
			</object>

				 Message

				  Send us a message

				 Bugs

				  Report a bug

				MDH

				Mälardalen University, SWE

				Progress

				Research center

Malardalen University, School of Innovation, Design and Engineering | Box 883 | 721 23 Västerås/Eskilstuna


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.web.shared;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.util.SC;

/**
 *
 * @author kulikov
 */
public abstract class BaseCallback<T> implements AsyncCallback<T> {

    @Override
    public void onFailure(Throwable caught) {
        SC.say("Error", caught.getMessage());
    }

}


text:
/**
 @file host.c
 @brief ENet host management functions
*/
#define ENET_BUILDING_LIB 1
#include <string.h>
#include <time.h>
#include "enet/enet.h"

/** @defgroup host ENet host functions
    @{
*/

/** Creates a host for communicating to peers.

    @param address   the address at which other peers may connect to this host.  If NULL, then no peers may connect to the host.
    @param peerCount the maximum number of peers that should be allocated for the host.
    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
    @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
    @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.

    @returns the host on success and NULL on failure

    @remarks ENet will strategically drop packets on specific sides of a connection between hosts
    to ensure the host's bandwidth is not overwhelmed.  The bandwidth parameters also determine
    the window size of a connection which limits the amount of reliable packets that may be in transit
    at any given time.
*/
ENetHost *
enet_host_create (const ENetAddress * address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
{
    ENetHost * host;
    ENetPeer * currentPeer;

    if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID)
      return NULL;

    host = (ENetHost *) enet_malloc (sizeof (ENetHost));
    if (host == NULL)
      return NULL;
    memset (host, 0, sizeof (ENetHost));

    host -> peers = (ENetPeer *) enet_malloc (peerCount * sizeof (ENetPeer));
    if (host -> peers == NULL)
    {
       enet_free (host);

       return NULL;
    }
    memset (host -> peers, 0, peerCount * sizeof (ENetPeer));

    host -> socket = enet_socket_create (ENET_SOCKET_TYPE_DATAGRAM);
    if (host -> socket == ENET_SOCKET_NULL || (address != NULL && enet_socket_bind (host -> socket, address) < 0))
    {
       if (host -> socket != ENET_SOCKET_NULL)
         enet_socket_destroy (host -> socket);

       enet_free (host -> peers);
       enet_free (host);

       return NULL;
    }

    enet_socket_set_option (host -> socket, ENET_SOCKOPT_NONBLOCK, 1);
    enet_socket_set_option (host -> socket, ENET_SOCKOPT_BROADCAST, 1);
    enet_socket_set_option (host -> socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE);
    enet_socket_set_option (host -> socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE);

    if (address != NULL)
      host -> address = * address;

    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
    else
    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;

    host -> randomSeed = (enet_uint32) (size_t) host;
#ifdef WIN32
    host -> randomSeed += (enet_uint32) timeGetTime();
#else
    host -> randomSeed += (enet_uint32) time(NULL);
#endif
    host -> randomSeed = (host -> randomSeed << 16) | (host -> randomSeed >> 16);
    host -> channelLimit = channelLimit;
    host -> incomingBandwidth = incomingBandwidth;
    host -> outgoingBandwidth = outgoingBandwidth;
    host -> bandwidthThrottleEpoch = 0;
    host -> recalculateBandwidthLimits = 0;
    host -> mtu = ENET_HOST_DEFAULT_MTU;
    host -> peerCount = peerCount;
    host -> commandCount = 0;
    host -> bufferCount = 0;
    host -> checksum = NULL;
    host -> receivedAddress.host = ENET_HOST_ANY;
    host -> receivedAddress.port = 0;
    host -> receivedData = NULL;
    host -> receivedDataLength = 0;

    host -> totalSentData = 0;
    host -> totalSentPackets = 0;
    host -> totalReceivedData = 0;
    host -> totalReceivedPackets = 0;

    host -> compressor.context = NULL;
    host -> compressor.compress = NULL;
    host -> compressor.decompress = NULL;
    host -> compressor.destroy = NULL;

    host -> intercept = NULL;

    enet_list_clear (& host -> dispatchQueue);

    for (currentPeer = host -> peers;
         currentPeer < & host -> peers [host -> peerCount];
         ++ currentPeer)
    {
       currentPeer -> host = host;
       currentPeer -> incomingPeerID = currentPeer - host -> peers;
       currentPeer -> outgoingSessionID = currentPeer -> incomingSessionID = 0xFF;
       currentPeer -> data = NULL;

       enet_list_clear (& currentPeer -> acknowledgements);
       enet_list_clear (& currentPeer -> sentReliableCommands);
       enet_list_clear (& currentPeer -> sentUnreliableCommands);
       enet_list_clear (& currentPeer -> outgoingReliableCommands);
       enet_list_clear (& currentPeer -> outgoingUnreliableCommands);
       enet_list_clear (& currentPeer -> dispatchedCommands);

       enet_peer_reset (currentPeer);
    }

    return host;
}

/** Destroys the host and all resources associated with it.
    @param host pointer to the host to destroy
*/
void
enet_host_destroy (ENetHost * host)
{
    ENetPeer * currentPeer;

    if (host == NULL)
      return;

    enet_socket_destroy (host -> socket);

    for (currentPeer = host -> peers;
         currentPeer < & host -> peers [host -> peerCount];
         ++ currentPeer)
    {
       enet_peer_reset (currentPeer);
    }

    if (host -> compressor.context != NULL && host -> compressor.destroy)
      (* host -> compressor.destroy) (host -> compressor.context);

    enet_free (host -> peers);
    enet_free (host);
}

/** Initiates a connection to a foreign host.
    @param host host seeking the connection
    @param address destination for the connection
    @param channelCount number of channels to allocate
    @param data user data supplied to the receiving host
    @returns a peer representing the foreign host on success, NULL on failure
    @remarks The peer returned will have not completed the connection until enet_host_service()
    notifies of an ENET_EVENT_TYPE_CONNECT event for the peer.
*/
ENetPeer *
enet_host_connect (ENetHost * host, const ENetAddress * address, size_t channelCount, enet_uint32 data)
{
    ENetPeer * currentPeer;
    ENetChannel * channel;
    ENetProtocol command;

    if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
      channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
    else
    if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
      channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;

    for (currentPeer = host -> peers;
         currentPeer < & host -> peers [host -> peerCount];
         ++ currentPeer)
    {
       if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED)
         break;
    }

    if (currentPeer >= & host -> peers [host -> peerCount])
      return NULL;

    currentPeer -> channels = (ENetChannel *) enet_malloc (channelCount * sizeof (ENetChannel));
    if (currentPeer -> channels == NULL)
      return NULL;
    currentPeer -> channelCount = channelCount;
    currentPeer -> state = ENET_PEER_STATE_CONNECTING;
    currentPeer -> address = * address;
    currentPeer -> connectID = ++ host -> randomSeed;

    if (host -> outgoingBandwidth == 0)
      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
    else
      currentPeer -> windowSize = (host -> outgoingBandwidth /
                                    ENET_PEER_WINDOW_SIZE_SCALE) *
                                      ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;

    if (currentPeer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
      currentPeer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
    else
    if (currentPeer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;

    for (channel = currentPeer -> channels;
         channel < & currentPeer -> channels [channelCount];
         ++ channel)
    {
        channel -> outgoingReliableSequenceNumber = 0;
        channel -> outgoingUnreliableSequenceNumber = 0;
        channel -> incomingReliableSequenceNumber = 0;
        channel -> incomingUnreliableSequenceNumber = 0;

        enet_list_clear (& channel -> incomingReliableCommands);
        enet_list_clear (& channel -> incomingUnreliableCommands);

        channel -> usedReliableWindows = 0;
        memset (channel -> reliableWindows, 0, sizeof (channel -> reliableWindows));
    }

    command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
    command.header.channelID = 0xFF;
    command.connect.outgoingPeerID = ENET_HOST_TO_NET_16 (currentPeer -> incomingPeerID);
    command.connect.incomingSessionID = currentPeer -> incomingSessionID;
    command.connect.outgoingSessionID = currentPeer -> outgoingSessionID;
    command.connect.mtu = ENET_HOST_TO_NET_32 (currentPeer -> mtu);
    command.connect.windowSize = ENET_HOST_TO_NET_32 (currentPeer -> windowSize);
    command.connect.channelCount = ENET_HOST_TO_NET_32 (channelCount);
    command.connect.incomingBandwidth = ENET_HOST_TO_NET_32 (host -> incomingBandwidth);
    command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);
    command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleInterval);
    command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleAcceleration);
    command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleDeceleration);
    command.connect.connectID = currentPeer -> connectID;
    command.connect.data = ENET_HOST_TO_NET_32 (data);

    enet_peer_queue_outgoing_command (currentPeer, & command, NULL, 0, 0);

    return currentPeer;
}

/** Queues a packet to be sent to all peers associated with the host.
    @param host host on which to broadcast the packet
    @param channelID channel on which to broadcast
    @param packet packet to broadcast
*/
void
enet_host_broadcast (ENetHost * host, enet_uint8 channelID, ENetPacket * packet)
{
    ENetPeer * currentPeer;

    for (currentPeer = host -> peers;
         currentPeer < & host -> peers [host -> peerCount];
         ++ currentPeer)
    {
       if (currentPeer -> state != ENET_PEER_STATE_CONNECTED)
         continue;

       enet_peer_send (currentPeer, channelID, packet);
    }

    if (packet -> referenceCount == 0)
      enet_packet_destroy (packet);
}

/** Sets the packet compressor the host should use to compress and decompress packets.
    @param host host to enable or disable compression for
    @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled
*/
void
enet_host_compress (ENetHost * host, const ENetCompressor * compressor)
{
    if (host -> compressor.context != NULL && host -> compressor.destroy)
      (* host -> compressor.destroy) (host -> compressor.context);

    if (compressor)
      host -> compressor = * compressor;
    else
      host -> compressor.context = NULL;
}

/** Limits the maximum allowed channels of future incoming connections.
    @param host host to limit
    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
*/
void
enet_host_channel_limit (ENetHost * host, size_t channelLimit)
{
    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
    else
    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;

    host -> channelLimit = channelLimit;
}

/** Adjusts the bandwidth limits of a host.
    @param host host to adjust
    @param incomingBandwidth new incoming bandwidth
    @param outgoingBandwidth new outgoing bandwidth
    @remarks the incoming and outgoing bandwidth parameters are identical in function to those
    specified in enet_host_create().
*/
void
enet_host_bandwidth_limit (ENetHost * host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
{
    host -> incomingBandwidth = incomingBandwidth;
    host -> outgoingBandwidth = outgoingBandwidth;
    host -> recalculateBandwidthLimits = 1;
}

void
enet_host_bandwidth_throttle (ENetHost * host)
{
    enet_uint32 timeCurrent = enet_time_get (),
           elapsedTime = timeCurrent - host -> bandwidthThrottleEpoch,
           peersTotal = 0,
           dataTotal = 0,
           peersRemaining,
           bandwidth,
           throttle = 0,
           bandwidthLimit = 0;
    int needsAdjustment;
    ENetPeer * peer;
    ENetProtocol command;

    if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
      return;

    for (peer = host -> peers;
         peer < & host -> peers [host -> peerCount];
         ++ peer)
    {
        if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
          continue;

        ++ peersTotal;
        dataTotal += peer -> outgoingDataTotal;
    }

    if (peersTotal == 0)
      return;

    peersRemaining = peersTotal;
    needsAdjustment = 1;

    if (host -> outgoingBandwidth == 0)
      bandwidth = ~0;
    else
      bandwidth = (host -> outgoingBandwidth * elapsedTime) / 1000;

    while (peersRemaining > 0 && needsAdjustment != 0)
    {
        needsAdjustment = 0;

        if (dataTotal < bandwidth)
          throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
        else
          throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;

        for (peer = host -> peers;
             peer < & host -> peers [host -> peerCount];
             ++ peer)
        {
            enet_uint32 peerBandwidth;

            if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
                peer -> incomingBandwidth == 0 ||
                peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
              continue;

            peerBandwidth = (peer -> incomingBandwidth * elapsedTime) / 1000;
            if ((throttle * peer -> outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
              continue;

            peer -> packetThrottleLimit = (peerBandwidth *
                                            ENET_PEER_PACKET_THROTTLE_SCALE) / peer -> outgoingDataTotal;

            if (peer -> packetThrottleLimit == 0)
              peer -> packetThrottleLimit = 1;

            if (peer -> packetThrottle > peer -> packetThrottleLimit)
              peer -> packetThrottle = peer -> packetThrottleLimit;

            peer -> outgoingBandwidthThrottleEpoch = timeCurrent;

            needsAdjustment = 1;
            -- peersRemaining;
            bandwidth -= peerBandwidth;
            dataTotal -= peerBandwidth;
        }
    }

    if (peersRemaining > 0)
    for (peer = host -> peers;
         peer < & host -> peers [host -> peerCount];
         ++ peer)
    {
        if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
            peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
          continue;

        peer -> packetThrottleLimit = throttle;

        if (peer -> packetThrottle > peer -> packetThrottleLimit)
          peer -> packetThrottle = peer -> packetThrottleLimit;
    }

    if (host -> recalculateBandwidthLimits)
    {
       host -> recalculateBandwidthLimits = 0;

       peersRemaining = peersTotal;
       bandwidth = host -> incomingBandwidth;
       needsAdjustment = 1;

       if (bandwidth == 0)
         bandwidthLimit = 0;
       else
       while (peersRemaining > 0 && needsAdjustment != 0)
       {
           needsAdjustment = 0;
           bandwidthLimit = bandwidth / peersRemaining;

           for (peer = host -> peers;
                peer < & host -> peers [host -> peerCount];
                ++ peer)
           {
               if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
                   peer -> incomingBandwidthThrottleEpoch == timeCurrent)
                 continue;

               if (peer -> outgoingBandwidth > 0 &&
                   peer -> outgoingBandwidth >= bandwidthLimit)
                 continue;

               peer -> incomingBandwidthThrottleEpoch = timeCurrent;

               needsAdjustment = 1;
               -- peersRemaining;
               bandwidth -= peer -> outgoingBandwidth;
           }
       }

       for (peer = host -> peers;
            peer < & host -> peers [host -> peerCount];
            ++ peer)
       {
           if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
             continue;

           command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
           command.header.channelID = 0xFF;
           command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);

           if (peer -> incomingBandwidthThrottleEpoch == timeCurrent)
             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (peer -> outgoingBandwidth);
           else
             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (bandwidthLimit);

           enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0);
       }
    }

    host -> bandwidthThrottleEpoch = timeCurrent;

    for (peer = host -> peers;
         peer < & host -> peers [host -> peerCount];
         ++ peer)
    {
        peer -> incomingDataTotal = 0;
        peer -> outgoingDataTotal = 0;
    }
}

/** @} */


text:
package laberinto;

import java.util.List;

public abstract class Estrategia {
	private int actual;
	protected Bicho bicho;
	protected List<Orientacion> orientaciones;
	void dormir(){};
	void atacar(){};
	void caminar(){};
	public Bicho getBicho(){return bicho;}
	public void setBicho(Bicho bicho){
		this.bicho=bicho;
		orientaciones=bicho.posicion.getOrientaciones();
	}
	void accion(){
		this.caminar();
		this.dormir();
	}
}


text:
class Range(object):
    """
        Represents the Range header.

        This only represents ``bytes`` ranges, which are the only kind
        specified in HTTP.  This can represent multiple sets of ranges,
        but no place else is this multi-range facility supported.
    """

    def __init__(self, ranges): # expect non-inclusive
        for begin, end in ranges:
            assert end is None or end >= 0, "Bad ranges: %r" % ranges
        self.ranges = ranges

    def satisfiable(self, length):
        """
            Returns true if this range can be satisfied by the resource
            with the given byte length.
        """
        return self.range_for_length(length) is not None

    def range_for_length(self, length):
        """
            *If* there is only one range, and *if* it is satisfiable by
            the given length, then return a (begin, end) non-inclusive range
            of bytes to serve.  Otherwise return None
        """
        if length is None or len(self.ranges) != 1:
            return None
        start, end = self.ranges[0]
        if end is None:
            end = length
            if start < 0:
                start += length
        if _is_content_range_valid(start, end, length):
            stop = min(end, length)
            return (start, stop)
        else:
            return None

    def content_range(self, length):
        """
            Works like range_for_length; returns None or a ContentRange object

            You can use it like::

                response.content_range = req.range.content_range(response.content_length)

            Though it's still up to you to actually serve that content range!
        """
        range = self.range_for_length(length)
        if range is None:
            return None
        return ContentRange(range[0], range[1], length)

    def __str__(self):
        parts = []
        for begin, end in self.ranges:
            if end is None:
                if begin >= 0:
                    parts.append('%s-' % begin)
                else:
                    parts.append(str(begin))
            else:
                if begin < 0:
                    raise ValueError("(%r, %r) should have a non-negative first value"
                                    % (begin, end))
                if end <= 0:
                    raise ValueError("(%r, %r) should have a positive second value"
                                    % (begin, end))
                parts.append('%s-%s' % (begin, end-1))
        return 'bytes=%s' % ','.join(parts)

    def __repr__(self):
        return '<%s ranges=%s>' % (
            self.__class__.__name__,
            ', '.join(map(repr, self.ranges)))

    @classmethod
    def parse(cls, header):
        """
            Parse the header; may return None if header is invalid
        """
        bytes = cls.parse_bytes(header)
        if bytes is None:
            return None
        units, ranges = bytes
        if units != 'bytes' or ranges is None:
            return None
        return cls(ranges)

    @staticmethod
    def parse_bytes(header):
        """
            Parse a Range header into (bytes, list_of_ranges).
            ranges in list_of_ranges are non-inclusive (unlike the HTTP header).

            Will return None if the header is invalid
        """
        if not header:
            raise TypeError("The header must not be empty")
        ranges = []
        last_end = 0
        try:
            (units, range) = header.split("=", 1)
            units = units.strip().lower()
            for item in range.split(","):
                if '-' not in item:
                    raise ValueError()
                if item.startswith('-'):
                    # This is a range asking for a trailing chunk.
                    if last_end < 0:
                        raise ValueError('too many end ranges')
                    begin = int(item)
                    end = None
                    last_end = -1
                else:
                    (begin, end) = item.split("-", 1)
                    begin = int(begin)
                    if begin < last_end or last_end < 0:
                        raise ValueError('begin<last_end, or last_end<0')
                    if end.strip():
                        end = int(end) + 1 # return val is non-inclusive
                        if begin >= end:
                            raise ValueError('begin>end')
                    else:
                        end = None
                    last_end = end
                ranges.append((begin, end))
        except ValueError, e:
            # In this case where the Range header is malformed,
            # section 14.16 says to treat the request as if the
            # Range header was not present.  How do I log this?
            return None
        return (units, ranges)

class ContentRange(object):

    """
    Represents the Content-Range header

    This header is ``start-stop/length``, where start-stop and length
    can be ``*`` (represented as None in the attributes).
    """

    def __init__(self, start, stop, length):
        if not _is_content_range_valid(start, stop, length):
            raise ValueError("Bad start:stop/length: %r-%r/%r" % (start, stop, length))
        self.start = start
        self.stop = stop # this is python-style range end (non-inclusive)
        self.length = length

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self)

    def __str__(self):
        if self.length is None:
            length = '*'
        else:
            length = self.length
        if self.start is None:
            assert self.stop is None
            return 'bytes */%s' % length
        stop = self.stop - 1 # from non-inclusive to HTTP-style
        return 'bytes %s-%s/%s' % (self.start, stop, length)

    def __iter__(self):
        """
            Mostly so you can unpack this, like:

                start, stop, length = res.content_range
        """
        return iter([self.start, self.stop, self.length])

    @classmethod
    def parse(cls, value):
        """
            Parse the header.  May return None if it cannot parse.
        """
        if value is None:
            return None
        value = value.strip()
        if not value.startswith('bytes '):
            # Unparseable
            return None
        value = value[len('bytes '):].strip()
        if '/' not in value:
            # Invalid, no length given
            return None
        range, length = value.split('/', 1)
        if length == '*':
            length = None
        elif length.isdigit():
            length = int(length)
        else:
            return None # invalid length

        if range == '*':
            return cls(None, None, length)
        elif '-' not in range:
            # Invalid, no range
            return None
        else:
            start, stop = range.split('-', 1)
            try:
                start = int(start)
                stop = int(stop)
                stop += 1 # convert to non-inclusive
            except ValueError:
                # Parse problem
                return None
            if _is_content_range_valid(start, stop, length, response=True):
                return cls(start, stop, length)
            return None

def _is_content_range_valid(start, stop, length, response=False):
    if (start is None) != (stop is None):
        return False
    elif start is None:
        return length is None or length >= 0
    elif length is None:
        return 0 <= start < stop
    elif start >= stop:
        return False
    elif response and stop > length:
        # "content-range: bytes 0-50/10" is invalid for a response
        # "range: bytes 0-50" is valid for a request to a 10-bytes entity
        return False
    else:
        return 0 <= start < length


text:
from magpie.api import schemas as s
from magpie.utils import get_logger

LOGGER = get_logger(__name__)

def includeme(config):
    LOGGER.info("Adding API resource...")
    # Add all the rest api routes
    config.add_route(**s.service_api_route_info(s.PermissionsAPI))
    config.add_route(**s.service_api_route_info(s.ResourcesAPI))
    config.add_route(**s.service_api_route_info(s.ResourceAPI))
    config.add_route(**s.service_api_route_info(s.ResourcePermissionsAPI))
    config.add_route(**s.service_api_route_info(s.ResourceTypesAPI))

    config.scan()


text:
var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    path = require('path'),
    tree = require('../tree'),
    install = require('./install');

exports.summary = 'Builds a project and reports a list of its exports';

exports.usage = '' +
'kanso ls [PATH]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to inspect (defaults to ".")\n' +
'\n' +
'Options:\n' +
'  --name              Show package name\n' +
'  --version           Show package version\n' +
'  --description       Show package description\n' +
'  --preprocessors     List preprocessors\n' +
'  --postprocessors    List postprocessors\n' +
'  --attachments       List attachment filenames\n' +
'  --properties        List other properties added the design doc\n' +
'  --shows             List show functions\n' +
'  --lists             List list function\n' +
'  --updates           List update functions\n' +
'  --filters           List filter functions\n' +
'  --views             List views\n' +
'  --rewrites          List rewrites (by "from" pattern)\n' +
'  --validate          Test whether validate_doc_update exists\n' +
'  --size              Calculate size of design doc including dependencies\n' +
'  --dependencies      List dependencies\n' +
'\n' +
'If no options are specified, shows all information';

exports.indent = '    ';

function print_heading(str, count) {
    console.log(
        logger.bold(str) +
        (count === undefined ? '': ' (' + count + ')')
    );
}

// prints property names without recursing
function shallow_print(title, obj) {
    if (!obj) {
        return;
    }
    var names = Object.keys(obj);
    if (!names.length) {
        return;
    }
    print_heading(title, names.length);
    names.forEach(function (name) {
        console.log(exports.indent + name);
    });
    console.log('');
}

function deep_print(obj, ignores, path) {
    path = path || [];
    var str = '';

    var sp = exports.indent;
    for (var i = 0; i < path.length; i++) {
        sp += exports.indent;
    }
    for (var k in obj) {
        var kp = path.concat([k]);
        if (ignores.indexOf(kp.join('.')) === -1) {
            if (typeof obj[k] === 'object') {
                if (obj[k] instanceof Array) {
                    str += sp + k + ' (' + k.length + ')\n';
                }
                else {
                    str += sp + k + '\n';
                    str += deep_print(obj[k], ignores, path.concat([k]));
                }
            }
            else {
                str += sp + k + '\n';
            }
        }
    }
    return str;
}

/**
 * Prints a hierarchy. Parameter 2 and 3 should not be passed by user code.
 * @param obj an object with a structure like: {title: 'root', children: [{title: 'ch1', children: []}, {title: 'ch2', children: []}]}
 */
function hierarchy_print(obj, thislevellog, nextlevellog) {
    var joinedprint = function () {
        console.log(Array.prototype.slice.call(arguments).join(''));
    };
    thislevellog = thislevellog || joinedprint;
    nextlevellog = nextlevellog || joinedprint;

    if (typeof obj.title !== 'undefined') {
        if (obj.children.length > 0) {
            thislevellog(logger.yellow('┬─ ') + obj.title);
        } else {
            thislevellog(logger.yellow('── ') + obj.title);
        }
    }
    for (var i = 0; i < obj.children.length - 1; i++) {
        hierarchy_print(obj.children[i], nextlevellog.bind(null, logger.yellow('├─')), nextlevellog.bind(null, logger.yellow('│ ')));
    }
    if (obj.children.length > 0) {
        hierarchy_print(obj.children[obj.children.length - 1], nextlevellog.bind(null, logger.yellow('└─')), nextlevellog.bind(null, '  '));
    }
};

exports.run = function (settings, args) {
    var options = {
        name:           {match: '--name'},
        version:        {match: '--version'},
        description:    {match: '--description'},
        preprocessors:  {match: '--preprocessors'},
        postprocessors: {match: '--postprocessors'},
        attachments:    {match: '--attachments'},
        properties:     {match: '--properties'},
        shows:          {match: '--shows'},
        lists:          {match: '--lists'},
        updates:        {match: '--updates'},
        filters:        {match: '--filters'},
        views:          {match: '--views'},
        rewrites:       {match: '--rewrites'},
        validate:       {match: '--validate'},
        size:           {match: '--size'},
        dependencies:   {match: '--dependencies'},
    };
    var a = argParse(args, options);
    var dir = utils.abspath(a.positional[0] || '.');
    kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
        if (err) {
            return logger.error(err);
        }
        var custom = false;

        for (var k in options) {
            custom = custom || a.options[k];
        }

        // suppress logger output
        logger.level = 'error';

        exports.loadApp(dir, {}, settings, function (err, doc, cfg) {
            if (err) {
                return logger.error(err);
            }

            if (!custom || a.options.name) {
                console.log(logger.bold('Name: ') + cfg.name + '\n');
            }
            if (!custom || a.options.version) {
                console.log(logger.bold('Version: ') + cfg.version + '\n');
            }
            if (!custom || a.options.description) {
                console.log(
                    logger.bold('Description') + '\n' +
                    cfg.description + '\n'
                );
            }

            if (!custom || a.options.preprocessors) {
                shallow_print('Preprocessors', cfg.preprocessors);
            }
            if (!custom || a.options.postprocessors) {
                shallow_print('Postprocessors', cfg.postprocessors);
            }

            if (!custom || a.options.attachments) {
                shallow_print('Attachments', doc._attachments);
            }
            if (!custom || a.options.properties) {
                var str = deep_print(doc, [
                    // ignore these properties
                    '_attachments',
                    'shows',
                    'lists',
                    'updates',
                    'filters',
                    'rewrites',
                    'views',
                    'validate_doc_update'
                ]);
                if (str) {
                    print_heading('Extra properties');
                    console.log(str);
                }
            }

            if (!custom || a.options.shows) {
                shallow_print('Show functions', doc.shows);
            }
            if (!custom || a.options.lists) {
                shallow_print('List functions', doc.lists);
            }
            if (!custom || a.options.updates) {
                shallow_print('Update functions', doc.updates);
            }
            if (!custom || a.options.filters) {
                shallow_print('Filter functions', doc.filters);
            }

            if (!custom || a.options.views) {
                shallow_print('Views', doc.views);
            }

            if (!custom || a.options.rewrites) {
                // Rewrites
                if (doc.rewrites && doc.rewrites.length) {
                    print_heading('Rewrites', doc.rewrites.length);
                    doc.rewrites.forEach(function (r) {
                        console.log(exports.indent + r.from);
                    });
                    console.log('');
                }
            }

            if (!custom || a.options.validate) {
                if (doc.validate_doc_update || custom) {
                    console.log(
                        logger.bold('Validate doc update: ') +
                        Boolean(doc.validate_doc_update).toString() +
                        '\n'
                    );
                }
            }

            if (!custom || a.options.size) {
                function roundNum(num, dec) {
                    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
                }

                var str = JSON.stringify(doc);
                var bytes = Buffer.byteLength(str, 'utf8');

                var num = bytes;
                var units = 'Bytes';

                if (num > 1024) {
                    num = num / 1024;
                    units = 'KB'
                }
                if (num > 1024) {
                    num = num / 1024;
                    units = 'MB'
                }

                console.log(
                    logger.bold('Size: ') +
                    roundNum(num, 2) + ' ' + units +
                    ' (including dependencies)\n'
                );
            }

            if (!custom || a.options.dependencies) {
                console.log(logger.bold('Dependencies'));

                tree.build({config: cfg, source: 'root'}, [install.dirSource(path.join(dir, 'packages'))], function (err, packages) {
                    var mypkgs = [];
                    var attach_deps = function (key, obj, ptree) {
                        for (var k in ptree) {
                            if (ptree.hasOwnProperty(k) && ptree[k].ranges && ptree[k].ranges.hasOwnProperty(key)) {
                                obj.push({
                                    "title"   : logger.cyan(k) + (ptree[k].ranges[key] ? logger.cyan('(' + ptree[k].ranges[key] + ')') : '') + '@' + ptree[k].current_version,
                                    "children": []
                                });
                                attach_deps(k, obj[obj.length -1 ].children, ptree);
                            }
                        }
                    };
                    attach_deps(cfg.name, mypkgs, packages);

                    hierarchy_print({children: mypkgs});

                    console.log('');
                    logger.end();
                });
            } else {
                logger.end();
            }
        });
    });
};

exports.loadApp = function (dir, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    packages.load(dir, paths, null, options, callback);
};


text:
@class CDMModel, DVTNotificationToken, DVTToolsVersion, DVTVersion, NSArray, NSSet, NSString, XDDiagramStorage;

@interface IDEDataModelDocument : IDEEditorDocument <NSKeyedUnarchiverDelegate, IDEDocumentStructureProviding, XDPMModelDelegate, DVTTextFindable, DVTTextReplacable>
{
    CDMModel *_model;
    XDDiagramStorage *_diagramStorage;
    DVTVersion *_iOSDeploymentVersion;
    DVTVersion *_macOSDeploymentVersion;
    DVTToolsVersion *_documentToolsVersion;
    DVTVersion *_documentVersion;
    DVTNotificationToken *_documentDidSaveToken;
    BOOL _supportsMacOSDeployment;
    BOOL _supportsIOSDeployment;
}

+ (id)keyPathsForValuesAffectingValueForKey:(id)arg1;
+ (id)wrapperByCopyingContentsAtPath:(id)arg1 error:(id *)arg2;
+ (BOOL)writeModel:(id)arg1 inDocument:(id)arg2 atPath:(id)arg3 error:(id *)arg4;
+ (BOOL)_shouldShowUtilititesAreaAtLoadForSimpleFilesFocusedWorkspace;
+ (BOOL)isNativeType:(id)arg1;
+ (id)writableTypes;
+ (id)readableTypes;
+ (id)currentDocumentVersion;
+ (id)currentToolsVersion;
+ (id)currentSystemVersion;
@property BOOL supportsMacOSDeployment; // @synthesize supportsMacOSDeployment=_supportsMacOSDeployment;
@property BOOL supportsIOSDeployment; // @synthesize supportsIOSDeployment=_supportsIOSDeployment;
@property(copy, nonatomic) DVTVersion *macOSDeploymentVersion; // @synthesize macOSDeploymentVersion=_macOSDeploymentVersion;
@property(copy, nonatomic) DVTVersion *iOSDeploymentVersion; // @synthesize iOSDeploymentVersion=_iOSDeploymentVersion;
@property(copy, nonatomic) DVTVersion *documentVersion; // @synthesize documentVersion=_documentVersion;
@property(retain, nonatomic) DVTToolsVersion *documentToolsVersion; // @synthesize documentToolsVersion=_documentToolsVersion;
@property(retain) CDMModel *model; // @synthesize model=_model;
- (void).cxx_destruct;
- (BOOL)replaceFindResults:(id)arg1 withString:(id)arg2 withError:(id *)arg3;
- (id)findStringMatchingDescriptor:(id)arg1 backwards:(BOOL)arg2 from:(id)arg3 to:(id)arg4;
- (void)updateChangeCount:(unsigned long long)arg1;
@property(readonly) NSArray *ideTopLevelStructureObjects;
- (BOOL)writeToURL:(id)arg1 ofType:(id)arg2 forSaveOperation:(unsigned long long)arg3 originalContentsURL:(id)arg4 error:(id *)arg5;
- (BOOL)writeToURL:(id)arg1 ofType:(id)arg2 error:(id *)arg3;
- (BOOL)writeModel:(id)arg1 atPath:(id)arg2 error:(id *)arg3;
- (BOOL)writeLegacyModel:(id)arg1 atPath:(id)arg2 error:(id *)arg3;
- (BOOL)writeElementsOfModel:(id)arg1 diagramStorage:(id)arg2 mappings:(id)arg3 atPath:(id)arg4 error:(id *)arg5;
- (BOOL)writeLayoutOfModelDiagramStorage:(id)arg1 mappings:(id)arg2 atPath:(id)arg3 error:(id *)arg4;
- (id)modelDataFromModel:(id)arg1;
- (void)documentFormatDidChange:(id)arg1;
- (void)updateSourceControlForPath:(id)arg1;
- (BOOL)readFromURL:(id)arg1 ofType:(id)arg2 error:(id *)arg3;
- (BOOL)loadModelFromURL:(id)arg1 error:(id *)arg2;
- (BOOL)canSave;
- (void)setDiagramStorage:(id)arg1;
- (id)diagramStorage;
- (void)setSupportsDeployment:(BOOL)arg1 forPlatformFamily:(id)arg2;
- (void)setOSDeploymentVersion:(id)arg1 forPlatformFamily:(id)arg2;
- (id)osDeploymentVersionForPlatformFamily:(id)arg1;
@property(readonly) NSSet *supportedPlatformFamilies;
- (void)setDocumentToolsVersionWithPackageTypeCheck:(id)arg1;
- (BOOL)isPackageDifferentForDocumentToolsVersion:(id)arg1;
- (void)editorDocumentWillClose;
- (id)displayName;
- (id)objectSpecifier;
- (id)newScriptingObjectOfClass:(Class)arg1 forValueForKey:(id)arg2 withContentsValue:(id)arg3 properties:(id)arg4;
- (id)sdefSupport_entities;
- (void)setDisplayName:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@property unsigned long long supportedMatchingOptions;

@end


text:
namespace OJS.Workers.Executors.Process
{
    using System;
    using System.Runtime.InteropServices;

    [StructLayout(LayoutKind.Sequential)]
    public struct ProcessMemoryCounters
    {
        public int SizeInBytes;
        public int PageFaultCount;
        public IntPtr PeakWorkingSetSize;
        public IntPtr WorkingSetSize;
        public IntPtr QuotaPeakPagedPoolUsage;
        public IntPtr QuotaPagedPoolUsage;
        public IntPtr QuotaPeakNonPagedPoolUsage;
        public IntPtr QuotaNonPagedPoolUsage;
        public IntPtr PagefileUsage;
        public IntPtr PeakPagefileUsage;
    }
}


text:
package org.jboss.weld.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.enterprise.inject.spi.Bean;

import org.jboss.weld.bean.proxy.ProxyInstantiator;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.config.WeldConfiguration;
import org.jboss.weld.exceptions.UnproxyableResolutionException;
import org.jboss.weld.logging.UtilLogger;
import org.jboss.weld.logging.ValidatorLogger;
import org.jboss.weld.util.collections.Arrays2;
import org.jboss.weld.util.reflection.Reflections;

/**
 * Utilities for working with proxies.
 *
 * @author Nicklas Karlsson
 * @author Pete Muir
 * @author Tomaz Cerar
 * @author Ales Justin
 */
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "NullableProblems"})
public class Proxies {

    public static class TypeInfo {

        private final Set<Class<?>> interfaces;
        private final Set<Class<?>> classes;

        private TypeInfo() {
            super();
            this.interfaces = new LinkedHashSet<Class<?>>();
            this.classes = new LinkedHashSet<Class<?>>();
        }

        public Class<?> getSuperClass() {
            if (classes.isEmpty()) {
                return Object.class;
            }
            Iterator<Class<?>> it = classes.iterator();
            Class<?> superclass = it.next();
            while (it.hasNext()) {
                Class<?> clazz = it.next();
                if (superclass.isAssignableFrom(clazz)) {
                    superclass = clazz;
                }
            }
            return superclass;
        }

        public Class<?> getSuperInterface() {
            if (interfaces.isEmpty()) {
                return null;
            }
            Iterator<Class<?>> it = interfaces.iterator();
            Class<?> superclass = it.next();
            while (it.hasNext()) {
                Class<?> clazz = it.next();
                if (superclass.isAssignableFrom(clazz)) {
                    superclass = clazz;
                }
            }
            return superclass;
        }

        private TypeInfo add(Type type) {
            if (type instanceof Class<?>) {
                Class<?> clazz = (Class<?>) type;
                if (clazz.isInterface()) {
                    interfaces.add(clazz);
                } else {
                    classes.add(clazz);
                }
            } else if (type instanceof ParameterizedType) {
                add(((ParameterizedType) type).getRawType());
            } else {
                throw UtilLogger.LOG.cannotProxyNonClassType(type);
            }
            return this;
        }

        public Set<Class<?>> getClasses() {
            return Collections.unmodifiableSet(classes);
        }

        public Set<Class<?>> getInterfaces() {
            return Collections.unmodifiableSet(interfaces);
        }

        public static TypeInfo of(Set<? extends Type> types) {
            TypeInfo typeInfo = new TypeInfo();
            for (Type type : types) {
                typeInfo.add(type);
            }
            return typeInfo;
        }

    }

    private Proxies() {
    }

    /**
     * Indicates if a class is proxyable
     *
     * @param type The class to test
     * @return True if proxyable, false otherwise
     */
    public static boolean isTypeProxyable(Type type, ServiceRegistry services) {
        return getUnproxyableTypeException(type, services) == null;
    }

    public static UnproxyableResolutionException getUnproxyableTypeException(Type type, ServiceRegistry services) {
        return getUnproxyableTypeException(type, null, services, false);
    }

    /**
     * Indicates if a set of types are all proxyable
     *
     * @param declaringBean with types to test
     * @return True if proxyable, false otherwise
     */
    public static boolean isTypesProxyable(Bean<?> declaringBean, ServiceRegistry services) {
        return getUnproxyableTypesException(declaringBean, services) == null;
    }

    /**
     * Indicates if a set of types are all proxyable
     *
     * @param types The types to test
     * @return True if proxyable, false otherwise
     */
    public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {
        return getUnproxyableTypesException(types, services) == null;
    }

    public static UnproxyableResolutionException getUnproxyableTypesException(Bean<?> declaringBean, ServiceRegistry services) {
        if (declaringBean == null) {
            throw new java.lang.IllegalArgumentException("Null declaring bean!");
        }

        return getUnproxyableTypesExceptionInt(declaringBean.getTypes(), declaringBean, services);
    }

    public static UnproxyableResolutionException getUnproxyableTypesException(Iterable<? extends Type> types, ServiceRegistry services) {
        return getUnproxyableTypesExceptionInt(types, null, services);
    }

    public static UnproxyableResolutionException getUnproxyableTypeException(Type type, Bean<?> declaringBean, ServiceRegistry services, boolean ignoreFinalMethods) {
        if (type instanceof Class<?> || type instanceof ParameterizedType || type instanceof GenericArrayType) {
            return getUnproxyableClassException(Reflections.getRawType(type), declaringBean, services, ignoreFinalMethods);
        }
        return ValidatorLogger.LOG.notProxyableUnknown(type, getDeclaringBeanInfo(declaringBean));
    }

    // --- private

    private static UnproxyableResolutionException getUnproxyableTypesExceptionInt(Iterable<? extends Type> types, Bean<?> declaringBean, ServiceRegistry services) {
        for (Type apiType : types) {
            if (Object.class.equals(apiType)) {
                continue;
            }
            UnproxyableResolutionException e = getUnproxyableTypeException(apiType, declaringBean, services, false);
            if (e != null) {
                return e;
            }
        }
        return null;
    }

    private static UnproxyableResolutionException getUnproxyableClassException(Class<?> clazz, Bean<?> declaringBean, ServiceRegistry services,
            boolean ignoreFinalMethods) {
        if (clazz.isInterface()) {
            return null;
        }

        Constructor<?> constructor = null;
        try {
            constructor = SecurityActions.getDeclaredConstructor(clazz);
        } catch (Exception ignored) {
        }

        if (clazz.isPrimitive()) {
            return ValidatorLogger.LOG.notProxyablePrimitive(clazz, getDeclaringBeanInfo(declaringBean));
        } else if (Reflections.isArrayType(clazz)) {
            return ValidatorLogger.LOG.notProxyableArrayType(clazz, getDeclaringBeanInfo(declaringBean));
        } else if (Reflections.isFinal(clazz)) {
            return ValidatorLogger.LOG.notProxyableFinalType(clazz, getDeclaringBeanInfo(declaringBean));
        } else {
            Method finalMethod = Reflections.getNonPrivateNonStaticFinalMethod(clazz);
            if (finalMethod != null) {
                if (ignoreFinalMethods || Beans.shouldIgnoreFinalMethods(declaringBean)
                        || services.get(WeldConfiguration.class).isFinalMethodIgnored(clazz.getName())) {
                    ValidatorLogger.LOG.notProxyableFinalMethodIgnored(finalMethod, getDeclaringBeanInfo(declaringBean));
                } else {
                    return ValidatorLogger.LOG.notProxyableFinalMethod(clazz, finalMethod, getDeclaringBeanInfo(declaringBean));
                }
            }
        }

        UnproxyableResolutionException exception = services.get(ProxyInstantiator.class).validateNoargConstructor(constructor, clazz, declaringBean);
        if (exception != null) {
            return exception;
        }

        return null;
    }

    public static Object getDeclaringBeanInfo(Bean<?> bean) {
        return (bean != null) ? bean : "<unknown javax.enterprise.inject.spi.Bean instance>";
    }

    /**
     *
     * @param interfaces
     * @return the sorted set of interfaces
     */
    public static LinkedHashSet<Class<?>> sortInterfacesHierarchy(Set<Class<?>> interfaces) {
        LinkedHashSet<Class<?>> sorted = new LinkedHashSet<>(interfaces.size());
        processSuperinterface(null, interfaces, sorted);
        if (interfaces.size() != sorted.size()) {
            // Interface may not processed due to incomplete type closure
            Set<Class<?>> unprocessed = new HashSet<>(interfaces);
            unprocessed.removeAll(sorted);
            for (Class<?> unprocessedInterface : unprocessed) {
                processSuperinterface(unprocessedInterface, interfaces, sorted);
                sorted.add(unprocessedInterface);
            }
        }
        return sorted;
    }

    private static void processSuperinterface(Class<?> superinterface, Set<Class<?>> interfaces, LinkedHashSet<Class<?>> sorted) {
        for (Class<?> interfaceClass : interfaces) {
            if (isInterfaceExtending(interfaceClass, superinterface)) {
                processSuperinterface(interfaceClass, interfaces, sorted);
                sorted.add(interfaceClass);
            }
        }
    }

    private static boolean isInterfaceExtending(Class<?> interfaceClass, Class<?> superinterface) {
        if (interfaceClass.equals(superinterface)) {
            return false;
        } else if (superinterface == null) {
            return interfaceClass.getInterfaces().length == 0;
        } else {
            return Arrays2.contains(interfaceClass.getInterfaces(), superinterface);
        }
    }
}


text:
'use strict'

describe('Topic wildcards', function() {
  const PORT = 6242
  const authUrl = 'nats://localhost:' + PORT
  let server

  before(function(done) {
    server = HemeraTestsuite.start_server(PORT, done)
  })

  after(function() {
    server.kill()
  })

  it('Should be able to use token wildcard in topic declaration', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a.>',
          cmd: 'info'
        },
        (req, cb) => {
          expect(req.topic).to.be.equals('systems-europe.a.info.details')
          cb(null, true)
        }
      )
      hemera.act(
        {
          topic: 'systems-europe.a.info.details',
          cmd: 'info'
        },
        function(err, resp) {
          expect(err).to.be.not.exists()
          expect(resp).to.be.equals(true)
          hemera.close(done)
        }
      )
    })
  })

  it('Should be able to use full wildcard in topic declaration', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a.*',
          cmd: 'info'
        },
        (req, cb) => {
          expect(req.topic).to.be.equals('systems-europe.a.info')
          cb(null, true)
        }
      )
      hemera.act(
        {
          topic: 'systems-europe.a.info',
          cmd: 'info'
        },
        function(err, resp) {
          expect(err).to.be.not.exists()
          expect(resp).to.be.equals(true)
          hemera.close(done)
        }
      )
    })
  })

  it('Should call the first server method twice because order is significant', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)
    let callback = Sinon.spy()
    let callback2 = Sinon.spy()

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a.>',
          cmd: 'info'
        },
        (req, cb) => {
          callback()
          cb(null, true)
        }
      )

      hemera.add(
        {
          topic: 'systems-europe.a.*',
          cmd: 'info'
        },
        (req, cb) => {
          callback2()
          cb(null, true)
        }
      )

      hemera.act(
        {
          topic: 'systems-europe.a.info',
          cmd: 'info'
        },
        function(err, resp) {
          expect(err).to.be.not.exists()
          expect(resp).to.be.equals(true)
          expect(callback2.callCount).to.be.equals(0)
          // NATS has registered two subject wildcards
          // On hemera side the order is significant
          expect(callback.callCount).to.be.equals(2)
          hemera.close(done)
        }
      )
    })
  })

  it('Should be able to use token wildcard in pubsub mode', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a.>',
          cmd: 'info'
        },
        req => {
          expect(req.topic).to.be.equals('systems-europe.a.info.details')
          hemera.close(done)
        }
      )
      hemera.act({
        topic: 'systems-europe.a.info.details',
        cmd: 'info',
        pubsub$: true
      })
    })
  })

  it('Should be able to use full wildcard in pubsub mode', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a.*',
          cmd: 'info'
        },
        req => {
          expect(req.topic).to.be.equals('systems-europe.a.info')
          hemera.close(done)
        }
      )
      hemera.act({
        topic: 'systems-europe.a.info',
        cmd: 'info',
        pubsub$: true
      })
    })
  })

  it('Should not convert topic without wildcard tokens', function(done) {
    const nats = require('nats').connect(authUrl)

    const hemera = new Hemera(nats)

    hemera.ready(() => {
      hemera.add(
        {
          topic: 'systems-europe.a',
          cmd: 'info'
        },
        (req, cb) => {
          expect(req.topic).to.be.equals('systems-europe.a')
          cb(null, true)
        }
      )

      const br = hemera.router.lookup({
        topic: 'systems-europe.a',
        cmd: 'info'
      })

      expect(br.pattern.topic).to.be.equals('systems-europe.a')
      hemera.close(done)
    })
  })
})


text:
package com.github.zhgxun.learn.test;

import java.util.HashMap;

public class HashMapTest {

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "zhangsan");
        System.out.println(map.get("name"));
    }
}


text:
/**
 *    Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
 *    University
 *
 *    Licensed under the Apache License, Version 2.0 (the "License"); you may
 *    not use this file except in compliance with the License. You may obtain
 *    a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *    License for the specific language governing permissions and limitations
 *    under the License.
 **/

/**
 * @author David Erickson (daviderickson@cs.stanford.edu) - Mar 11, 2010
 */
package org.openflow.protocol.action;

import org.jboss.netty.buffer.ChannelBuffer;

/**
 * Represents an ofp_action_vlan_vid
 *
 * @author David Erickson (daviderickson@cs.stanford.edu) - Mar 11, 2010
 */
public class OFActionVirtualLanIdentifier extends OFAction {
	public static int MINIMUM_LENGTH = 8;

	protected short virtualLanIdentifier;

	public OFActionVirtualLanIdentifier() {
		super.setType(OFActionType.SET_VLAN_ID);
		super.setLength((short) OFActionVirtualLanIdentifier.MINIMUM_LENGTH);
	}

	public OFActionVirtualLanIdentifier(final short vlanId) {
		this();
		this.virtualLanIdentifier = vlanId;
	}

	/**
	 * @return the virtualLanIdentifier
	 */
	public short getVirtualLanIdentifier() {
		return this.virtualLanIdentifier;
	}

	/**
	 * @param virtualLanIdentifier
	 *            the virtualLanIdentifier to set
	 */
	public void setVirtualLanIdentifier(final short virtualLanIdentifier) {
		this.virtualLanIdentifier = virtualLanIdentifier;
	}

	@Override
	public void readFrom(final ChannelBuffer data) {
		super.readFrom(data);
		this.virtualLanIdentifier = data.readShort();
		data.readShort();
	}

	@Override
	public void writeTo(final ChannelBuffer data) {
		super.writeTo(data);
		data.writeShort(this.virtualLanIdentifier);
		data.writeShort((short) 0);
	}

	@Override
	public int hashCode() {
		final int prime = 383;
		int result = super.hashCode();
		result = prime * result + this.virtualLanIdentifier;
		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (!(obj instanceof OFActionVirtualLanIdentifier)) {
			return false;
		}
		final OFActionVirtualLanIdentifier other = (OFActionVirtualLanIdentifier) obj;
		if (this.virtualLanIdentifier != other.virtualLanIdentifier) {
			return false;
		}
		return true;
	}
}


text:
package main

import (
	"fmt"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
	"path/filepath"
	"runtime"
	"runtime/debug"
	"runtime/pprof"

	"github.com/btcsuite/btcd/blockchain/indexers"
	"github.com/btcsuite/btcd/database"
	"github.com/btcsuite/btcd/limits"
)

const (
	// blockDbNamePrefix is the prefix for the block database name.  The
	// database type is appended to this value to form the full block
	// database name.
	blockDbNamePrefix = "blocks"
)

var (
	cfg *config
)

// winServiceMain is only invoked on Windows.  It detects when btcd is running
// as a service and reacts accordingly.
var winServiceMain func() (bool, error)

// btcdMain is the real main function for btcd.  It is necessary to work around
// the fact that deferred functions do not run when os.Exit() is called.  The
// optional serverChan parameter is mainly used by the service code to be
// notified with the server once it is setup so it can gracefully stop it when
// requested from the service control manager.
func btcdMain(serverChan chan<- *server) error {
	// Load configuration and parse command line.  This function also
	// initializes logging and configures it accordingly.
	tcfg, _, err := loadConfig()
	if err != nil {
		return err
	}
	cfg = tcfg
	defer func() {
		if logRotator != nil {
			logRotator.Close()
		}
	}()

	// Get a channel that will be closed when a shutdown signal has been
	// triggered either from an OS signal such as SIGINT (Ctrl+C) or from
	// another subsystem such as the RPC server.
	interrupt := interruptListener()
	defer btcdLog.Info("Shutdown complete")

	// Show version at startup.
	btcdLog.Infof("Version %s", version())

	// Enable http profiling server if requested.
	if cfg.Profile != "" {
		go func() {
			listenAddr := net.JoinHostPort("", cfg.Profile)
			btcdLog.Infof("Profile server listening on %s", listenAddr)
			profileRedirect := http.RedirectHandler("/debug/pprof",
				http.StatusSeeOther)
			http.Handle("/", profileRedirect)
			btcdLog.Errorf("%v", http.ListenAndServe(listenAddr, nil))
		}()
	}

	// Write cpu profile if requested.
	if cfg.CPUProfile != "" {
		f, err := os.Create(cfg.CPUProfile)
		if err != nil {
			btcdLog.Errorf("Unable to create cpu profile: %v", err)
			return err
		}
		pprof.StartCPUProfile(f)
		defer f.Close()
		defer pprof.StopCPUProfile()
	}

	// Perform upgrades to btcd as new versions require it.
	if err := doUpgrades(); err != nil {
		btcdLog.Errorf("%v", err)
		return err
	}

	// Return now if an interrupt signal was triggered.
	if interruptRequested(interrupt) {
		return nil
	}

	// Load the block database.
	db, err := loadBlockDB()
	if err != nil {
		btcdLog.Errorf("%v", err)
		return err
	}
	defer func() {
		// Ensure the database is sync'd and closed on shutdown.
		btcdLog.Infof("Gracefully shutting down the database...")
		db.Close()
	}()

	// Return now if an interrupt signal was triggered.
	if interruptRequested(interrupt) {
		return nil
	}

	// Drop indexes and exit if requested.
	//
	// NOTE: The order is important here because dropping the tx index also
	// drops the address index since it relies on it.
	if cfg.DropAddrIndex {
		if err := indexers.DropAddrIndex(db, interrupt); err != nil {
			btcdLog.Errorf("%v", err)
			return err
		}

		return nil
	}
	if cfg.DropTxIndex {
		if err := indexers.DropTxIndex(db, interrupt); err != nil {
			btcdLog.Errorf("%v", err)
			return err
		}

		return nil
	}

	// Create server and start it.
	server, err := newServer(cfg.Listeners, db, activeNetParams.Params,
		interrupt)
	if err != nil {
		// TODO: this logging could do with some beautifying.
		btcdLog.Errorf("Unable to start server on %v: %v",
			cfg.Listeners, err)
		return err
	}
	defer func() {
		btcdLog.Infof("Gracefully shutting down the server...")
		server.Stop()
		server.WaitForShutdown()
		srvrLog.Infof("Server shutdown complete")
	}()
	server.Start()
	if serverChan != nil {
		serverChan <- server
	}

	// Wait until the interrupt signal is received from an OS signal or
	// shutdown is requested through one of the subsystems such as the RPC
	// server.
	<-interrupt
	return nil
}

// removeRegressionDB removes the existing regression test database if running
// in regression test mode and it already exists.
func removeRegressionDB(dbPath string) error {
	// Don't do anything if not in regression test mode.
	if !cfg.RegressionTest {
		return nil
	}

	// Remove the old regression test database if it already exists.
	fi, err := os.Stat(dbPath)
	if err == nil {
		btcdLog.Infof("Removing regression test database from '%s'", dbPath)
		if fi.IsDir() {
			err := os.RemoveAll(dbPath)
			if err != nil {
				return err
			}
		} else {
			err := os.Remove(dbPath)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// dbPath returns the path to the block database given a database type.
func blockDbPath(dbType string) string {
	// The database name is based on the database type.
	dbName := blockDbNamePrefix + "_" + dbType
	if dbType == "sqlite" {
		dbName = dbName + ".db"
	}
	dbPath := filepath.Join(cfg.DataDir, dbName)
	return dbPath
}

// warnMultipeDBs shows a warning if multiple block database types are detected.
// This is not a situation most users want.  It is handy for development however
// to support multiple side-by-side databases.
func warnMultipeDBs() {
	// This is intentionally not using the known db types which depend
	// on the database types compiled into the binary since we want to
	// detect legacy db types as well.
	dbTypes := []string{"ffldb", "leveldb", "sqlite"}
	duplicateDbPaths := make([]string, 0, len(dbTypes)-1)
	for _, dbType := range dbTypes {
		if dbType == cfg.DbType {
			continue
		}

		// Store db path as a duplicate db if it exists.
		dbPath := blockDbPath(dbType)
		if fileExists(dbPath) {
			duplicateDbPaths = append(duplicateDbPaths, dbPath)
		}
	}

	// Warn if there are extra databases.
	if len(duplicateDbPaths) > 0 {
		selectedDbPath := blockDbPath(cfg.DbType)
		btcdLog.Warnf("WARNING: There are multiple block chain databases "+
			"using different database types.\nYou probably don't "+
			"want to waste disk space by having more than one.\n"+
			"Your current database is located at [%v].\nThe "+
			"additional database is located at %v", selectedDbPath,
			duplicateDbPaths)
	}
}

// loadBlockDB loads (or creates when needed) the block database taking into
// account the selected database backend and returns a handle to it.  It also
// contains additional logic such warning the user if there are multiple
// databases which consume space on the file system and ensuring the regression
// test database is clean when in regression test mode.
func loadBlockDB() (database.DB, error) {
	// The memdb backend does not have a file path associated with it, so
	// handle it uniquely.  We also don't want to worry about the multiple
	// database type warnings when running with the memory database.
	if cfg.DbType == "memdb" {
		btcdLog.Infof("Creating block database in memory.")
		db, err := database.Create(cfg.DbType)
		if err != nil {
			return nil, err
		}
		return db, nil
	}

	warnMultipeDBs()

	// The database name is based on the database type.
	dbPath := blockDbPath(cfg.DbType)

	// The regression test is special in that it needs a clean database for
	// each run, so remove it now if it already exists.
	removeRegressionDB(dbPath)

	btcdLog.Infof("Loading block database from '%s'", dbPath)
	db, err := database.Open(cfg.DbType, dbPath, activeNetParams.Net)
	if err != nil {
		// Return the error if it's not because the database doesn't
		// exist.
		if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode !=
			database.ErrDbDoesNotExist {

			return nil, err
		}

		// Create the db if it does not exist.
		err = os.MkdirAll(cfg.DataDir, 0700)
		if err != nil {
			return nil, err
		}
		db, err = database.Create(cfg.DbType, dbPath, activeNetParams.Net)
		if err != nil {
			return nil, err
		}
	}

	btcdLog.Info("Block database loaded")
	return db, nil
}

func main() {
	// Use all processor cores.
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Block and transaction processing can cause bursty allocations.  This
	// limits the garbage collector from excessively overallocating during
	// bursts.  This value was arrived at with the help of profiling live
	// usage.
	debug.SetGCPercent(10)

	// Up some limits.
	if err := limits.SetLimits(); err != nil {
		fmt.Fprintf(os.Stderr, "failed to set limits: %v\n", err)
		os.Exit(1)
	}

	// Call serviceMain on Windows to handle running as a service.  When
	// the return isService flag is true, exit now since we ran as a
	// service.  Otherwise, just fall through to normal operation.
	if runtime.GOOS == "windows" {
		isService, err := winServiceMain()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		if isService {
			os.Exit(0)
		}
	}

	// Work around defer not working after os.Exit()
	if err := btcdMain(nil); err != nil {
		os.Exit(1)
	}
}


text:
package org.apache.geode;

// import org.apache.geode.internal.Assert;
// import java.io.*;
// import java.util.*;

/**
 * Used to describe a logical collection of statistics. These descriptions are used to create an
 * instance of {@link Statistics}.
 *
 *

 * To get an instance of this interface use an instance of {@link StatisticsFactory}.
 *
 *
 * @since GemFire 3.0
 */
public interface StatisticsType {

  /**
   * Returns the name of this statistics type
   */
  public String getName();

  /**
   * Returns a description of this statistics type
   */
  public String getDescription();

  /**
   * Returns descriptions of the statistics that this statistics type gathers together
   */
  public StatisticDescriptor[] getStatistics();

  /**
   * Returns the id of the statistic with the given name in this statistics instance.
   *
   * @throws IllegalArgumentException No statistic named name exists in this statistics
   *         instance.
   */
  public int nameToId(String name);

  /**
   * Returns the descriptor of the statistic with the given name in this statistics instance.
   *
   * @throws IllegalArgumentException No statistic named name exists in this statistics
   *         instance.
   */
  public StatisticDescriptor nameToDescriptor(String name);

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Database;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using Xamarin.Media;

namespace Xamarin.Contacts
{
	public class Contact
	{
		public Contact()
		{
		}

		internal Contact (string id, bool isAggregate, ContentResolver content)
		{
			this.content = content;
			IsAggregate = isAggregate;
			Id = id;
		}

		public string Id
		{
			get;
			private set;
		}

		public bool IsAggregate
		{
			get;
			private set;
		}

		public string DisplayName
		{
			get;
			set;
		}

		public string Prefix
		{
			get;
			set;
		}

		public string FirstName
		{
			get;
			set;
		}

		public string MiddleName
		{
			get;
			set;
		}

		public string LastName
		{
			get;
			set;
		}

		public string Nickname
		{
			get;
			set;
		}

		public string Suffix
		{
			get;
			set;
		}

		internal List<Relationship> relationships = new List<Relationship>();
		public IEnumerable<Relationship> Relationships
		{
			get { return this.relationships; }
			set { this.relationships = new List<Relationship> (value); }
		}

		internal List<Address> addresses = new List<Address>();
		public IEnumerable<Address> Addresses
		{
			get { return this.addresses; }
			set { this.addresses = new List<Address> (value); }
		}

		internal List<InstantMessagingAccount> instantMessagingAccounts = new List<InstantMessagingAccount>();
		public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts
		{
			get { return this.instantMessagingAccounts; }
			set { this.instantMessagingAccounts = new List<InstantMessagingAccount> (value); }
		}

		internal List<Website> websites = new List<Website>();
		public IEnumerable<Website> Websites
		{
			get { return this.websites; }
			set { this.websites = new List<Website> (value); }
		}

		internal List<Organization> organizations = new List<Organization>();
		public IEnumerable<Organization> Organizations
		{
			get { return this.organizations; }
			set { this.organizations = new List<Organization> (value); }
		}

		internal List<Note> notes = new List<Note>();
		public IEnumerable<Note> Notes
		{
			get { return this.notes; }
			set { this.notes = new List<Note> (value); }
		}

		internal List<Email> emails = new List<Email>();
		public IEnumerable<Email> Emails
		{
			get { return this.emails; }
			set { this.emails = new List<Email> (value); }
		}

		internal List<Phone> phones = new List<Phone>();
		public IEnumerable<Phone> Phones
		{
			get { return this.phones; }
			set { this.phones = new List<Phone> (value); }
		}

		public Bitmap GetThumbnail()
		{
			byte[] data = GetThumbnailBytes();
			return (data == null) ? null : BitmapFactory.DecodeByteArray (data, 0, data.Length);
		}

		public Task<MediaFile> SaveThumbnailAsync (string path)
		{
			if (path == null)
				throw new ArgumentNullException ("path");

			return Task.Factory.StartNew (() => {
				byte[] bytes = GetThumbnailBytes();
				if (bytes == null)
					return null;

				File.WriteAllBytes (path, bytes);
				return new MediaFile (path, deletePathOnDispose: false);
			});
		}

		byte[] GetThumbnailBytes()
		{
			string lookupColumn = (IsAggregate)
			                      	? ContactsContract.ContactsColumns.LookupKey
			                      	: ContactsContract.RawContactsColumns.ContactId;

			ICursor c = null;
			try {
				c = this.content.Query (ContactsContract.Data.ContentUri, new[] { ContactsContract.CommonDataKinds.Photo.PhotoColumnId, ContactsContract.DataColumns.Mimetype },
					lookupColumn + "=? AND " + ContactsContract.DataColumns.Mimetype + "=?", new[] { Id, ContactsContract.CommonDataKinds.Photo.ContentItemType }, null);

				while (c.MoveToNext()) {
					byte[] tdata = c.GetBlob (c.GetColumnIndex (ContactsContract.CommonDataKinds.Photo.PhotoColumnId));
					if (tdata != null)
						return tdata;
				}
			} finally {
				if (c != null)
					c.Close();
			}

			return null;
		}

		private readonly ContentResolver content;
	}
}


text:
// @target: ES5
// @declaration: true
// @comments: true

/** Enum of colors*/
enum Colors {
    /** Fancy name for 'blue'*/
    Cornflower /* blue */,
    /** Fancy name for 'pink'*/
    FancyPink
} // trailing comment
var x = Colors.Cornflower;
x = Colors.FancyPink;


text:
<my-breadcrumbs data-hide-ns-dropdown="true"></my-breadcrumbs>

          System Configuration

              Configuration

              Services

              Preferences

          Namespaces

                  Applications

                  Datasets

                  Preferences

                  Settings

                  Templates