text:
#include "Socket.h"

namespace netLink {

#ifdef WIN32
void init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
        throw Exception(Exception::ERROR_INIT);
}
#define snprintf _snprintf_s
#else
#define closesocket close
#endif

static void readSockaddr(const struct sockaddr_storage* addr, std::string& host, unsigned int& port) {
    char buffer[INET6_ADDRSTRLEN];
    if(addr->ss_family == AF_INET) {
        auto sin = reinterpret_cast<const struct sockaddr_in*>(addr);
        port = ntohs(sin->sin_port);
        inet_ntop(addr->ss_family, (void*)&(sin->sin_addr), buffer, sizeof(buffer));
    }else{
        auto sin = reinterpret_cast<const struct sockaddr_in6*>(addr);
        port = ntohs(sin->sin6_port);
        inet_ntop(addr->ss_family, (void*)&(sin->sin6_addr), buffer, sizeof(buffer));
    }
    host = buffer;
}

Socket::AddrinfoContainer Socket::getSocketInfoFor(const char* host, unsigned int port, bool wildcardAddress) {
    struct addrinfo conf, *res;
    memset(&conf, 0, sizeof(conf));
    conf.ai_flags = AI_V4MAPPED;
    conf.ai_family = AF_UNSPEC;

    if(wildcardAddress)
        conf.ai_flags |= AI_PASSIVE;

    switch(type) {
        case TCP_CLIENT:
        case TCP_SERVER:
            conf.ai_socktype = SOCK_STREAM;
        break;
        case UDP_PEER:
            conf.ai_socktype = SOCK_DGRAM;
        break;
        default:
            disconnect();
            throw Exception(Exception::BAD_PROTOCOL);
    }

    char portStr[10];
    snprintf(portStr, 10, "%u", port);

    int result = getaddrinfo(host, portStr, &conf, &res);
    if(result != 0)
        throw Exception(Exception::ERROR_RESOLVING_ADDRESS);

    return AddrinfoContainer(res);
}

Socket::pos_type Socket::seekoff(Socket::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) {
    switch(way) {
        case std::ios_base::beg:
            if (off < 0) break;

            if(which & std::ios_base::in) {
                if(eback() + off >= egptr()) break;
                setg(eback(), eback()+off, egptr());
            }

            if(which & std::ios_base::out) {
                if(pbase() + off >= epptr()) break;
                setp(pbase(), epptr());
                pbump(off);
            }
        return off;
        case std::ios_base::cur:
            if(which == std::ios_base::in) {
                if(eback() + off >= egptr() || egptr() + off < eback()) break;
                setg(eback(), gptr()+off, egptr());
                return gptr()-eback();
            }else if(which == std::ios_base::out) {
                if(pbase() + off >= epptr() || epptr() + off < pbase()) break;
                pbump(off);
                return pptr()-pbase();
            }else
                break;
        case std::ios_base::end:
            if(off > 0) break;

            if(which == std::ios_base::in) {
                if(egptr() + off < eback()) break;
                setg(eback(), egptr()+off, egptr());
                return gptr()-eback();
            }else if(which == std::ios_base::out) {
                if(epptr() + off < pbase()) break;
                setp(pbase(), epptr());
                pbump(off);
                return pptr()-pbase();
            }else
                break;
    }
    return EOF;
}

Socket::pos_type Socket::seekpos(Socket::pos_type sp, std::ios_base::openmode which) {
    return Socket::seekoff(sp, std::ios_base::beg, which);
}

int Socket::sync() {
    if(getOutputBufferSize() <= 0) //No output buffer
        return EOF;

    if(pptr() == pbase()) //Allready in sync
        return 0;

    try {
        setp(pbase(), pptr()+send(pbase(), pptr()-pbase()));
        return 0;
    } catch(Exception err) {
        return EOF;
    }
}

std::streamsize Socket::xsgetn(char_type* buffer, std::streamsize size) {
    if(inputIntermediateSize > 0) //Read from input buffer
        return super::xsgetn(buffer, size);

    try {
        return receive(buffer, size);
    } catch(Exception err) {
        return 0;
    }
}

Socket::int_type Socket::underflow() {
    if(type == UDP_PEER || advanceInputBuffer() <= 0)
        return EOF;
    return *eback();
}

std::streamsize Socket::xsputn(const char_type* buffer, std::streamsize size) {
    if(getOutputBufferSize()) //Write into buffer
        return super::xsputn(buffer, size);

    try {
        return send(buffer, size);
    } catch(Exception err) {
        return 0;
    }
}

Socket::int_type Socket::overflow(int_type c) {
    if(sync() == EOF)
        return EOF;
    *pbase() = c;
    pbump(1);
    return c;
}

void Socket::initSocket(bool blockingConnect) {
    AddrinfoContainer info;

    if(type == TCP_CLIENT)
        info = getSocketInfoFor(hostRemote.c_str(), portRemote, false);
    else{
        const char* host;
        if(!hostLocal.compare("") || !hostLocal.compare("*"))
            host = NULL;
        else
            host = hostLocal.c_str();
        info = getSocketInfoFor(host, portLocal, true);
    }

    struct addrinfo* nextAddr = info.get();
    while(nextAddr) {
        handle = socket(nextAddr->ai_family, nextAddr->ai_socktype, nextAddr->ai_protocol);
        if(handle == -1) {
            nextAddr = nextAddr->ai_next;
            continue;
        }

        setBlockingMode(blockingConnect);
        #ifdef WIN32
        char flag = 1;
        #else
        int flag = 1;
        if(setsockopt(handle, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) == -1) {
            disconnect();
            throw Exception(Exception::ERROR_SET_SOCK_OPT);
        }
        #endif
        if(setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1) {
            disconnect();
            throw Exception(Exception::ERROR_SET_SOCK_OPT);
        }

        switch(nextAddr->ai_family) {
            case AF_INET:
                ipVersion = IPv4;
            break;
            case AF_INET6:
                ipVersion = IPv6;
            break;
        }

        switch(type) {
            case NONE:
            case TCP_SERVERS_CLIENT:
                disconnect();
                throw Exception(Exception::BAD_TYPE);
            case TCP_CLIENT:
                if(connect(handle, nextAddr->ai_addr, nextAddr->ai_addrlen) == -1 && blockingConnect) {
                    closesocket(handle);
                    handle = -1;
                }else if(blockingConnect)
                    status = READY;
                else
                    status = CONNECTING;
            break;
            case TCP_SERVER: {
                if(bind(handle, nextAddr->ai_addr, nextAddr->ai_addrlen) == -1) {
                    closesocket(handle);
                    handle = -1;
                }

                if(listen(handle, status) == -1) {
                    disconnect();
                    throw Exception(Exception::ERROR_INIT);
                }
            } break;
            case UDP_PEER: {
                if(bind(handle, nextAddr->ai_addr, nextAddr->ai_addrlen) == -1) {
                    closesocket(handle);
                    handle = -1;
                }

                status = READY;
            } break;
        }
        if(handle == -1) {
            nextAddr = nextAddr->ai_next;
            continue;
        }

        if(blockingConnect)
            setBlockingMode(false);
        break;
    }

    if(handle == -1) {
        disconnect();
        throw Exception(Exception::ERROR_INIT);
    }

    struct sockaddr_storage localAddr;
    #ifdef WIN32
    int size = sizeof(localAddr);
    #else
    unsigned int size = sizeof(localAddr);
    #endif
    if(getsockname(handle, reinterpret_cast<struct sockaddr*>(&localAddr), &size) != 0) {
        disconnect();
        throw Exception(Exception::ERROR_GET_SOCK_NAME);
    }

    readSockaddr(&localAddr, hostLocal, portLocal);
}

void Socket::initAsTcpClient(const std::string& _hostRemote, unsigned _portRemote, bool waitUntilConnected) {
    type = TCP_CLIENT;
    hostRemote = _hostRemote;
    portRemote = _portRemote;
    initSocket(waitUntilConnected);
}

void Socket::initAsTcpServer(const std::string& _hostLocal, unsigned _portLocal, unsigned _listenQueue) {
    type = TCP_SERVER;
    hostLocal = _hostLocal;
    portLocal = _portLocal;
    status = _listenQueue;
    initSocket(false);
}

void Socket::initAsUdpPeer(const std::string& _hostLocal, unsigned _portLocal) {
    type = UDP_PEER;
    hostLocal = _hostLocal;
    portLocal = _portLocal;
    initSocket(false);
}

Socket::Socket() :ipVersion(ANY), type(NONE), status(NOT_CONNECTED),
    handle(-1), portLocal(0), portRemote(0) {
    #if NETLINK_DEFAULT_INPUT_BUFFER_SIZE > 0
    setInputBufferSize(NETLINK_DEFAULT_INPUT_BUFFER_SIZE);
    #else
    setInputBufferSize(0);
    #endif
    #if NETLINK_DEFAULT_OUTPUT_BUFFER_SIZE > 0
    setOutputBufferSize(NETLINK_DEFAULT_INPUT_BUFFER_SIZE);
    #else
    setOutputBufferSize(0);
    #endif
};

Socket::~Socket() {
    disconnect();
}

Socket::IPVersion Socket::getIPVersion() const {
    return ipVersion;
}

Socket::Type Socket::getType() const {
    return type;
}

Socket::Status Socket::getStatus() const {
    if(type == TCP_SERVER)
        return (status == NOT_CONNECTED) ? NOT_CONNECTED : LISTENING;
    else
        return (Socket::Status)status;
}

std::streamsize Socket::showmanyc() {
    #ifdef WIN32
    unsigned long result = 0;
    if(ioctlsocket(handle, FIONREAD, &result)) {
    #else
    int result = 0;
    if(ioctl(handle, FIONREAD, &result)) {
    #endif
        disconnect();
        throw Exception(Exception::ERROR_IOCTL);
    }else
        return result;
}

std::streamsize Socket::advanceInputBuffer() {
    if(inputIntermediateSize == 0) //No input buffer
        return 0;

    std::streamsize inAvail;
    if(type == UDP_PEER)
        inAvail = 0;
    else{
        inAvail = egptr()-gptr();
        memmove(eback(), gptr(), inAvail);
    }

    try {
        inAvail += receive(eback()+inAvail, inputIntermediateSize-inAvail);
    } catch(Exception err) {

    }

    setg(eback(), eback(), eback()+inAvail);
    return inAvail;
}

std::streamsize Socket::receive(char_type* buffer, std::streamsize size) {
    if(type == TCP_SERVER)
        throw Exception(Exception::BAD_TYPE);
    if(status != Socket::Status::READY && status != Socket::Status::BUSY)
        return 0;
    size = std::min(size, showmanyc());
    if(size == 0)
        return 0;

    switch(type) {
        case UDP_PEER: {
            struct sockaddr_storage remoteAddr;
            #ifdef WIN32
            int addrSize = sizeof(remoteAddr);
            #else
            unsigned int addrSize = sizeof(remoteAddr);
            #endif
            int result = recvfrom(handle, (char*)buffer, size, 0, reinterpret_cast<struct sockaddr*>(&remoteAddr), &addrSize);

            if(result <= 0) {
                portRemote = 0;
                hostRemote = "";
                throw Exception(Exception::ERROR_READ);
            }else
                readSockaddr(&remoteAddr, hostRemote, portRemote);

            return result;
        }
        case TCP_CLIENT:
        case TCP_SERVERS_CLIENT: {
            int result = recv(handle, (char*)buffer, size, 0);

            if(result <= 0)
                throw Exception(Exception::ERROR_READ);

            return result;
        }
        default:
        case NONE:
        case TCP_SERVER:
            throw Exception(Exception::BAD_TYPE);
    }
}

std::streamsize Socket::send(const char_type* buffer, std::streamsize size) {
    if(type == TCP_SERVER)
        throw Exception(Exception::BAD_TYPE);
    if(status != Socket::Status::READY || size == 0)
        return 0;

    switch(type) {
        case UDP_PEER: {
            AddrinfoContainer info = getSocketInfoFor(hostRemote.c_str(), portRemote, false);

            size_t sentBytes = 0;
            while(sentBytes < (size_t)size) {
                int result = ::sendto(handle, (const char*)buffer + sentBytes, size - sentBytes, 0, info->ai_addr, info->ai_addrlen);
                if(result <= 0) {
                    status = BUSY;
                    throw Exception(Exception::ERROR_SEND);
                }
                sentBytes += result;
            }

            return sentBytes;
        }
        case TCP_CLIENT:
        case TCP_SERVERS_CLIENT: {
            size_t sentBytes = 0;
            while(sentBytes < (size_t)size) {
                int result = ::send(handle, (const char*)buffer + sentBytes, size - sentBytes, 0);
                if(result <= 0) {
                    status = BUSY;
                    throw Exception(Exception::ERROR_SEND);
                }
                sentBytes += result;
            }
            return sentBytes;
        }
        default:
        case NONE:
        case TCP_SERVER:
            throw Exception(Exception::BAD_TYPE);
    }
}

std::streamsize Socket::redirect(const std::vector<std::shared_ptr<Socket>>& destinations) {
    if(type == TCP_SERVER)
        throw Exception(Exception::BAD_TYPE);

    std::streamsize size = 0;
    while(in_avail()) {
        auto length = egptr()-gptr();
        for(const auto& destination : destinations)
            if(destination->sputn(gptr(), length) < length)
                throw Exception(Exception::ERROR_SEND);
        gbump(length);
        size += length;
        advanceInputBuffer();
    }

    return size;
}

std::streamsize Socket::getInputBufferSize() {
    return inputIntermediateSize;
}

std::streamsize Socket::getOutputBufferSize() {
    return epptr()-pbase();
}

void Socket::setInputBufferSize(std::streamsize n) {
    if(eback()) delete[] eback();
    if(type != TCP_SERVER && n > 0) {
        char_type* readBuffer = new char_type[n];
        setg(readBuffer, readBuffer, readBuffer);
        inputIntermediateSize = n;
    }else{
        setg(NULL, NULL, NULL);
        inputIntermediateSize = 0;
    }
}

void Socket::setOutputBufferSize(std::streamsize n) {
    if(pbase()) delete[] pbase();
    if(type != TCP_SERVER && n > 0) {
        char_type* writeBuffer = new char_type[n];
        setp(writeBuffer, writeBuffer+n);
    }else
        setp(NULL, NULL);
}

void Socket::setBlockingMode(bool blocking) {
    #ifdef WIN32
    unsigned long flag = !blocking;
    if(ioctlsocket(handle, FIONBIO, &flag) != 0)
    #else
    int flags = fcntl(handle, F_GETFL);
    if(blocking)
        flags &= ~O_NONBLOCK;
    else
        flags |= O_NONBLOCK;
    if(fcntl(handle, F_SETFL, flags) == -1)
    #endif
        throw Exception(Exception::ERROR_IOCTL);
}

void Socket::setBroadcast(bool active) {
    if(type != UDP_PEER || ipVersion != IPv4)
        throw Exception(Exception::BAD_PROTOCOL);

    #ifdef WIN32
    char flag = 1;
    #else
    int flag = 1;
    #endif
    if(setsockopt(handle, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag)) == -1)
        throw Exception(Exception::ERROR_SET_SOCK_OPT);
}

void Socket::setMulticastGroup(const std::string& address, bool join) {
    if(type != UDP_PEER)
        throw Exception(Exception::BAD_PROTOCOL);

    if(ipVersion == IPv4) {
        struct in_addr sin;
        if(inet_pton(AF_INET, address.c_str(), &sin) == -1)
            throw Exception(Exception::ERROR_RESOLVING_ADDRESS);

        if((ntohl(sin.s_addr) & 0xF0000000) == 0xE0000000) {
            struct ip_mreq mreq;
            mreq.imr_multiaddr = sin;
            mreq.imr_interface.s_addr = 0;

            if(setsockopt(handle, IPPROTO_IP, (join) ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) == -1)
                throw Exception(Exception::ERROR_SET_SOCK_OPT);
        }
    }else{
        struct in6_addr sin;
        if(inet_pton(AF_INET6, address.c_str(), &sin) == -1)
            throw Exception(Exception::ERROR_RESOLVING_ADDRESS);

        if(sin.s6_addr[0] == 0xFF) {
            struct ipv6_mreq mreq;
            mreq.ipv6mr_multiaddr = sin;
            mreq.ipv6mr_interface = 0;

            if(setsockopt(handle, IPPROTO_IPV6, (join) ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP, (const char*)&mreq, sizeof(ipv6_mreq)) == -1)
                throw Exception(Exception::ERROR_SET_SOCK_OPT);
        }
    }
}

std::shared_ptr<Socket> Socket::accept() {
    if(type != TCP_SERVER)
        throw Exception(Exception::BAD_TYPE);

    struct sockaddr_storage remoteAddr;
    #ifdef WIN32
    int addrSize = sizeof(remoteAddr);
    #else
    unsigned int addrSize = sizeof(remoteAddr);
    #endif

    int clientHandle = ::accept(handle, reinterpret_cast<struct sockaddr*>(&remoteAddr), &addrSize);
    if(clientHandle == -1) return nullptr;

    std::shared_ptr<Socket> client = SocketFactory();
    client->ipVersion = ipVersion;
    client->type = TCP_SERVERS_CLIENT;
    client->status = READY;
    client->handle = clientHandle;
    client->hostLocal = hostLocal;
    client->portLocal = portLocal;
    readSockaddr(&remoteAddr, client->hostRemote, client->portRemote);
    client->setBlockingMode(false);
    clients.insert(client);

    return client;
}

void Socket::disconnect() {
    ipVersion = ANY;
    type = NONE;
    status = NOT_CONNECTED;
    setInputBufferSize(getInputBufferSize());
    setOutputBufferSize(getOutputBufferSize());
    clients.clear();
    if(handle != -1) {
        closesocket(handle);
        handle = -1;
    }
}

};


text:
var definition = require("ui/gestures");
(function (GestureTypes) {
    GestureTypes[GestureTypes["Tap"] = 1 << 0] = "Tap";
    GestureTypes[GestureTypes["DoubleTap"] = 1 << 1] = "DoubleTap";
    GestureTypes[GestureTypes["Pinch"] = 1 << 2] = "Pinch";
    GestureTypes[GestureTypes["Pan"] = 1 << 3] = "Pan";
    GestureTypes[GestureTypes["Swipe"] = 1 << 4] = "Swipe";
    GestureTypes[GestureTypes["Rotation"] = 1 << 5] = "Rotation";
    GestureTypes[GestureTypes["LongPress"] = 1 << 6] = "LongPress";
})(exports.GestureTypes || (exports.GestureTypes = {}));
var GestureTypes = exports.GestureTypes;
(function (GestureStateTypes) {
    GestureStateTypes[GestureStateTypes["Possible"] = 1 << 0] = "Possible";
    GestureStateTypes[GestureStateTypes["Recognized"] = 1 << 1] = "Recognized";
    GestureStateTypes[GestureStateTypes["Failed"] = 1 << 2] = "Failed";
    GestureStateTypes[GestureStateTypes["Cancelled"] = 1 << 3] = "Cancelled";
    GestureStateTypes[GestureStateTypes["Began"] = 1 << 4] = "Began";
    GestureStateTypes[GestureStateTypes["Changed"] = 1 << 5] = "Changed";
    GestureStateTypes[GestureStateTypes["Ended"] = 1 << 6] = "Ended";
})(exports.GestureStateTypes || (exports.GestureStateTypes = {}));
var GestureStateTypes = exports.GestureStateTypes;
(function (SwipeDirection) {
    SwipeDirection[SwipeDirection["Right"] = 1 << 0] = "Right";
    SwipeDirection[SwipeDirection["Left"] = 1 << 1] = "Left";
    SwipeDirection[SwipeDirection["Up"] = 1 << 2] = "Up";
    SwipeDirection[SwipeDirection["Down"] = 1 << 3] = "Down";
})(exports.SwipeDirection || (exports.SwipeDirection = {}));
var SwipeDirection = exports.SwipeDirection;
function observe(target, type, callback) {
    var observer = new definition.GesturesObserver(callback);
    observer.observe(target, type);
    return observer;
}
exports.observe = observe;
function toString(type, separator) {
    var types = new Array();
    if (type & definition.GestureTypes.Tap) {
        types.push("Tap");
    }
    if (type & definition.GestureTypes.DoubleTap) {
        types.push("DoubleTap");
    }
    if (type & definition.GestureTypes.Pinch) {
        types.push("Pinch");
    }
    if (type & definition.GestureTypes.Pan) {
        types.push("Pan");
    }
    if (type & definition.GestureTypes.Swipe) {
        types.push("Swipe");
    }
    if (type & definition.GestureTypes.Rotation) {
        types.push("Rotation");
    }
    if (type & definition.GestureTypes.LongPress) {
        types.push("LongPress");
    }
    return types.join(separator);
}
exports.toString = toString;
function fromString(type) {
    var t = type.trim().toLowerCase();
    if (t === "tap") {
        return definition.GestureTypes.Tap;
    }
    else if (t === "doubletap") {
        return definition.GestureTypes.DoubleTap;
    }
    else if (t === "pinch") {
        return definition.GestureTypes.Pinch;
    }
    else if (t === "pan") {
        return definition.GestureTypes.Pan;
    }
    else if (t === "swipe") {
        return definition.GestureTypes.Swipe;
    }
    else if (t === "rotation") {
        return definition.GestureTypes.Rotation;
    }
    else if (t === "longpress") {
        return definition.GestureTypes.LongPress;
    }
    return undefined;
}
exports.fromString = fromString;

redpajama_set_name: RedPajamaGithub


text:
package de.tum.in.www1.jReto.connectivity;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

import de.tum.in.www1.jReto.module.api.Connection;
import de.tum.in.www1.jReto.packet.Packet;
import de.tum.in.www1.jReto.packet.PacketType;
import de.tum.in.www1.jReto.routing.Node;

/**
* PacketConnections are used to send and receive packets. Packets used by Reto can be any data of any fixed length,
* but the first four bytes always contain the packet's type.
*
* A PacketConnection encapsulates the idea of a logical connection. It adds an additional indirection between a Connection as provided by
* the Reto API and underlying connections. This allows the PacketConnection to switch between different underlying connections, and even exist without
* an underlying connection. This is the basis of features such as automatic reconnect, and offering automatic connection upgrades.
*
* Packets can be sent by calling the write() method. If data is currently written, or no underlying connection is available, the packet is buffered
* until it can be sent.
*
* A PacketConnection can have multiple delegates. Amongst other events, the PacketConnection delegates the handling of packets to multiple delegates that implement
* the PacketHandler protocol. The PacketHandlers may specify the packet types they are able to handler; the packet connection will call the according handler's
* handlePacket method.
*
* The PacketConnection itself is agnostic of the different packet types; the introduction of new packet types and handlers does not require any changes
* in the PacketConnection class. This allows Reto to split up different functionality of Connections into different classes,
* e.g. the TransferManager and ReliabilityManager, which are both PacketHandlers.
*/
public class PacketConnection {
	/**
	* The delegate protocol used with the PacketConnection.
	* It allows delegates to specify which types of packets they wish to handle.
	*/
	public static interface Handler {
	    /** Called when the underlying connection closed. */
		void onUnderlyingConnectionClose(PacketConnection connection);
	    /** Called when the underlying connection is about to be switched to a different one. */
		void onWillSwapUnderlyingConnection(PacketConnection connection);
	    /** Called when confirmation that the underlying connection did connect is received. */
		void onUnderlyingConnectionConnected(PacketConnection connection);
	    /** Called whenever all packets that were queued have been sent, i.e. the connection is ready for more data if available. */
		void onNoPacketsLeft(PacketConnection connection);
	    /** An array of packet types that are handled by this PacketHandler. */
		Set<PacketType> getHandledPacketTypes();
	    /** Called when a packet is received that should be handled */
		void handlePacket(ByteBuffer data, PacketType type);
	}

    /** The underlying connection used by this PacketConnection */
	private de.tum.in.www1.jReto.module.api.Connection underlyingConnection;
    /** The PacketConnection's delegates. */
	private Set<Handler> delegates = new HashSet<>();
    /**
    * The PacketConnection's delegates, organized by the packet type they handle.
    */
	private Map<PacketType, Handler> packetHandlers = new HashMap<>();
    /** The connection's identifier. This identifier is used to associate new incoming underlying connections with exising packet connections. */
	private final UUID connectionIdentifier;
    /** This connection's destinations. */
	private final Set<Node> destinations;
    /** Buffer for unsent packets. */
	private Queue<Packet> unsentPackets;
    /** Whether a packet is currently being sent. */
	private boolean isSendingPacket = false;
    /** Whether a connection is currently being established. */
	private boolean isEstablishingConnection = false;

	/** Handles events from the underlying connection and calls appropriate methods. */
	private final de.tum.in.www1.jReto.module.api.Connection.Handler underlyingConnectionHandler = new de.tum.in.www1.jReto.module.api.Connection.Handler() {
		@Override
		public void onDataReceived(de.tum.in.www1.jReto.module.api.Connection connection,
				ByteBuffer data) {
			if (connection != PacketConnection.this.underlyingConnection) {
				System.out.println("Received data from unused underlying connection.");
				return;
			}

			PacketType packetType = PacketType.fromData(data);
			Handler handler = PacketConnection.this.packetHandlers.get(packetType);

			if (handler == null) {
				System.err.println("Warning: There is no handler for packets of type "+ packetType+ ". Registered handlers: "+ PacketConnection.this.packetHandlers);
				return;
			}

			handler.handlePacket(data, packetType);
		}

		@Override
		public void onDataSent(de.tum.in.www1.jReto.module.api.Connection connection) {
			if (connection != PacketConnection.this.underlyingConnection) {
				System.out.println("Received onDataSent from unused underlying connection.");
				return;
			}
			PacketConnection.this.isSendingPacket = false;
			PacketConnection.this.write();
		}

		@Override
		public void onConnect(de.tum.in.www1.jReto.module.api.Connection connection) {
			if (connection != PacketConnection.this.underlyingConnection) {
				System.out.println("Received onConnect from unused underlying connection.");
				return;
			}

			PacketConnection.this.onConnect();
		}

		@Override
		public void onClose(de.tum.in.www1.jReto.module.api.Connection connection) {
			if (connection != PacketConnection.this.underlyingConnection) {
				System.out.println("Previous underlying connection closed.");
				connection.setHandler(null);
				return;
			}

			PacketConnection.this.delegates.forEach(delegate -> delegate.onUnderlyingConnectionClose(PacketConnection.this));
		}
	};

    /**
    * Initializes a new PacketConnection.
    *
    * @param connection An underlying connection to use with this packet connection. May be nil and set later.
    * @param connectionIdentifier This connection's identifier.
    * @param destinations The connection's destinations.
    */
	public PacketConnection(de.tum.in.www1.jReto.module.api.Connection underlyingConnection, UUID connectionIdentifier, Set<Node> destinations) {
		this.unsentPackets = new LinkedBlockingQueue<Packet>();
		this.underlyingConnection = underlyingConnection;
		this.connectionIdentifier = connectionIdentifier;
		this.destinations = destinations;

		if (this.underlyingConnection != null) {
			this.underlyingConnection.setHandler(this.underlyingConnectionHandler);
			if (this.underlyingConnection.isConnected()) this.onConnect();
		}
	}

	private void onConnect() {
		this.delegates.forEach(delegate -> delegate.onUnderlyingConnectionConnected(this));

		this.write();
	}

    /** Add a delegate */
	public void addDelegate(Handler delegate) {
		this.delegates.add(delegate);

		for (PacketType type : delegate.getHandledPacketTypes()) {
			this.packetHandlers.put(type, delegate);
		}
	}
	/** Remove a delegate*/
	public void removeDelegate(Handler delegate) {
		this.delegates.remove(delegate);
		// TODO remove packet handlers
	}

	public Connection getUnderlyingConnection() {
		return this.underlyingConnection;
	}

	public Set<Node> getDestinations() {
		return this.destinations;
	}

	public boolean getIsEstablishingConnection() {
		return this.isEstablishingConnection;
	}

	public void setIsEstablishingConnection(boolean isEstablishingConnection) {
		this.isEstablishingConnection = isEstablishingConnection;
	}

    /**
    * Swaps this PacketConnection's underlying connection to a new one. The new connection can also be nil; in that case the packet connection will be disconnected.
    */
	public void swapUnderlyingConnection(de.tum.in.www1.jReto.module.api.Connection underlyingConnection) {
		if (this.underlyingConnection == underlyingConnection) return;

		if (this.underlyingConnection != null) {
			this.delegates.forEach(delegate -> delegate.onWillSwapUnderlyingConnection(this));
		}

		Connection previousConnection = this.underlyingConnection;
		this.underlyingConnection = underlyingConnection;
		if (this.underlyingConnection != null) this.underlyingConnection.setHandler(this.underlyingConnectionHandler);

		if (previousConnection != null && previousConnection.isConnected()) previousConnection.close();

		this.isSendingPacket = false;
		this.unsentPackets.clear();

		if (this.underlyingConnection != null && this.underlyingConnection.isConnected()) this.onConnect();
	}

	public UUID getConnectionIdentifier() {
		return this.connectionIdentifier;
	}

	public boolean getIsConnected() {
		return this.underlyingConnection != null && this.underlyingConnection.isConnected();
	}

    /**
    * Closes the underlying connection
    */
	public void disconnectUnderlyingConnection() {
		this.underlyingConnection.close();
	}
	/**
	 * Writes a packet. The packet will be buffered and sent later if the connection is currently disconnected.
	 */
	public void writePacket(Packet packet) {
		this.unsentPackets.add(packet);
		this.write();
	}
    /**
    * Attempts to write any buffered packets, or notifies it's delegates that all packes have been written.
    */
	public void write() {
		if (this.isSendingPacket)
			return;
		if (this.underlyingConnection == null
				|| !this.underlyingConnection.isConnected())
			return;

		Packet nextPacket = null;
		if (this.unsentPackets.size() != 0) {
			nextPacket = this.unsentPackets.poll();
		}

		if (nextPacket != null) {
			this.isSendingPacket = true;
			this.underlyingConnection.writeData(nextPacket.serialize());
		} else {
			this.delegates.forEach(delegate -> delegate.onNoPacketsLeft(this));
		}
	}
}


text:
%-------------------------------------------------------------------------------
%	SECTION TITLE
%-------------------------------------------------------------------------------
\cvsection{Education}

%-------------------------------------------------------------------------------
%	CONTENT
%-------------------------------------------------------------------------------
\begin{cventries}

%---------------------------------------------------------
  \cventry
    {B.S. in Computer Science and Engineering} % Degree
    {POSTECH(Pohang University of Science and Technology)} % Institution
    {Pohang, S.Korea} % Location
    {Mar. 2010 - Exp. Aug. 2017} % Date(s)
    {
      \begin{cvitems} % Description(s) bullet points
        \item {Got a Chun Shin-Il Scholarship which is given to promising students in CSE Dept.}
      \end{cvitems}
    }

%---------------------------------------------------------
\end{cventries}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Gets server rights</title>

iis_get_server_by_path

iis_get_service_state

IIS Functions

PHP Manual

iis_get_server_rights

(PECL iisfunc SVN)

iis_get_server_rights — Gets server rights

Description

   int iis_get_server_rights
    ( int $server_instance
   , string $virtual_path
   )

Warning
This function is
currently not documented; only its argument list is available.

iis_get_server_by_path

iis_get_service_state

IIS Functions

PHP Manual


text:
import os
import glob
import sys
import json
sys.path.append(os.path.abspath(".."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'ocradmin.settings'

sys.path.insert(0, "lib")

from ocradmin.nodelib import nodes as nodetree_nodes

from nodetree import script, registry

def run(nodelist, outpath):
    s = script.Script(nodelist)
    term = s.get_terminals()[0]
    print "Rendering to %s" % outpath
    os.environ["NODETREE_WRITE_FILEOUT"] = "1"
    out = s.add_node("util.FileOut", "Output",
            params=[("path", os.path.abspath(outpath))])
    out.set_input(0, term)
    out.eval()

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "Usage: %s <script> <output>" % sys.argv[0]
        sys.exit(1)

    nodes = None
    with open(sys.argv[1], "r") as f:
        nodes = json.load(f)

    if nodes is None:
        print "No nodes found in script"
        sys.exit(1)

    run(nodes, sys.argv[2])


text:
package org.apache.geode.internal.cache.partitioned.rebalance.model;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import org.apache.geode.internal.cache.persistence.PersistentMemberID;

/**
 * Represents a single bucket.
 */
public class Bucket implements Comparable<Bucket> {
  private final int id;
  private final Set<Member> membersHosting = new TreeSet<>();
  private final Set<PersistentMemberID> offlineMembers;
  private float load;
  private long bytes;
  private float primaryLoad;
  private int redundancy = -1;
  private Member primary;

  public Bucket(int id) {
    this(id, 0, 0, new HashSet<>());
  }

  public Bucket(int id, float load, long bytes, Set<PersistentMemberID> offlineMembers) {
    this.id = id;
    this.load = load;
    this.bytes = bytes;
    this.offlineMembers = offlineMembers;
  }

  void changeLoad(float change) {
    load += change;
  }

  void changePrimaryLoad(float change) {
    primaryLoad += change;
  }

  void changeBytes(long change) {
    bytes += change;
  }

  void addOfflineMembers(Collection<? extends PersistentMemberID> members) {
    offlineMembers.addAll(members);
  }

  public void setPrimary(Member member, float primaryLoad) {
    if (primary == PartitionedRegionLoadModel.INVALID_MEMBER) {
      return;
    }
    if (primary != null) {
      primary.removePrimary(this);
    }
    primary = member;
    this.primaryLoad = primaryLoad;
    if (primary != PartitionedRegionLoadModel.INVALID_MEMBER && primary != null) {
      addMember(primary);
      member.addPrimary(this);
    }
  }

  public boolean addMember(Member targetMember) {
    if (getMembersHosting().add(targetMember)) {
      redundancy++;
      targetMember.addBucket(this);
      return true;
    }

    return false;
  }

  public boolean removeMember(Member targetMember) {
    if (getMembersHosting().remove(targetMember)) {
      if (targetMember == primary) {
        setPrimary(null, 0);
      }
      redundancy--;
      targetMember.removeBucket(this);
      return true;
    }
    return false;
  }

  public int getRedundancy() {
    return redundancy + offlineMembers.size();
  }

  public int getOnlineRedundancy() {
    return redundancy;
  }

  public float getLoad() {
    return load;
  }

  public int getId() {
    return id;
  }

  public long getBytes() {
    return bytes;
  }

  @Override
  public String toString() {
    return "Bucket(id=" + getId() + ",load=" + load + ")";
  }

  public float getPrimaryLoad() {
    return primaryLoad;
  }

  public Set<Member> getMembersHosting() {
    return membersHosting;
  }

  public Member getPrimary() {
    return primary;
  }

  public Collection<? extends PersistentMemberID> getOfflineMembers() {
    return offlineMembers;
  }

  @Override
  public int hashCode() {
    return id;
  }

  @Override
  public boolean equals(Object other) {
    if (!(other instanceof Bucket)) {
      return false;
    }
    Bucket o = (Bucket) other;
    return id == o.id;
  }

  @Override
  public int compareTo(Bucket other) {
    return Integer.compare(id, other.id);
  }
}


text:
import DeepFried2 as df

from examples.utils import make_progressbar

from train import train
from test import test
from model import net, lenet2

if __name__ == "__main__":
    print("THIS IS JUST AN EXAMPLE; DO NOT BASE DECISIONS ON THIS.")
    print("Please don't take these numbers as a benchmark.")
    print("A fair comparison would run all experiments multiple times AND RUN MORE THAN FIVE EPOCHS.")

    batch_size = 64

    (Xtrain, ytrain), (Xval, yval), (Xtest, ytest) = df.datasets.mnist.data()

    criterion = df.ClassNLLCriterion()

    def run(optim):
        progress = make_progressbar('Training with ' + str(optim), 5)
        progress.start()

        model = net()
        model.training()
        for epoch in range(5):
            train(Xtrain, ytrain, model, optim, criterion, batch_size, 'train')
            train(Xtrain, ytrain, model, optim, criterion, batch_size, 'stats')
            progress.update(epoch+1)

        progress.finish()

        model.evaluate()
        nll, _ = test(Xtrain, ytrain, model, batch_size)
        _, nerr = test(Xval, yval, model, batch_size)

        print("Trainset NLL: {:.2f}".format(nll))
        print("Testset errors: {}".format(nerr))

    run(df.SGD(lr=1e-1))
    run(df.Momentum(lr=1e-2, momentum=0.95))
    run(df.Nesterov(lr=1e-2, momentum=0.90))
    run(df.AdaGrad(lr=1e-2, eps=1e-4))
    run(df.RMSProp(lr=1e-3, rho=0.90, eps=1e-5))
    run(df.DQNProp(lr=1e-3, rho=0.90, eps=1e-5))
    run(df.AdaDelta(rho=0.99, lr=5e-1, eps=1e-4))
    run(df.Adam(alpha=1e-3, beta1=0.95, beta2=0.9, eps=1e-8))


text:
import createAll from 'react-redux/lib/components/createAll';
import { ActionCreators } from './devTools';

export default function createDevTools(React) {
  const { PropTypes, Component } = React;
  const { connect } = createAll(React);

  @connect(
    state => state,
    ActionCreators
  )
  class DevTools extends Component {
    render() {
      const { monitor: Monitor } = this.props;
      return <Monitor {...this.props} />;
    }
  }

  return class DevToolsWrapper extends Component {
    static propTypes = {
      monitor: PropTypes.func.isRequired,
      store: PropTypes.shape({
        devToolsStore: PropTypes.shape({
          dispatch: PropTypes.func.isRequired
        }).isRequired
      }).isRequired
    };

    constructor(props, context) {
      if (props.store && !props.store.devToolsStore) {
        console.error(
          'Could not find the devTools store inside your store. ' +
          'Have you applied devTools() store enhancer?'
        );
      }
      super(props, context);
    }

    render() {
      return (
        <DevTools {...this.props}
                  store={this.props.store.devToolsStore} />
      );
    }
  };
}


text:
using SX.WebCore.DbModels.Abstract;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GE.WebUI.Models
{
    [Table("D_HUMOR")]
    public class Humor : SxMaterial
    {
        [MaxLength(100)]
        public string UserName { get; set; }
    }
}


text:
'use strict';

/**
 * 어떤 일을 하고 있습니까?
 * @class UniformMatrix4fvDataPair
 * @param gl 변수
 */
var UniformMatrix4fvDataPair = function(gl, uniformName)
{
	if (!(this instanceof UniformMatrix4fvDataPair))
	{
		throw new Error(Messages.CONSTRUCT_ERROR);
	}
	this.gl = gl;
	this.name = uniformName;
	this.uniformLocation;
	this.matrix4fv;
};

/**
 * 어떤 일을 하고 있습니까?
 * @param gl 변수
 */
UniformMatrix4fvDataPair.prototype.bindUniform = function()
{
	this.gl.uniformMatrix4fv(this.uniformLocation, false, this.matrix4fv);
};


text:
package org.blackchip.scorebored.talker;

/**
 * Listener for talk events.
 */
public interface TalkListener {

    /**
     * Invoked when a phrase to be spoken has started.
     *
     * @param speech the text that will be spoken.
     */
    public void talkStarted(Speech speech);

    /**
     * Invoked when the previous text has finished being spoken,
     */
    public void talkEnded();

}


text:
using content::NavigationController;

LanguageState::LanguageState(NavigationController* nav_controller)
    : navigation_controller_(nav_controller),
      page_needs_translation_(false),
      translation_pending_(false),
      translation_declined_(false),
      in_page_navigation_(false),
      translate_enabled_(false),
      observer_(NULL) {
}

LanguageState::~LanguageState() {
}

void LanguageState::DidNavigate(
    const content::LoadCommittedDetails& details) {
  in_page_navigation_ = details.is_in_page;
  if (in_page_navigation_ || !details.is_main_frame)
    return;  // Don't reset our states, the page has not changed.

  bool reload =
      details.entry->GetTransitionType() == content::PAGE_TRANSITION_RELOAD ||
      details.type == content::NAVIGATION_TYPE_SAME_PAGE;
  if (reload) {
    // We might not get a LanguageDetermined notifications on reloads. Make sure
    // to keep the original language and to set current_lang_ so
    // IsPageTranslated() returns false.
    current_lang_ = original_lang_;
  } else {
    prev_original_lang_ = original_lang_;
    prev_current_lang_ = current_lang_;
    original_lang_.clear();
    current_lang_.clear();
  }

  translation_pending_ = false;
  translation_declined_ = false;

  SetTranslateEnabled(false);
}

void LanguageState::LanguageDetermined(const std::string& page_language,
                                       bool page_needs_translation) {
  if (in_page_navigation_ && !original_lang_.empty()) {
    // In-page navigation, we don't expect our states to change.
    // Note that we'll set the languages if original_lang_ is empty.  This might
    // happen if the we did not get called on the top-page.
    return;
  }
  page_needs_translation_ = page_needs_translation;
  original_lang_ = page_language;
  current_lang_ = page_language;
}

bool LanguageState::InTranslateNavigation() const {
  // The user is in the same translate session if
  //   - no translation is pending
  //   - this page is in the same language as the previous page
  //   - the previous page had been translated
  //   - the new page was navigated through a link.
  return
      !translation_pending_ &&
      prev_original_lang_ == original_lang_ &&
      prev_original_lang_ != prev_current_lang_ &&
      navigation_controller_->GetActiveEntry() &&
      navigation_controller_->GetActiveEntry()->GetTransitionType() ==
          content::PAGE_TRANSITION_LINK;
}

std::string LanguageState::AutoTranslateTo() const {
  if (InTranslateNavigation() &&
      // The page is not yet translated.
      original_lang_ == current_lang_ ) {
    return prev_current_lang_;
  }

  return std::string();
}

void LanguageState::SetTranslateEnabled(bool value) {
  if (translate_enabled_ == value)
    return;

  translate_enabled_ = value;
  if (observer_) {
    content::WebContents* web_contents =
        navigation_controller_->GetWebContents();
    observer_->OnTranslateEnabledChanged(web_contents);
  }
}

bool LanguageState::HasLanguageChanged() const {
  return original_lang_ != prev_original_lang_;
}


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef TROLLCOIN_RANDOM_H
#define TROLLCOIN_RANDOM_H

#include "uint256.h"

#include <stdint.h>

/* Seed OpenSSL PRNG with additional entropy data */
void RandAddSeed();

/**
 * Functions to gather random data via the OpenSSL PRNG
 */
void GetRandBytes(unsigned char* buf, int num);
uint64_t GetRand(uint64_t nMax);
int GetRandInt(int nMax);
uint256 GetRandHash();

/**
 * Function to gather random data from multiple sources, failing whenever any
 * of those source fail to provide a result.
 */
void GetStrongRandBytes(unsigned char* buf, int num);

/**
 * Fast randomness source. This is seeded once with secure random data, but
 * is completely deterministic and insecure after that.
 * This class is not thread-safe.
 */
class FastRandomContext {
public:
    explicit FastRandomContext(bool fDeterministic=false);

    uint32_t rand32() {
        Rz = 36969 * (Rz & 65535) + (Rz >> 16);
        Rw = 18000 * (Rw & 65535) + (Rw >> 16);
        return (Rw << 16) + Rz;
    }

    uint32_t Rz;
    uint32_t Rw;
};

/* Number of random bytes returned by GetOSRand.
 * When changing this constant make sure to change all call sites, and make
 * sure that the underlying OS APIs for all platforms support the number.
 * (many cap out at 256 bytes).
 */
static const ssize_t NUM_OS_RANDOM_BYTES = 32;

/** Get 32 bytes of system entropy. Do not use this in application code: use
 * GetStrongRandBytes instead.
 */
void GetOSRand(unsigned char *ent32);

/** Check that OS randomness is available and returning the requested number
 * of bytes.
 */
bool Random_SanityCheck();

#endif // TROLLCOIN_RANDOM_H


text:
package main

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

func init() {
	os.Chdir(filepath.Dir(os.Args[0]))
	os.Mkdir("logs", 0755)
	runtime.GOMAXPROCS(runtime.NumCPU())
}

func main() {
	var err error
	if err = InitGlobalConfig(); err != nil {
		fmt.Println("failed to init global config:", err)
		return
	}
	if err = initPublicKeyAndPrivateKey(); err != nil {
		panic(err)
	}
	go func() {
		fmt.Printf("start metric interface %s\n", config.MetricBind)
		fmt.Printf("%s\n", http.ListenAndServe(config.MetricBind, nil))
	}()
	if err = initTSDB(); err != nil {
		fmt.Println("failed to init tsdb storage:", err)
		return
	}
	if err = InitMysqlConnPool(); err != nil {
		fmt.Println("failed to init mysql connection pool:", err)
		return
	}
	if err := InitServer(); err != nil {
		fmt.Println("failed to init http server:", err)
		return
	}
}


text:
Topple is a small script for running commands associated with vertices of a graph with versions in order.
Most likely, the vertices of the graph are subprojects in a big project and an edge from A to B means A depends on B.

**Most of the time, the right tool for that sort of thing is Make.**
I wrote this partly for fun and partly because I actually thought it'd help me save some time with a project (it did!).

Suppose you have the graph (stored in `_topple`):

    A --> B --> C
          \
           \--> D --> E

... some commands associated with A, B, C, D, and E, their current versions, and their versions at the last time you ran the command.

Suppose the version of B, stored in `B/.topple-version`, is different than the version of B from when you last ran `topple`.
Topple keeps track of this in `.topple-status`.
Then `topple` will run the commands for B, C, and D, then E.

The `_topple` file for the example above might look like this:

    # A comment.

    A:
        # Some commands for A.

    B: A
        # Some commands for B.

    C: B
        # Some commands for C.

    D: B
        # Some commands for D.

    E: A B D
        # Not necessary to list A and B (because D depends on them).

Looks suspiciously like a Makefile!

If these commands create files whose modification times you can easily compare to determine whether or not you want to rerun the commands for a vertex (say, if B's output is newer than C's, we want to rerun the commands for C), then **you should use Make**.

Topple will be a little more annoying because you have to specify that a vertex has a new version yourself.
A new version might come in when you `git pull`, along with sources modified by your teammate.
Of course, you yourself can increase the version by running `topup` or `topup <path>`.

When you run `topple` in the directory with a `_topple` file it'll rebuild everything downstream of the vertex with the new version.

# Installing

Topple is written in OCaml. If you have OPAM,

    $ git clone https://github.com/jonathanyc/topple.git
    $ opam pin add topple topple

... should both install dependencies and install `topple` and `topup` to your `$PATH`.

# Automatic Versioning

Starting with version 0.3.0, Topple has support for "automatic versioning" of directories based on glob patterns.
Topple derives a tree of filenames that match a positive pattern and do not match any negative patterns then hashes the tree with the last modification time of the files in the tree.
This approach takes care of deletion of files in addition to addition of files, unlike the naive approach that only considers modification times.

The syntax is as follows:

    <pos> ::= <glob>
    <neg> ::= !<glob>

    <pos | neg>
    <subproject>: <dep> ...
        <command>
        ...

... for example, we can add a subproject `core` whose version depends on all of the `*.ml` files except for `tileAuto.ml`, which is generated:

    *.ml !tileAuto.ml
    core:
        echo "Building core subproject!"

The hash is then stored instead of the version number in the `.topple-status` file.
The presence of patterns overrides the existence of a `.topple-version` file.

# Really, what's the use?

As far as I know, Make is great for when:

1. You want to generate an artifact by running some commands,
2. you can easily query the modification time of the artifact,
3. you can easily query the modification times of the inputs,
4. so you can compare the last modification time of an input with that of the artifact in order to determine whether or not you need to run the commands again.

This works for almost every project I've ever worked on. Unfortunately, I was working on an OCaml project with subprojects that installed as findlib packages (why I had to do this was another story!)
It seemed pretty terrible to have Make check the modification times of the files that findlib installed, somewhere deep in `~/.opam/...`, to the modification times of files in my project.
I could have had the commands create a "phony" file that served only to mark the last time the commands installing the subproject was run, but I decided I might as well have fun writing this instead.

# To Do

- Better parsing of the _topple file. It'd be nice to allow escapes in more places.
- More tests for Glob.


text:
#pragma once

#include <vector>

#include "Graphics/Commands/CommandBuffer.hpp"
#include "Graphics/Descriptors/Descriptor.hpp"
#include "Maths/Vector2.hpp"

namespace acid {
class Bitmap;

/**
 * @brief A representation of a Vulkan image, sampler, and view.
 */
class ACID_EXPORT Image : public Descriptor {
public:
	/**
	 * Creates a new image object.
	 * @param filter The magnification/minification filter to apply to lookups.
	 * @param addressMode The addressing mode for outside [0..1] range.
	 * @param samples The number of samples per texel.
	 * @param layout The layout that the image subresources accessible from.
	 * @param usage The intended usage of the image.
	 * @param format The format and type of the texel blocks that will be contained in the image.
	 * @param mipLevels The number of levels of detail available for minified sampling of the image.
	 * @param arrayLayers The number of layers in the image.
	 * @param extent The number of data elements in each dimension of the base level.
	 */
	Image(VkFilter filter, VkSamplerAddressMode addressMode, VkSampleCountFlagBits samples, VkImageLayout layout, VkImageUsageFlags usage,
		VkFormat format, uint32_t mipLevels, uint32_t arrayLayers, const VkExtent3D &extent);

	~Image();

	WriteDescriptorSet GetWriteDescriptor(uint32_t binding, VkDescriptorType descriptorType, const std::optional<OffsetSize> &offsetSize) const override;
	static VkDescriptorSetLayoutBinding GetDescriptorSetLayout(uint32_t binding, VkDescriptorType descriptorType, VkShaderStageFlags stage, uint32_t count);

	/**
	 * Copies the images pixels from memory to a bitmap. If this method is called from multiple threads at the same time Vulkan will crash!
	 * @param mipLevel The mipmap level index to sample.
	 * @param arrayLayer The array level to sample.
	 * @return A copy of the images pixels.
	 */
	std::unique_ptr<Bitmap> GetBitmap(uint32_t mipLevel = 0, uint32_t arrayLayer = 0) const;

	const VkExtent3D &GetExtent() const { return extent; }
	Vector2ui GetSize() const { return {extent.width, extent.height}; }
	VkFormat GetFormat() const { return format; }
	VkSampleCountFlagBits GetSamples() const { return samples; }
	VkImageUsageFlags GetUsage() const { return usage; }
	uint32_t GetMipLevels() const { return mipLevels; }
	uint32_t GetArrayLevels() const { return arrayLayers; }
	VkFilter GetFilter() const { return filter; }
	VkSamplerAddressMode GetAddressMode() const { return addressMode; }
	VkImageLayout GetLayout() const { return layout; }
	const VkImage &GetImage() { return image; }
	const VkDeviceMemory &GetMemory() { return memory; }
	const VkSampler &GetSampler() const { return sampler; }
	const VkImageView &GetView() const { return view; }

	static uint32_t GetMipLevels(const VkExtent3D &extent);

	/**
	 * Find a format in the candidates list that fits the tiling and features required.
	 * @param candidates Formats that are tested for features, in order of preference.
	 * @param tiling Tiling mode to test features in.
	 * @param features The features to test for.
	 * @return The format found, or VK_FORMAT_UNDEFINED.
	 */
	static VkFormat FindSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features);

	/**
	 * Gets if a format has a depth component.
	 * @param format The format to check.
	 * @return If the format has a depth component.
	 */
	static bool HasDepth(VkFormat format);

	/**
	 * Gets if a format has a depth component.
	 * @param format The format to check.
	 * @return If the format has a depth component.
	 */
	static bool HasStencil(VkFormat format);

	static void CreateImage(VkImage &image, VkDeviceMemory &memory, const VkExtent3D &extent, VkFormat format, VkSampleCountFlagBits samples,
		VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, uint32_t mipLevels, uint32_t arrayLayers, VkImageType type);
	static void CreateImageSampler(VkSampler &sampler, VkFilter filter, VkSamplerAddressMode addressMode, bool anisotropic, uint32_t mipLevels);
	static void CreateImageView(const VkImage &image, VkImageView &imageView, VkImageViewType type, VkFormat format, VkImageAspectFlags imageAspect,
		uint32_t mipLevels, uint32_t baseMipLevel, uint32_t layerCount, uint32_t baseArrayLayer);
	static void CreateMipmaps(const VkImage &image, const VkExtent3D &extent, VkFormat format, VkImageLayout dstImageLayout, uint32_t mipLevels,
		uint32_t baseArrayLayer, uint32_t layerCount);
	static void TransitionImageLayout(const VkImage &image, VkFormat format, VkImageLayout srcImageLayout, VkImageLayout dstImageLayout,
		VkImageAspectFlags imageAspect, uint32_t mipLevels, uint32_t baseMipLevel, uint32_t layerCount, uint32_t baseArrayLayer);
	static void InsertImageMemoryBarrier(const CommandBuffer &commandBuffer, const VkImage &image, VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask,
		VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
		VkImageAspectFlags imageAspect, uint32_t mipLevels, uint32_t baseMipLevel, uint32_t layerCount, uint32_t baseArrayLayer);
	static void CopyBufferToImage(const VkBuffer &buffer, const VkImage &image, const VkExtent3D &extent, uint32_t layerCount, uint32_t baseArrayLayer);
	static bool CopyImage(const VkImage &srcImage, VkImage &dstImage, VkDeviceMemory &dstImageMemory, VkFormat srcFormat, const VkExtent3D &extent,
		VkImageLayout srcImageLayout, uint32_t mipLevel, uint32_t arrayLayer);

protected:
	VkExtent3D extent;
	VkSampleCountFlagBits samples;
	VkImageUsageFlags usage;
	VkFormat format = VK_FORMAT_UNDEFINED;
	uint32_t mipLevels = 0;
	uint32_t arrayLayers;

	VkFilter filter;
	VkSamplerAddressMode addressMode;

	VkImageLayout layout;

	VkImage image = VK_NULL_HANDLE;
	VkDeviceMemory memory = VK_NULL_HANDLE;
	VkSampler sampler = VK_NULL_HANDLE;
	VkImageView view = VK_NULL_HANDLE;
};
}


text:
"""
Implements the "make clean" target

(C) 2017 Jack Lloyd

Botan is released under the Simplified BSD License (see license.txt)
"""

import os
import sys
import stat
import re
import optparse  # pylint: disable=deprecated-module
import logging
import json
import shutil
import errno

def remove_dir(d):
    try:
        if os.access(d, os.X_OK):
            logging.debug('Removing directory "%s"', d)
            shutil.rmtree(d)
        else:
            logging.debug('Directory %s was missing', d)
    except Exception as e: # pylint: disable=broad-except
        logging.error('Failed removing directory "%s": %s', d, e)

def remove_file(f):
    try:
        logging.debug('Removing file "%s"', f)
        os.unlink(f)
    except OSError as e:
        if e.errno != errno.ENOENT:
            logging.error('Failed removing file "%s": %s', f, e)

def remove_all_in_dir(d):
    if os.access(d, os.X_OK):
        logging.debug('Removing all files in directory "%s"', d)

        for f in os.listdir(d):
            full_path = os.path.join(d, f)
            mode = os.lstat(full_path).st_mode

            if stat.S_ISDIR(mode):
                remove_dir(full_path)
            else:
                remove_file(full_path)

def parse_options(args):
    parser = optparse.OptionParser()
    parser.add_option('--build-dir', default='build', metavar='DIR',
                      help='specify build dir to clean (default %default)')

    parser.add_option('--distclean', action='store_true', default=False,
                      help='clean everything')
    parser.add_option('--verbose', action='store_true', default=False,
                      help='noisy logging')

    (options, args) = parser.parse_args(args)

    if len(args) > 1:
        raise Exception("Unknown arguments")

    return options

def main(args=None):
    if args is None:
        args = sys.argv

    options = parse_options(args)

    logging.basicConfig(stream=sys.stderr,
                        format='%(levelname) 7s: %(message)s',
                        level=logging.DEBUG if options.verbose else logging.INFO)

    build_dir = options.build_dir

    if os.access(build_dir, os.X_OK) != True:
        logging.debug('No build directory found')
        # No build dir: clean enough!
        return 0

    build_config_path = os.path.join(build_dir, 'build_config.json')
    build_config_str = None

    try:
        build_config_file = open(build_config_path)
        build_config_str = build_config_file.read()
        build_config_file.close()
    except Exception: # pylint: disable=broad-except
        # Ugh have to do generic catch as different exception type thrown in Python2
        logging.error("Unable to access build_config.json in build dir")
        return 1

    build_config = json.loads(build_config_str)

    if options.distclean:
        build_dir = build_config['build_dir']
        remove_file(build_config['makefile_path'])
        remove_dir(build_dir)
    else:
        for dir_type in ['libobj_dir', 'cliobj_dir', 'testobj_dir', 'doc_output_dir_manual', 'doc_output_dir_doxygen']:
            dir_path = build_config[dir_type]
            if dir_path:
                remove_all_in_dir(dir_path)

        remove_file(build_config['doc_stamp_file'])

    remove_file(build_config['cli_exe'])
    remove_file(build_config['test_exe'])

    lib_basename = build_config['lib_prefix'] + build_config['libname']
    matches_libname = re.compile('^' + lib_basename + '.([a-z]+)((\\.[0-9\\.]+)|$)')

    known_suffix = ['a', 'so', 'dll', 'manifest', 'exp']

    for f in os.listdir(build_config['out_dir']):
        match = matches_libname.match(f)
        if match and match.group(1) in known_suffix:
            remove_file(os.path.join(build_config['out_dir'], f))

    if options.distclean:
        if 'generated_files' in build_config:
            for f in build_config['generated_files'].split(' '):
                remove_file(f)

    return 0

if __name__ == '__main__':
    sys.exit(main())


text:
/**
 * Created by guntars on 12/02/15.
 */
define(['./../utils/amdThree'], function (three) {

    function Hierarchy(el) {
        this.container = el;
        var style = window.getComputedStyle(el, null);

        this.width = Number(style.width.slice(0, -2));
        this.height = Number(style.height.slice(0, -2));

        this.mouseX = 0;
        this.mouseY = 0;

        this.windowHalfX = this.width / 2;
        this.windowHalfY = this.height / 2;

        this.diff = this.width / this.height;

        this.camera = new three.PerspectiveCamera(60, this.diff, 1, 15000);
        this.camera.position.z = 500;

        this.scene = new three.Scene();

        var geometry = new three.BoxGeometry(100, 100, 100);
        var material = new three.MeshNormalMaterial();

        this.root = new three.Mesh(geometry, material);
        this.root.position.x = 1000;
        this.scene.add(this.root);

        var amount = 200, object,
            parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.x = 100;

            parent.add(object);
            parent = object;

        }

        parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.x = -100;

            parent.add(object);
            parent = object;

        }

        parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.y = -100;

            parent.add(object);
            parent = object;

        }

        parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.y = 100;

            parent.add(object);
            parent = object;

        }

        parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.z = -100;

            parent.add(object);
            parent = object;

        }

        parent = this.root;

        for (var i = 0; i < amount; i++) {

            object = new three.Mesh(geometry, material);
            object.position.z = 100;

            parent.add(object);
            parent = object;

        }

        this.renderer = new three.WebGLRenderer();
        this.renderer.setClearColor(0xffffff);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(this.width, this.height);
        this.renderer.sortObjects = false;
        this.container.appendChild(this.renderer.domElement);

        //

        this.onWindowResize();
        this.animate();
        this.onDocumentMouseMove();
    }

    Hierarchy.prototype = {

        render: function () {

            var time = Date.now() * 0.001;

            var rx = Math.sin(time * 0.7) * 0.2;
            var ry = Math.sin(time * 0.3) * 0.1;
            var rz = Math.sin(time * 0.2) * 0.1;

            this.camera.position.x += ( this.mouseX - this.camera.position.x ) * .05;
            this.camera.position.y += ( -this.mouseY - this.camera.position.y ) * .05;

            this.camera.lookAt(this.scene.position);

            this.root.traverse(function (object) {

                object.rotation.x = rx;
                object.rotation.y = ry;
                object.rotation.z = rz;

            });

            this.renderer.render(this.scene, this.camera);

        },
        animate: function () {

            window.requestAnimationFrame(this.animate.bind(this));

            this.render();

        },

        onWindowResize: function () {
            window.addEventListener('resize', function () {

                this.width = this.container.clientWidth;
                this.height = this.container.clientHeight;

                this.windowHalfX = this.width / 2;
                this.windowHalfY = this.height / 2;

                this.diff = this.width / this.height;

                this.camera.aspect = this.diff;
                this.camera.updateProjectionMatrix();

                this.renderer.setSize(this.width, this.height);
            }.bind(this), false);
        },

        onDocumentMouseMove: function () {
            document.addEventListener('mousemove', function (event) {
                this.mouseX = ( event.clientX - this.windowHalfX ) * 10;
                this.mouseY = ( event.clientY - this.windowHalfY ) * 10;

            }.bind(this), false);

        }

    };
    return Hierarchy;
});


text:
When many developers collaborate on complex software projects, it can be a long and unpredictable process to integrate different parts of code together. However, you can make this process more efficient and more reliable if you build and deploy your project continuously.

**Continuous integration** (CI) is the process of integrating your code into a shared repository as frequently as possible. During code integration, a build break or a test failure can inform you, in a timely manner, of an error in your code.

Martin Fowler has the following breakdown of practices for continuous integration:

- Maintain a single source repository.
- Automate the build.
- Make your build self-sustaining.
- Check in at least once a day.
- Build each check-in on the CI server.
- Keep the build fast.
- Test in a clone of the production environment.
- Make it easy for anyone to get the most recent executable.
- Always be aware of what is happening.
- Automate deployment.

For more information, see the following page on Martin Fowler's Web site: [Continuous Integration](http://www.martinfowler.com/articles/continuousIntegration.html)

Visual Studio Team Services help you manage the end-to-end process of software development and supports the practice of continuous integration. By leveraging the capabilities of Visual Studio, your project can avoid unexpected delays, cost overruns, and execution risks.


text:
<?xml version='1.0' encoding="UTF-8" standalone="no" ?>
<!DOCTYPE OPS_envelope SYSTEM "ops.dtd">
<OPS_envelope>
 <header>
  <version>0.9</version>
  </header>
 <body>
  <data_block>
   <dt_assoc>
    <item key="response_text">Command Successful</item>
   </dt_assoc>
  </data_block>
 </body>
</OPS_envelope>


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Formularios" table="formularios">
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="nombre" type="string" column="nombre" length="100" nullable="false"/>
    <field name="numero" type="integer" column="numero" nullable="true"/>
    <field name="descripcion" type="text" column="descripcion" nullable="true"/>
    <field name="encabezado" type="text" column="encabezado" nullable="true"/>
    <many-to-one field="formulario" target-entity="Formularios">
      <join-columns>
        <join-column name="formulario_id" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>