text:
package org.apache.ignite.internal;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.managers.communication.GridIoMessageFactory;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheMapEntry;
import org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture;
import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.T3;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgniteClosure;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.jetbrains.annotations.Nullable;

/**
 *
 */
public class IgniteDiagnosticMessage implements Message {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    private static final int REQUEST_FLAG_MASK = 0x01;

    /** */
    private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
        @Override protected DateFormat initialValue() {
            return new SimpleDateFormat("HH:mm:ss.SSS");
        }
    };

    /** */
    private byte flags;

    /** */
    private long futId;

    /** */
    private byte[] bytes;

    /**
     * Required by {@link GridIoMessageFactory}.
     */
    public IgniteDiagnosticMessage() {
        // No-op.
    }

    /**
     * @param marsh Marshaller.
     * @param c Closure to run.
     * @param futId Future ID.
     * @return Request message.
     * @throws IgniteCheckedException If failed.
     */
    public static IgniteDiagnosticMessage createRequest(Marshaller marsh,
        IgniteClosure<GridKernalContext, IgniteDiagnosticInfo> c,
        long futId)
        throws IgniteCheckedException
    {
        byte[] cBytes = U.marshal(marsh, c);

        IgniteDiagnosticMessage msg = new IgniteDiagnosticMessage();

        msg.futId = futId;
        msg.bytes = cBytes;
        msg.flags |= REQUEST_FLAG_MASK;

        return msg;
    }

    /**
     * @param resBytes Marshalled result.
     * @param futId Future ID.
     * @return Response message.
     */
    public static IgniteDiagnosticMessage createResponse(byte[] resBytes, long futId) {
        IgniteDiagnosticMessage msg = new IgniteDiagnosticMessage();

        msg.futId = futId;
        msg.bytes = resBytes;

        return msg;
    }

    /**
     * @param marsh Marshaller.
     * @return Unmarshalled payload.
     * @throws IgniteCheckedException If failed.
     */
    @Nullable public <T> T unmarshal(Marshaller marsh)
        throws IgniteCheckedException {
        if (bytes == null)
            return null;

        return U.unmarshal(marsh, bytes, null);
    }

    /**
     * @return Future ID.
     */
    public long futureId() {
        return futId;
    }

    /**
     * @return {@code True} if this is request message.
     */
    public boolean request() {
        return (flags & REQUEST_FLAG_MASK) != 0;
    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 0:
                if (!writer.writeByteArray("bytes", bytes))
                    return false;

                writer.incrementState();

            case 1:
                if (!writer.writeByte("flags", flags))
                    return false;

                writer.incrementState();

            case 2:
                if (!writer.writeLong("futId", futId))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        switch (reader.state()) {
            case 0:
                bytes = reader.readByteArray("bytes");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 1:
                flags = reader.readByte("flags");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 2:
                futId = reader.readLong("futId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(IgniteDiagnosticMessage.class);
    }

    /** {@inheritDoc} */
    @Override public short directType() {
        return -61;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 3;
    }

    /** {@inheritDoc} */
    @Override public void onAckReceived() {
        // No-op.
    }

    /**
     *
     */
    public static abstract class DiagnosticBaseClosure implements IgniteBiInClosure<StringBuilder, GridKernalContext> {
        /**
         * @return Key to group similar messages.
         */
        public Object mergeKey() {
            return getClass();
        }

        /**
         * @param other Another closure of the same type.
         */
        public void merge(DiagnosticBaseClosure other) {
            // No-op.
        }
    }

    /**
     *
     */
    public final static class TxEntriesInfoClosure extends DiagnosticBaseClosure {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        private final int cacheId;

        /** */
        private Collection<KeyCacheObject> keys;

        /**
         * @param cacheId Cache ID.
         * @param keys Keys.
         */
        TxEntriesInfoClosure(int cacheId, Collection<KeyCacheObject> keys) {
            this.cacheId = cacheId;
            this.keys = new HashSet<>(keys);
        }

        /** {@inheritDoc} */
        @Override public void apply(StringBuilder sb, GridKernalContext ctx) {
            sb.append(U.nl());

            GridCacheContext cctx = ctx.cache().context().cacheContext(cacheId);

            if (cctx == null) {
                sb.append("Failed to find cache with id: ").append(cacheId);

                return;
            }

            try {
                for (KeyCacheObject key : keys)
                    key.finishUnmarshal(cctx.cacheObjectContext(), null);
            }
            catch (IgniteCheckedException e) {
                ctx.cluster().diagnosticLog().error("Failed to unmarshal key: " + e, e);

                sb.append("Failed to unmarshal key: ").append(e).append(U.nl());
            }

            sb.append("Cache entries [cacheId=").append(cacheId)
                .append(", cacheName=").append(cctx.name()).append("]: ");

            for (KeyCacheObject key : keys) {
                GridCacheMapEntry e = (GridCacheMapEntry)cctx.cache().peekEx(key);

                sb.append(U.nl()).append("    Key [key=").append(key).append(", entry=").append(e).append("]");
            }
        }

        /** {@inheritDoc} */
        @Override public Object mergeKey() {
            return new T2<>(getClass(), cacheId);
        }

        /** {@inheritDoc} */
        @Override public void merge(DiagnosticBaseClosure other) {
            TxEntriesInfoClosure other0 = (TxEntriesInfoClosure)other;

            assert other0 != null && cacheId == other0.cacheId : other;

            this.keys.addAll(other0.keys);
        }

        /**
         * @param out Output stream.
         * @throws IOException If failed.
         */
        private void writeObject(java.io.ObjectOutputStream out)
            throws IOException {
            /*
            Transform to List, otherwise Set unmarshalling fails since need
            call KeyCacheObject.finishUnmarshal before adding in Set.
             */
            this.keys = new ArrayList<>(keys);

            out.defaultWriteObject();
        }
    }

    /**
     *
     */
    public final static class ExchangeInfoClosure extends DiagnosticBaseClosure {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        private final AffinityTopologyVersion topVer;

        /**
         * @param topVer Exchange version.
         */
        ExchangeInfoClosure(AffinityTopologyVersion topVer) {
            this.topVer = topVer;
        }

        /** {@inheritDoc} */
        @Override public void apply(StringBuilder sb, GridKernalContext ctx) {
            sb.append(U.nl());

            List<GridDhtPartitionsExchangeFuture> futs = ctx.cache().context().exchange().exchangeFutures();

            for (GridDhtPartitionsExchangeFuture fut : futs) {
                if (topVer.equals(fut.initialVersion())) {
                    sb.append("Exchange future: ").append(fut);

                    return;
                }
            }

            sb.append("Failed to find exchange future: ").append(topVer);
        }

        /** {@inheritDoc} */
        @Override public Object mergeKey() {
            return new T2<>(getClass(), topVer);
        }
    }

    /**
     *
     */
    public final static class TxInfoClosure extends DiagnosticBaseClosure {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        private final GridCacheVersion dhtVer;

        /** */
        private final GridCacheVersion nearVer;

        /**
         * @param dhtVer Tx dht version.
         * @param nearVer Tx near version.
         */
        TxInfoClosure(GridCacheVersion dhtVer, GridCacheVersion nearVer) {
            this.dhtVer = dhtVer;
            this.nearVer = nearVer;
        }

        /** {@inheritDoc} */
        @Override public void apply(StringBuilder sb, GridKernalContext ctx) {
            sb.append(U.nl())
                .append("Related transactions [dhtVer=").append(dhtVer)
                .append(", nearVer=").append(nearVer).append("]: ");

            boolean found = false;

            for (IgniteInternalTx tx : ctx.cache().context().tm().activeTransactions()) {
                if (dhtVer.equals(tx.xidVersion()) || nearVer.equals(tx.nearXidVersion())) {
                    sb.append(U.nl())
                        .append("    ")
                        .append(tx.getClass().getSimpleName())
                        .append(" [ver=").append(tx.xidVersion())
                        .append(", nearVer=").append(tx.nearXidVersion())
                        .append(", topVer=").append(tx.topologyVersion())
                        .append(", state=").append(tx.state())
                        .append(", fullTx=").append(tx).append(']');

                    found = true;
                }
            }

            if (!found)
                sb.append(U.nl()).append("Failed to find related transactions.");
        }

        /** {@inheritDoc} */
        @Override public Object mergeKey() {
            return new T3<>(getClass(), nearVer, dhtVer);
        }
    }

    /**
     *
     * @param sb String builder.
     * @param ctx Context.
     */
    static void dumpNodeBasicInfo(StringBuilder sb, GridKernalContext ctx) {
        sb.append("General node info [id=").append(ctx.localNodeId())
            .append(", client=").append(ctx.clientNode())
            .append(", discoTopVer=").append(ctx.discovery().topologyVersionEx())
            .append(", time=").append(formatTime(U.currentTimeMillis())).append(']');
    }

    /**
     * @param sb String builder.
     * @param ctx Context.
     */
    static void dumpExchangeInfo(StringBuilder sb, GridKernalContext ctx) {
        GridCachePartitionExchangeManager exchMgr = ctx.cache().context().exchange();
        GridDhtTopologyFuture fut = exchMgr.lastTopologyFuture();

        sb.append("Partitions exchange info [readyVer=").append(exchMgr.readyAffinityVersion()).append(']').append(U.nl())
            .append("Last initialized exchange future: ").append(fut);
    }

    /**
     * @param sb String builder.
     * @param ctx Context.
     */
    static void dumpPendingCacheMessages(StringBuilder sb, GridKernalContext ctx) {
        ctx.cache().context().io().dumpPendingMessages(sb);
    }

    /**
     * @param ctx Context.
     * @param nodeId Target node ID.
     * @return Communication information future.
     */
    public static IgniteInternalFuture<String> dumpCommunicationInfo(GridKernalContext ctx, UUID nodeId) {
        if (ctx.config().getCommunicationSpi() instanceof TcpCommunicationSpi)
            return ((TcpCommunicationSpi) ctx.config().getCommunicationSpi()).dumpNodeStatistics(nodeId);
        else
            return new GridFinishedFuture<>("Unexpected communication SPI: " + ctx.config().getCommunicationSpi());
    }

    /**
     * @param time Time.
     * @return Time string.
     */
    private static String formatTime(long time) {
        return dateFormat.get().format(new Date(time));
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(IgniteDiagnosticMessage.class, this);
    }
}


text:
package com.study.jooq.global;

import com.study.jooq.base.connection.ConnectionPoolService;
import com.study.jooq.base.connection.impl.HikariCpImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

/**
 * 全局上下文.
 */
public enum GlobalContext {

    INSTANCE;

    private final static Logger log = LoggerFactory.getLogger(GlobalContext.class);

    private final ConnectionPoolService connPollService;

    GlobalContext() {
        this.connPollService = new HikariCpImpl(); // 构造 mysql 连接池服务
    }

    public ConnectionPoolService getConnPoolService() {
        return this.connPollService;
    }

    public void evictConnection(Connection connection) {
        this.connPollService.evict(connection);
    }

    public void contextInitialized() {
        log.info("contextInitialized-----------");
    }

    public void contextDestroyed() {
        log.info("contextDestroyed----------");
        //销毁数据库连接池
        connPollService.shutdown();
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
date: '2016-05-03'
title: "Belinda Ang BUTTERCUP DRESS Sleeveless Short/Mini Aline/Princess"
category: Belinda Ang
tags: [Belinda Ang,Aline/Princess ,Strapless,Short/Mini,Sleeveless]
---
### Belinda Ang BUTTERCUP DRESS
Just **$359.99**
###   Sleeveless Short/Mini Aline/Princess

BRANDS	Belinda Ang

Silhouette	Aline/Princess

Neckline	Strapless

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/belinda-ang-earth-angel/19983-belinda-ang-buttercup-dress.html](https://www.readybrides.com/en/belinda-ang-earth-angel/19983-belinda-ang-buttercup-dress.html)


text:
@interface CommunityPoliceDetailVC : BaseViewController

@end


text:
from datetime import datetime
from normality import stringify

from aleph.core import db
from aleph.model.common import DatedModel, IdModel

class Permission(db.Model, IdModel, DatedModel):
    """A set of rights granted to a role on a collection."""

    __tablename__ = "permission"

    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey("role.id"), index=True)
    read = db.Column(db.Boolean, default=False)
    write = db.Column(db.Boolean, default=False)
    collection_id = db.Column(db.Integer, nullable=False)

    def to_dict(self):
        data = self.to_dict_dates()
        data.update(
            {
                "id": stringify(self.id),
                "role_id": stringify(self.role_id),
                "collection_id": stringify(self.collection_id),
                "read": self.read,
                "write": self.write,
            }
        )
        return data

    @classmethod
    def grant(cls, collection, role, read, write):
        read = read or write
        permission = cls.by_collection_role(collection, role)
        if not read:
            if permission is not None:
                permission.delete()
            return
        if permission is None:
            permission = Permission()
            permission.role_id = role.id
            permission.collection_id = collection.id
        permission.read = True
        permission.write = write
        permission.updated_at = datetime.utcnow()
        db.session.add(permission)
        db.session.flush()
        return permission

    @classmethod
    def by_collection_role(cls, collection, role):
        q = cls.all()
        q = q.filter(Permission.role_id == role.id)
        q = q.filter(Permission.collection_id == collection.id)
        return q.first()

    @classmethod
    def delete_by_collection(cls, collection_id):
        q = db.session.query(cls)
        q = q.filter(cls.collection_id == collection_id)
        q.delete(synchronize_session=False)


text:
package com.evanzeimet.queryinfo.jpa.predicate;

import static com.evanzeimet.queryinfo.condition.ConditionOperator.isEitherInOperator;
import static com.evanzeimet.queryinfo.condition.ConditionOperator.isEitherNullOperator;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.Expression;

import com.evanzeimet.queryinfo.QueryInfoException;
import com.evanzeimet.queryinfo.QueryInfoUtils;
import com.evanzeimet.queryinfo.condition.ConditionOperator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * It appears that hibernate parses at least numeric types out of the box:
 *
 * <pre>
 * http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate-entitymanager/4.3.10.Final/org/hibernate/jpa/criteria/predicate/ComparisonPredicate.java#ComparisonPredicate.%3Cinit%3E%28org.hibernate.jpa.criteria.CriteriaBuilderImpl%2Corg.hibernate.jpa.criteria.predicate.ComparisonPredicate.ComparisonOperator%2Cjavax.persistence.criteria.Expression%2Cjava.lang.Object%29
 * </pre>
 *
 * Let's parse everything else.
 */
public class QueryInfoFieldValueParser {

	private ObjectMapper objectMapper;

	public QueryInfoFieldValueParser() {
		objectMapper = new QueryInfoUtils().createObjectMapper();
	}

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	public Object parseLiteral(JsonNode fieldValue) throws QueryInfoException {
		return parseType(fieldValue, Object.class);
	}

	public Object parseLiteralForExpression(Expression<?> expression,
			ConditionOperator conditionOperator,
			JsonNode fieldValue) throws QueryInfoException {
		Object result;
		Class<?> javaType = expression.getJavaType();

		if (isEitherInOperator(conditionOperator)) {
			result = parseInForExpression(expression, fieldValue);
		} else if (isEitherNullOperator(conditionOperator)) {
			result = null;
		} else if (Date.class.isAssignableFrom(javaType)) {
			result = parseDate(fieldValue);
		} else {
			result = parseType(fieldValue, javaType);
		}

		return result;
	}

	protected Date parseDate(JsonNode fieldValue) throws QueryInfoException {
		Date result;
		String stringValue = parseType(fieldValue, String.class);

		try {
			DateFormat dateFormat = objectMapper.getDateFormat();
			result = dateFormat.parse(stringValue);
		} catch (ParseException e) {
			throw new QueryInfoException(e);
		}

		return result;
	}

	protected <T> List<T> parseInForExpression(Expression<?> path,
			JsonNode fieldValue) throws QueryInfoException {
		Class<?> javaType = path.getJavaType();

		TypeFactory typeFactory = objectMapper.getTypeFactory();
		CollectionType collectionType = typeFactory.constructCollectionType(List.class, javaType);

		return objectMapper.convertValue(fieldValue, collectionType);
	}

	protected <T> T parseType(JsonNode fieldValue, Class<T> javaType) throws QueryInfoException {
		T result;

		try {
			result = objectMapper.convertValue(fieldValue, javaType);
		} catch (IllegalArgumentException e) {
			String message = String.format("Could not parse [%s] as [%s]",
					fieldValue,
					javaType);
			throw new QueryInfoException(message, e);
		}

		return result;
	}
}


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class CultureInfoCompareInfo
    {
        [Fact]
        public void TestEsES()
        {
            CultureInfo myCIintl = new CultureInfo("es-ES");
            string compareString1 = "llegar";
            string compareString2 = "lugar";
            Assert.True(myCIintl.CompareInfo.Compare(compareString1, compareString2) < 0);
        }

        [Fact]
        [ActiveIssue(5463, PlatformID.AnyUnix)]
        public void TestEsESTraditional()
        {
            CultureInfo myCItrad = new CultureInfo("es-ES_tradnl");
            string compareString1 = "llegar";
            string compareString2 = "lugar";
            Assert.True(myCItrad.CompareInfo.Compare(compareString1, compareString2) > 0);
        }

        [Fact]
        public void TestCompareInfoName()
        {
            string expectedName = "en-US";
            CultureInfo myCultureInfo = new CultureInfo(expectedName);
            CompareInfo myCompareInfo = myCultureInfo.CompareInfo;
            Assert.True(myCompareInfo.Name.Equals(expectedName, StringComparison.OrdinalIgnoreCase));
        }

        [Fact]
        public void TestCompareInfoNameWithInvariant()
        {
            string expectedName = "";
            CultureInfo myCultureInfo = new CultureInfo(expectedName);
            CompareInfo myCompareInfo = myCultureInfo.CompareInfo;
            Assert.True(myCompareInfo.Name.Equals(expectedName, StringComparison.OrdinalIgnoreCase));
        }
    }
}


text:
:- use_module(library(main)).
:- use_module(library(option)).
:- use_module(server).

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage:

    swipl run.pl [--public] [--port=Port]

Simple start script for running SWISH  in an interactive Prolog session.
This version is intended for development  and testing purposes. Checkout
daemon.pl if to deploy SWISH as a server.  Options:

  * --port=Port
    Bind to a the specified port instead of the default 3050.
  * --public
    Listen on all networks.  By default SWISH only listens on
    `localhost`.  Only use this in a *trusted network environent*,
    e.g., behind a firewall.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

:- initialization(run_swish, main).

run_swish :-
    set_prolog_flag(toplevel_goal, prolog), % run interactively
    current_prolog_flag(argv, Argv),
    argv_options(Argv, _, Options),
    option(port(Port), Options, 3020),
    (   option(public(true), Options)
    ->  Address = Port
    ;   Address = localhost:Port
    ),
    server(Address).


text:
require 'spec_helper'

describe 'sysfs::service' do

  let(:default_params) { {
  } }

  shared_examples_for 'sysfs::service configuration' do
    let :params do
      default_params
    end

    context 'with default params' do
      let :params do
        default_params.merge({})
      end

      it 'configures with the default params' do
        should contain_class('sysfs::service')
        should contain_service('sysfsutils').with(
          :ensure     => 'running',
          :enable     => true,
          :hasstatus  => false,
          :hasrestart => true)
      end
    end

  end

  context 'on Debian platforms' do
    let :facts do
      { :osfamily => 'Debian',
        :operatingsystem => 'Debian',
        :hostname => 'hostname.example.com', }
    end

    it_configures 'sysfs::service configuration'
  end

  context 'on RedHat platforms' do
    let :facts do
      { :osfamily => 'RedHat',
        :operatingsystem => 'RedHat',
        :hostname => 'hostname.example.com', }
    end

    it_configures 'sysfs::service configuration'
  end

end


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        hashmap.h
// Purpose:     wxHashMap class
// Author:      Mattia Barbon
// Modified by:
// Created:     29/01/2002
// RCS-ID:      $Id: hashmap.h,v 1.46.2.5 2006/01/18 16:32:38 JS Exp $
// Copyright:   (c) Mattia Barbon
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_HASHMAP_H_
#define _WX_HASHMAP_H_

#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface "hashmap.h"
#endif

#include "wx/string.h"

#if (defined(HAVE_EXT_HASH_MAP) || defined(HAVE_HASH_MAP)) \
    && (defined(HAVE_GNU_CXX_HASH_MAP) || defined(HAVE_STD_HASH_MAP))
    #define HAVE_STL_HASH_MAP
#endif

#if wxUSE_STL && defined(HAVE_STL_HASH_MAP)

#if defined(HAVE_EXT_HASH_MAP)
    #include <ext/hash_map>
#elif defined(HAVE_HASH_MAP)
    #include <hash_map>
#endif

#if defined(HAVE_GNU_CXX_HASH_MAP)
    #define WX_HASH_MAP_NAMESPACE __gnu_cxx
#elif defined(HAVE_STD_HASH_MAP)
    #define WX_HASH_MAP_NAMESPACE std
#endif

#define _WX_DECLARE_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME, CLASSEXP ) \
    typedef WX_HASH_MAP_NAMESPACE::hash_map< KEY_T, VALUE_T, HASH_T, KEY_EQ_T > CLASSNAME;

#else // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

#ifdef __WXWINCE__
typedef int ptrdiff_t;
#else
#include <stddef.h>             // for ptrdiff_t
#endif

// private
struct WXDLLIMPEXP_BASE _wxHashTable_NodeBase
{
    _wxHashTable_NodeBase() : m_nxt(0) {}

    _wxHashTable_NodeBase* m_nxt;

// Cannot do this:
//  DECLARE_NO_COPY_CLASS(_wxHashTable_NodeBase)
// without rewriting the macros, which require a public copy constructor.
};

// private
class WXDLLIMPEXP_BASE _wxHashTableBase2
{
public:
    typedef void (*NodeDtor)(_wxHashTable_NodeBase*);
    typedef unsigned long (*BucketFromNode)(_wxHashTableBase2*,_wxHashTable_NodeBase*);
    typedef _wxHashTable_NodeBase* (*ProcessNode)(_wxHashTable_NodeBase*);
protected:
    static _wxHashTable_NodeBase* DummyProcessNode(_wxHashTable_NodeBase* node);
    static void DeleteNodes( size_t buckets, _wxHashTable_NodeBase** table,
                             NodeDtor dtor );
    static _wxHashTable_NodeBase* GetFirstNode( size_t buckets,
                                                _wxHashTable_NodeBase** table )
    {
        for( size_t i = 0; i < buckets; ++i )
            if( table[i] )
                return table[i];
        return 0;
    }

    // as static const unsigned prime_count = 31 but works with all compilers
    enum { prime_count = 31 };
    static const unsigned long ms_primes[prime_count];

    // returns the first prime in ms_primes greater than n
    static unsigned long GetNextPrime( unsigned long n );

    // returns the first prime in ms_primes smaller than n
    // ( or ms_primes[0] if n is very small )
    static unsigned long GetPreviousPrime( unsigned long n );

    static void CopyHashTable( _wxHashTable_NodeBase** srcTable,
                               size_t srcBuckets, _wxHashTableBase2* dst,
                               _wxHashTable_NodeBase** dstTable,
                               BucketFromNode func, ProcessNode proc );

    static void** AllocTable( size_t sz )
    {
        return (void **)calloc(sz, sizeof(void*));
    }
    static void FreeTable(void *table)
    {
        free(table);
    }
};

#define _WX_DECLARE_HASHTABLE( VALUE_T, KEY_T, HASH_T, KEY_EX_T, KEY_EQ_T, CLASSNAME, CLASSEXP, SHOULD_GROW, SHOULD_SHRINK ) \
CLASSEXP CLASSNAME : protected _wxHashTableBase2 \
{ \
public: \
    typedef KEY_T key_type; \
    typedef VALUE_T value_type; \
    typedef HASH_T hasher; \
    typedef KEY_EQ_T key_equal; \
 \
    typedef size_t size_type; \
    typedef ptrdiff_t difference_type; \
    typedef value_type* pointer; \
    typedef const value_type* const_pointer; \
    typedef value_type& reference; \
    typedef const value_type& const_reference; \
    /* should these be protected? */ \
    typedef const KEY_T const_key_type; \
    typedef const VALUE_T const_mapped_type; \
public: \
    struct Node; \
    typedef KEY_EX_T key_extractor; \
    typedef CLASSNAME Self; \
protected: \
    Node** m_table; \
    size_t m_tableBuckets; \
    size_t m_items; \
    hasher m_hasher; \
    key_equal m_equals; \
    key_extractor m_getKey; \
public: \
    struct Node:public _wxHashTable_NodeBase \
    { \
    public: \
        Node( const value_type& value ) \
            : m_value( value ) {} \
        Node* m_next() { return (Node*)this->m_nxt; } \
 \
        value_type m_value; \
    }; \
 \
    CLASSEXP Iterator; \
    friend CLASSEXP Iterator; \
protected: \
    static void DeleteNode( _wxHashTable_NodeBase* node ) \
    { \
        delete (Node*)node; \
    } \
public: \
    /*                  */ \
    /* forward iterator */ \
    /*                  */ \
    CLASSEXP Iterator \
    { \
    public: \
        Node* m_node; \
        Self* m_ht; \
 \
        Iterator() : m_node(0), m_ht(0) {} \
        Iterator( Node* node, const Self* ht ) \
            : m_node(node), m_ht((Self*)ht) {} \
        bool operator ==( const Iterator& it ) const \
            { return m_node == it.m_node; } \
        bool operator !=( const Iterator& it ) const \
            { return m_node != it.m_node; } \
    protected: \
        Node* GetNextNode() \
        { \
            size_type bucket = GetBucketForNode(m_ht,m_node); \
            for( size_type i = bucket + 1; i < m_ht->m_tableBuckets; ++i ) \
            { \
                if( m_ht->m_table[i] ) \
                    return m_ht->m_table[i]; \
            } \
            return 0; \
        } \
 \
        void PlusPlus() \
        { \
            Node* next = m_node->m_next(); \
            m_node = next ? next : GetNextNode(); \
        } \
    }; \
 \
public: \
    CLASSEXP iterator : public Iterator \
    { \
    public: \
        iterator() : Iterator() {} \
        iterator( Node* node, Self* ht ) : Iterator( node, ht ) {} \
        iterator& operator++() { PlusPlus(); return *this; } \
        iterator operator++(int) { iterator it=*this;PlusPlus();return it; } \
        reference operator *() const { return m_node->m_value; } \
        pointer operator ->() const { return &(m_node->m_value); } \
    }; \
 \
    CLASSEXP const_iterator : public Iterator \
    { \
    public: \
        const_iterator() : Iterator() {} \
        const_iterator( Node* node, const Self* ht ) \
            : Iterator( node, (Self*)ht ) {} \
        const_iterator& operator++() { PlusPlus();return *this; } \
        const_iterator operator++(int) { const_iterator it=*this;PlusPlus();return it; } \
        const_reference operator *() const { return m_node->m_value; } \
        const_pointer operator ->() const { return &(m_node->m_value); } \
    }; \
 \
    CLASSNAME( size_type sz = 10, const hasher& hfun = hasher(), \
               const key_equal& k_eq = key_equal(), \
               const key_extractor& k_ex = key_extractor() ) \
        : m_tableBuckets( GetNextPrime( (unsigned long) sz ) ), \
          m_items( 0 ), \
          m_hasher( hfun ), \
          m_equals( k_eq ), \
          m_getKey( k_ex ) \
    { \
        m_table = (Node**)AllocTable( m_tableBuckets ); \
    } \
 \
    CLASSNAME( const Self& ht ) \
        : m_table( 0 ), \
          m_tableBuckets( 0 ), \
          m_items( ht.m_items ), \
          m_hasher( ht.m_hasher ), \
          m_equals( ht.m_equals ), \
          m_getKey( ht.m_getKey ) \
    { \
        HashCopy( ht ); \
    } \
 \
    const Self& operator=( const Self& ht ) \
    { \
         clear(); \
         m_hasher = ht.m_hasher; \
         m_equals = ht.m_equals; \
         m_getKey = ht.m_getKey; \
         m_items = ht.m_items; \
         HashCopy( ht ); \
         return *this; \
    } \
 \
    ~CLASSNAME() \
    { \
        clear(); \
 \
        FreeTable(m_table); \
    } \
 \
    hasher hash_funct() { return m_hasher; } \
    key_equal key_eq() { return m_equals; } \
 \
    /* removes all elements from the hash table, but does not */ \
    /* shrink it ( perhaps it should ) */ \
    void clear() \
    { \
        DeleteNodes( m_tableBuckets, (_wxHashTable_NodeBase**)m_table, \
                     DeleteNode ); \
        m_items = 0; \
    } \
 \
    size_type size() const { return m_items; } \
    size_type max_size() const { return size_type(-1); } \
    bool empty() const { return size() == 0; } \
 \
    const_iterator end() const { return const_iterator( 0, this ); } \
    iterator end() { return iterator( 0, this ); } \
    const_iterator begin() const \
        { return const_iterator( (Node*)GetFirstNode( m_tableBuckets, (_wxHashTable_NodeBase**)m_table ), this ); }; \
    iterator begin() \
        { return iterator( (Node*)GetFirstNode( m_tableBuckets, (_wxHashTable_NodeBase**)m_table ), this ); }; \
 \
    size_type erase( const const_key_type& key ) \
    { \
        Node** node = GetNodePtr( key ); \
 \
        if( !node ) \
            return 0; \
 \
        --m_items; \
        Node* temp = (*node)->m_next(); \
        delete *node; \
        (*node) = temp; \
        if( SHOULD_SHRINK( m_tableBuckets, m_items ) ) \
            ResizeTable( GetPreviousPrime( (unsigned long) m_tableBuckets ) - 1 ); \
        return 1; \
    } \
 \
protected: \
    static size_type GetBucketForNode( Self* ht, Node* node ) \
    { \
        return ht->m_hasher( ht->m_getKey( node->m_value ) ) \
            % ht->m_tableBuckets; \
    } \
    static Node* CopyNode( Node* node ) { return new Node( *node ); } \
 \
    Node* GetOrCreateNode( const value_type& value, bool& created ) \
    { \
        const const_key_type& key = m_getKey( value ); \
        size_t bucket = m_hasher( key ) % m_tableBuckets; \
        Node* node = m_table[bucket]; \
 \
        while( node ) \
        { \
            if( m_equals( m_getKey( node->m_value ), key ) ) \
            { \
                created = false; \
                return node; \
            } \
            node = node->m_next(); \
        } \
        created = true; \
        return CreateNode( value, bucket); \
    }\
    Node * CreateNode( const value_type& value, size_t bucket ) \
    {\
        Node* node = new Node( value ); \
        node->m_nxt = m_table[bucket]; \
        m_table[bucket] = node; \
 \
        /* must be after the node is inserted */ \
        ++m_items; \
        if( SHOULD_GROW( m_tableBuckets, m_items ) ) \
            ResizeTable( m_tableBuckets ); \
 \
        return node; \
    } \
    void CreateNode( const value_type& value ) \
    {\
        CreateNode(value, m_hasher( m_getKey(value) ) % m_tableBuckets ); \
    }\
 \
    /* returns NULL if not found */ \
    Node** GetNodePtr( const const_key_type& key ) const \
    { \
        size_t bucket = m_hasher( key ) % m_tableBuckets; \
        Node** node = &m_table[bucket]; \
 \
        while( *node ) \
        { \
            if( m_equals( m_getKey( (*node)->m_value ), key ) ) \
                return node; \
            node = (Node**)&(*node)->m_nxt; \
        } \
 \
        return 0; \
    } \
 \
    /* returns NULL if not found */ \
    /* expressing it in terms of GetNodePtr is 5-8% slower :-( */ \
    Node* GetNode( const const_key_type& key ) const \
    { \
        size_t bucket = m_hasher( key ) % m_tableBuckets; \
        Node* node = m_table[bucket]; \
 \
        while( node ) \
        { \
            if( m_equals( m_getKey( node->m_value ), key ) ) \
                return node; \
            node = node->m_next(); \
        } \
 \
        return 0; \
    } \
 \
    void ResizeTable( size_t newSize ) \
    { \
        newSize = GetNextPrime( (unsigned long)newSize ); \
        Node** srcTable = m_table; \
        size_t srcBuckets = m_tableBuckets; \
        m_table = (Node**)AllocTable( newSize ); \
        m_tableBuckets = newSize; \
 \
        CopyHashTable( (_wxHashTable_NodeBase**)srcTable, srcBuckets, \
                       this, (_wxHashTable_NodeBase**)m_table, \
                       (BucketFromNode)GetBucketForNode,\
                       (ProcessNode)&DummyProcessNode ); \
        FreeTable(srcTable); \
    } \
 \
    /* this must be called _after_ m_table has been cleaned */ \
    void HashCopy( const Self& ht ) \
    { \
        ResizeTable( ht.size() ); \
        CopyHashTable( (_wxHashTable_NodeBase**)ht.m_table, ht.m_tableBuckets,\
                       (_wxHashTableBase2*)this, \
                       (_wxHashTable_NodeBase**)m_table, \
                       (BucketFromNode)GetBucketForNode, \
                       (ProcessNode)CopyNode ); \
    } \
};

// defines an STL-like pair class CLASSNAME storing two fields: first of type
// KEY_T and second of type VALUE_T
#define _WX_DECLARE_PAIR( KEY_T, VALUE_T, CLASSNAME, CLASSEXP ) \
CLASSEXP CLASSNAME \
{ \
public: \
    typedef KEY_T t1; \
    typedef VALUE_T t2; \
    typedef const KEY_T const_t1; \
    typedef const VALUE_T const_t2; \
 \
    CLASSNAME( const const_t1& f, const const_t2& s ):first(t1(f)),second(t2(s)) {} \
 \
    t1 first; \
    t2 second; \
};

// defines the class CLASSNAME returning the key part (of type KEY_T) from a
// pair of type PAIR_T
#define _WX_DECLARE_HASH_MAP_KEY_EX( KEY_T, PAIR_T, CLASSNAME, CLASSEXP ) \
CLASSEXP CLASSNAME \
{ \
    typedef KEY_T key_type; \
    typedef PAIR_T pair_type; \
    typedef const key_type const_key_type; \
    typedef const pair_type const_pair_type; \
    typedef const_key_type& const_key_reference; \
    typedef const_pair_type& const_pair_reference; \
public: \
    CLASSNAME() { } \
    const_key_reference operator()( const_pair_reference pair ) const { return pair.first; }\
    \
    /* the dummy assignment operator is needed to suppress compiler */ \
    /* warnings from hash table class' operator=(): gcc complains about */ \
    /* "statement with no effect" without it */ \
    CLASSNAME& operator=(const CLASSNAME&) { return *this; } \
};

// grow/shrink predicates
inline bool never_grow( size_t, size_t ) { return false; }
inline bool never_shrink( size_t, size_t ) { return false; }
inline bool grow_lf70( size_t buckets, size_t items )
{
    return float(items)/float(buckets) >= 0.85;
}

#endif // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

// ----------------------------------------------------------------------------
// hashing and comparison functors
// ----------------------------------------------------------------------------

// NB: implementation detail: all of these classes must have dummy assignment
//     operators to suppress warnings about "statement with no effect" from gcc
//     in the hash table class assignment operator (where they're assigned)

#if wxUSE_STL && defined(HAVE_STL_HASH_MAP)

// integer types
class WXDLLIMPEXP_BASE wxIntegerHash
{
    WX_HASH_MAP_NAMESPACE::hash<long> longHash;
    WX_HASH_MAP_NAMESPACE::hash<unsigned long> ulongHash;
    WX_HASH_MAP_NAMESPACE::hash<int> intHash;
    WX_HASH_MAP_NAMESPACE::hash<unsigned int> uintHash;
    WX_HASH_MAP_NAMESPACE::hash<short> shortHash;
    WX_HASH_MAP_NAMESPACE::hash<unsigned short> ushortHash;

#if defined wxLongLong_t && !defined wxLongLongIsLong
    size_t longlongHash( wxLongLong_t x ) const
    {
        return longHash( wx_truncate_cast(long, x) ) ^
               longHash( wx_truncate_cast(long, x >> (sizeof(long) * 8)) );
    }
#endif

public:
    wxIntegerHash() { }
    size_t operator()( long x ) const { return longHash( x ); }
    size_t operator()( unsigned long x ) const { return ulongHash( x ); }
    size_t operator()( int x ) const { return intHash( x ); }
    size_t operator()( unsigned int x ) const { return uintHash( x ); }
    size_t operator()( short x ) const { return shortHash( x ); }
    size_t operator()( unsigned short x ) const { return ushortHash( x ); }
#if defined wxLongLong_t && !defined wxLongLongIsLong
    size_t operator()( wxLongLong_t x ) const { return longlongHash(x); }
    size_t operator()( wxULongLong_t x ) const { return longlongHash(x); }
#endif

    wxIntegerHash& operator=(const wxIntegerHash&) { return *this; }
};

#else // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

// integer types
class WXDLLIMPEXP_BASE wxIntegerHash
{
public:
    wxIntegerHash() { }
    unsigned long operator()( long x ) const { return (unsigned long)x; }
    unsigned long operator()( unsigned long x ) const { return x; }
    unsigned long operator()( int x ) const { return (unsigned long)x; }
    unsigned long operator()( unsigned int x ) const { return x; }
    unsigned long operator()( short x ) const { return (unsigned long)x; }
    unsigned long operator()( unsigned short x ) const { return x; }
#if defined wxLongLong_t && !defined wxLongLongIsLong
    wxULongLong_t operator()( wxLongLong_t x ) const { return wx_static_cast(wxULongLong_t, x); }
    wxULongLong_t operator()( wxULongLong_t x ) const { return x; }
#endif

    wxIntegerHash& operator=(const wxIntegerHash&) { return *this; }
};

#endif // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

class WXDLLIMPEXP_BASE wxIntegerEqual
{
public:
    wxIntegerEqual() { }
    bool operator()( long a, long b ) const { return a == b; }
    bool operator()( unsigned long a, unsigned long b ) const { return a == b; }
    bool operator()( int a, int b ) const { return a == b; }
    bool operator()( unsigned int a, unsigned int b ) const { return a == b; }
    bool operator()( short a, short b ) const { return a == b; }
    bool operator()( unsigned short a, unsigned short b ) const { return a == b; }
#if defined wxLongLong_t && !defined wxLongLongIsLong
    bool operator()( wxLongLong_t a, wxLongLong_t b ) const { return a == b; }
    bool operator()( wxULongLong_t a, wxULongLong_t b ) const { return a == b; }
#endif

    wxIntegerEqual& operator=(const wxIntegerEqual&) { return *this; }
};

// pointers
class WXDLLIMPEXP_BASE wxPointerHash
{
public:
    wxPointerHash() { }

#if wxUSE_STL && defined(HAVE_STL_HASH_MAP)
    size_t operator()( const void* k ) const { return (size_t)k; }
#else
    wxUIntPtr operator()( const void* k ) const { return wxPtrToUInt(k); }
#endif

    wxPointerHash& operator=(const wxPointerHash&) { return *this; }
};

class WXDLLIMPEXP_BASE wxPointerEqual
{
public:
    wxPointerEqual() { }
    bool operator()( const void* a, const void* b ) const { return a == b; }

    wxPointerEqual& operator=(const wxPointerEqual&) { return *this; }
};

// wxString, char*, wxChar*
class WXDLLIMPEXP_BASE wxStringHash
{
public:
    wxStringHash() {}
    unsigned long operator()( const wxString& x ) const
        { return wxCharStringHash( x.c_str() ); }
    unsigned long operator()( const wxChar* x ) const
        { return wxCharStringHash( x ); }
    static unsigned long wxCharStringHash( const wxChar* );
#if wxUSE_UNICODE
    unsigned long operator()( const char* x ) const
        { return charStringHash( x ); }
    static unsigned long charStringHash( const char* );
#endif // wxUSE_UNICODE

    wxStringHash& operator=(const wxStringHash&) { return *this; }
};

class WXDLLIMPEXP_BASE wxStringEqual
{
public:
    wxStringEqual() {}
    bool operator()( const wxString& a, const wxString& b ) const
        { return a == b; }
    bool operator()( const wxChar* a, const wxChar* b ) const
        { return wxStrcmp( a, b ) == 0; }
#if wxUSE_UNICODE
    bool operator()( const char* a, const char* b ) const
        { return strcmp( a, b ) == 0; }
#endif // wxUSE_UNICODE

    wxStringEqual& operator=(const wxStringEqual&) { return *this; }
};

#if !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

#define _WX_DECLARE_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME, CLASSEXP ) \
_WX_DECLARE_PAIR( KEY_T, VALUE_T, CLASSNAME##_wxImplementation_Pair, CLASSEXP ) \
_WX_DECLARE_HASH_MAP_KEY_EX( KEY_T, CLASSNAME##_wxImplementation_Pair, CLASSNAME##_wxImplementation_KeyEx, CLASSEXP ) \
_WX_DECLARE_HASHTABLE( CLASSNAME##_wxImplementation_Pair, KEY_T, HASH_T, CLASSNAME##_wxImplementation_KeyEx, KEY_EQ_T, CLASSNAME##_wxImplementation_HashTable, CLASSEXP, grow_lf70, never_shrink ) \
CLASSEXP CLASSNAME:public CLASSNAME##_wxImplementation_HashTable \
{ \
public: \
    typedef VALUE_T mapped_type; \
    _WX_DECLARE_PAIR( iterator, bool, Insert_Result, CLASSEXP ) \
 \
    wxEXPLICIT CLASSNAME( size_type hint = 100, hasher hf = hasher(),        \
                          key_equal eq = key_equal() )                       \
        : CLASSNAME##_wxImplementation_HashTable( hint, hf, eq,              \
                                   CLASSNAME##_wxImplementation_KeyEx() ) {} \
 \
    mapped_type& operator[]( const const_key_type& key ) \
    { \
        bool created; \
        return GetOrCreateNode( \
                CLASSNAME##_wxImplementation_Pair( key, mapped_type() ), \
                created)->m_value.second; \
    } \
 \
    const_iterator find( const const_key_type& key ) const \
    { \
        return const_iterator( GetNode( key ), this ); \
    } \
 \
    iterator find( const const_key_type& key ) \
    { \
        return iterator( GetNode( key ), this ); \
    } \
 \
    Insert_Result insert( const value_type& v ) \
    { \
        bool created; \
        Node *node = GetOrCreateNode( \
                CLASSNAME##_wxImplementation_Pair( v.first, v.second ), \
                created); \
        if ( !created ) \
            node->m_value.second = v.second; \
        return Insert_Result(iterator(node, this), created); \
    } \
 \
    size_type erase( const key_type& k ) \
        { return CLASSNAME##_wxImplementation_HashTable::erase( k ); } \
    void erase( const iterator& it ) { erase( it->first ); } \
    void erase( const const_iterator& it ) { erase( it->first ); } \
 \
    /* count() == 0 | 1 */ \
    size_type count( const const_key_type& key ) \
        { return GetNode( key ) ? 1 : 0; } \
}

#endif // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

// these macros are to be used in the user code
#define WX_DECLARE_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME) \
    _WX_DECLARE_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME, class )

#define WX_DECLARE_STRING_HASH_MAP( VALUE_T, CLASSNAME ) \
    _WX_DECLARE_HASH_MAP( wxString, VALUE_T, wxStringHash, wxStringEqual, \
                          CLASSNAME, class )

#define WX_DECLARE_VOIDPTR_HASH_MAP( VALUE_T, CLASSNAME ) \
    _WX_DECLARE_HASH_MAP( void*, VALUE_T, wxPointerHash, wxPointerEqual, \
                          CLASSNAME, class )

// and these do exactly the same thing but should be used inside the
// library
#define WX_DECLARE_HASH_MAP_WITH_DECL( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME, DECL) \
    _WX_DECLARE_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME, DECL )

#define WX_DECLARE_EXPORTED_HASH_MAP( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, CLASSNAME) \
    WX_DECLARE_HASH_MAP_WITH_DECL( KEY_T, VALUE_T, HASH_T, KEY_EQ_T, \
                                   CLASSNAME, class WXDLLEXPORT )

#define WX_DECLARE_STRING_HASH_MAP_WITH_DECL( VALUE_T, CLASSNAME, DECL ) \
    _WX_DECLARE_HASH_MAP( wxString, VALUE_T, wxStringHash, wxStringEqual, \
                          CLASSNAME, DECL )

#define WX_DECLARE_EXPORTED_STRING_HASH_MAP( VALUE_T, CLASSNAME ) \
    WX_DECLARE_STRING_HASH_MAP_WITH_DECL( VALUE_T, CLASSNAME, \
                                          class WXDLLEXPORT )

#define WX_DECLARE_VOIDPTR_HASH_MAP_WITH_DECL( VALUE_T, CLASSNAME, DECL ) \
    _WX_DECLARE_HASH_MAP( void*, VALUE_T, wxPointerHash, wxPointerEqual, \
                          CLASSNAME, DECL )

#define WX_DECLARE_EXPORTED_VOIDPTR_HASH_MAP( VALUE_T, CLASSNAME ) \
    WX_DECLARE_VOIDPTR_HASH_MAP_WITH_DECL( VALUE_T, CLASSNAME, \
                                           class WXDLLEXPORT )

// delete all hash elements
//
// NB: the class declaration of the hash elements must be visible from the
//     place where you use this macro, otherwise the proper destructor may not
//     be called (a decent compiler should give a warning about it, but don't
//     count on it)!
#define WX_CLEAR_HASH_MAP(type, hashmap)                                     \
    {                                                                        \
        type::iterator it, en;                                               \
        for( it = (hashmap).begin(), en = (hashmap).end(); it != en; ++it )  \
            delete it->second;                                               \
        (hashmap).clear();                                                   \
    }

//---------------------------------------------------------------------------
// Declarations of common hashmap classes

WX_DECLARE_HASH_MAP_WITH_DECL( long, long, wxIntegerHash, wxIntegerEqual,
                               wxLongToLongHashMap, class WXDLLIMPEXP_BASE );

#endif // _WX_HASHMAP_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

 </RelativeLayout>


text:
"""Support for Tuya Cover."""
from __future__ import annotations

from dataclasses import dataclass
import logging
from typing import Any

from tuya_iot import TuyaDevice, TuyaDeviceManager

from homeassistant.components.cover import (
    ATTR_POSITION,
    ATTR_TILT_POSITION,
    DEVICE_CLASS_CURTAIN,
    DEVICE_CLASS_GARAGE,
    SUPPORT_CLOSE,
    SUPPORT_OPEN,
    SUPPORT_SET_POSITION,
    SUPPORT_SET_TILT_POSITION,
    SUPPORT_STOP,
    CoverEntity,
    CoverEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect

from . import HomeAssistantTuyaData
from .base import EnumTypeData, IntegerTypeData, TuyaEntity
from .const import DOMAIN, TUYA_DISCOVERY_NEW, DPCode

_LOGGER = logging.getLogger(__name__)

@dataclass
class TuyaCoverEntityDescription(CoverEntityDescription):
    """Describe an Tuya cover entity."""

    current_state: DPCode | None = None
    current_position: DPCode | None = None
    set_position: DPCode | None = None

COVERS: dict[str, tuple[TuyaCoverEntityDescription, ...]] = {
    # Curtain
    # Note: Multiple curtains isn't documented
    # https://developer.tuya.com/en/docs/iot/categorycl?id=Kaiuz1hnpo7df
    "cl": (
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL,
            name="Curtain",
            current_state=DPCode.SITUATION_SET,
            current_position=DPCode.PERCENT_STATE,
            set_position=DPCode.PERCENT_CONTROL,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL_2,
            name="Curtain 2",
            current_position=DPCode.PERCENT_STATE_2,
            set_position=DPCode.PERCENT_CONTROL_2,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL_3,
            name="Curtain 3",
            current_position=DPCode.PERCENT_STATE_3,
            set_position=DPCode.PERCENT_CONTROL_3,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
    ),
    # Garage Door Opener
    # https://developer.tuya.com/en/docs/iot/categoryckmkzq?id=Kaiuz0ipcboee
    "ckmkzq": (
        TuyaCoverEntityDescription(
            key=DPCode.SWITCH_1,
            name="Door",
            current_state=DPCode.DOORCONTACT_STATE,
            device_class=DEVICE_CLASS_GARAGE,
        ),
        TuyaCoverEntityDescription(
            key=DPCode.SWITCH_2,
            name="Door 2",
            current_state=DPCode.DOORCONTACT_STATE_2,
            device_class=DEVICE_CLASS_GARAGE,
        ),
        TuyaCoverEntityDescription(
            key=DPCode.SWITCH_3,
            name="Door 3",
            current_state=DPCode.DOORCONTACT_STATE_3,
            device_class=DEVICE_CLASS_GARAGE,
        ),
    ),
    # Curtain Switch
    # https://developer.tuya.com/en/docs/iot/category-clkg?id=Kaiuz0gitil39
    "clkg": (
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL,
            name="Curtain",
            current_position=DPCode.PERCENT_CONTROL,
            set_position=DPCode.PERCENT_CONTROL,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL_2,
            name="Curtain 2",
            current_position=DPCode.PERCENT_CONTROL_2,
            set_position=DPCode.PERCENT_CONTROL_2,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
    ),
    # Curtain Robot
    # Note: Not documented
    "jdcljqr": (
        TuyaCoverEntityDescription(
            key=DPCode.CONTROL,
            current_position=DPCode.PERCENT_STATE,
            set_position=DPCode.PERCENT_CONTROL,
            device_class=DEVICE_CLASS_CURTAIN,
        ),
    ),
}

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None:
    """Set up Tuya cover dynamically through Tuya discovery."""
    hass_data: HomeAssistantTuyaData = hass.data[DOMAIN][entry.entry_id]

    @callback
    def async_discover_device(device_ids: list[str]) -> None:
        """Discover and add a discovered tuya cover."""
        entities: list[TuyaCoverEntity] = []
        for device_id in device_ids:
            device = hass_data.device_manager.device_map[device_id]
            if descriptions := COVERS.get(device.category):
                for description in descriptions:
                    if (
                        description.key in device.function
                        or description.key in device.status
                    ):
                        entities.append(
                            TuyaCoverEntity(
                                device, hass_data.device_manager, description
                            )
                        )

        async_add_entities(entities)

    async_discover_device([*hass_data.device_manager.device_map])

    entry.async_on_unload(
        async_dispatcher_connect(hass, TUYA_DISCOVERY_NEW, async_discover_device)
    )

class TuyaCoverEntity(TuyaEntity, CoverEntity):
    """Tuya Cover Device."""

    _current_position_type: IntegerTypeData | None = None
    _set_position_type: IntegerTypeData | None = None
    _tilt_dpcode: DPCode | None = None
    _tilt_type: IntegerTypeData | None = None
    entity_description: TuyaCoverEntityDescription

    def __init__(
        self,
        device: TuyaDevice,
        device_manager: TuyaDeviceManager,
        description: TuyaCoverEntityDescription,
    ) -> None:
        """Init Tuya Cover."""
        super().__init__(device, device_manager)
        self.entity_description = description
        self._attr_unique_id = f"{super().unique_id}{description.key}"
        self._attr_supported_features = 0

        # Check if this cover is based on a switch or has controls
        if device.function[description.key].type == "Boolean":
            self._attr_supported_features |= SUPPORT_OPEN | SUPPORT_CLOSE
        elif device.function[description.key].type == "Enum":
            data_type = EnumTypeData.from_json(
                device.status_range[description.key].values
            )
            if "open" in data_type.range:
                self._attr_supported_features |= SUPPORT_OPEN
            if "close" in data_type.range:
                self._attr_supported_features |= SUPPORT_CLOSE
            if "stop" in data_type.range:
                self._attr_supported_features |= SUPPORT_STOP

        # Determine type to use for setting the position
        if (
            description.set_position is not None
            and description.set_position in device.status_range
        ):
            self._attr_supported_features |= SUPPORT_SET_POSITION
            self._set_position_type = IntegerTypeData.from_json(
                device.status_range[description.set_position].values
            )
            # Set as default, unless overwritten below
            self._current_position_type = self._set_position_type

        # Determine type for getting the position
        if (
            description.current_position is not None
            and description.current_position in device.status_range
        ):
            self._current_position_type = IntegerTypeData.from_json(
                device.status_range[description.current_position].values
            )

        # Determine type to use for setting the tilt
        if tilt_dpcode := next(
            (
                dpcode
                for dpcode in (DPCode.ANGLE_HORIZONTAL, DPCode.ANGLE_VERTICAL)
                if dpcode in device.function
            ),
            None,
        ):
            self._attr_supported_features |= SUPPORT_SET_TILT_POSITION
            self._tilt_dpcode = tilt_dpcode
            self._tilt_type = IntegerTypeData.from_json(
                device.status_range[tilt_dpcode].values
            )

    @property
    def current_cover_position(self) -> int | None:
        """Return cover current position."""
        if self._current_position_type is None:
            return None

        if not (
            dpcode := (
                self.entity_description.current_position
                or self.entity_description.set_position
            )
        ):
            return None

        position = self.device.status.get(dpcode)
        if position is None:
            return None

        return round(
            self._current_position_type.remap_value_to(position, 0, 100, reverse=True)
        )

    @property
    def current_cover_tilt_position(self) -> int | None:
        """Return current position of cover tilt.

        None is unknown, 0 is closed, 100 is fully open.
        """
        if self._tilt_dpcode is None or self._tilt_type is None:
            return None

        angle = self.device.status.get(self._tilt_dpcode)
        if angle is None:
            return None

        return round(self._tilt_type.remap_value_to(angle, 0, 100))

    @property
    def is_closed(self) -> bool | None:
        """Return is cover is closed."""
        if (
            self.entity_description.current_state is not None
            and (
                current_state := self.device.status.get(
                    self.entity_description.current_state
                )
            )
            is not None
        ):
            return current_state in (True, "fully_close")

        if (position := self.current_cover_position) is not None:
            return position == 0

        return None

    def open_cover(self, **kwargs: Any) -> None:
        """Open the cover."""
        value: bool | str = True
        if self.device.function[self.entity_description.key].type == "Enum":
            value = "open"
        self._send_command([{"code": self.entity_description.key, "value": value}])

    def close_cover(self, **kwargs: Any) -> None:
        """Close cover."""
        value: bool | str = True
        if self.device.function[self.entity_description.key].type == "Enum":
            value = "close"
        self._send_command([{"code": self.entity_description.key, "value": value}])

    def set_cover_position(self, **kwargs: Any) -> None:
        """Move the cover to a specific position."""
        if self._set_position_type is None:
            raise RuntimeError(
                "Cannot set position, device doesn't provide methods to set it"
            )

        self._send_command(
            [
                {
                    "code": self.entity_description.set_position,
                    "value": round(
                        self._set_position_type.remap_value_from(
                            kwargs[ATTR_POSITION], 0, 100, reverse=True
                        )
                    ),
                }
            ]
        )

    def stop_cover(self, **kwargs: Any) -> None:
        """Stop the cover."""
        self._send_command([{"code": self.entity_description.key, "value": "stop"}])

    def set_cover_tilt_position(self, **kwargs):
        """Move the cover tilt to a specific position."""
        if self._tilt_type is None:
            raise RuntimeError(
                "Cannot set tilt, device doesn't provide methods to set it"
            )

        self._send_command(
            [
                {
                    "code": self._tilt_dpcode,
                    "value": round(
                        self._tilt_type.remap_value_from(
                            kwargs[ATTR_TILT_POSITION], 0, 100, reverse=True
                        )
                    ),
                }
            ]
        )


text:
/*
 * Author: Alexandre Havrileck (Oxyno-zeta)
 * Date: 01/09/16
 * Licence: See Readme
 */
(function () {
    'use strict';

    angular
        .module('crash-reporter.views.administration.users')
        .controller('AdminAddNewUserController', AdminAddNewUserController);

    /** @ngInject */
    function AdminAddNewUserController($mdDialog, $mdToast, usersService, roles) {
        var vm = this;
        // Variables
        vm.username = null;
        vm.password = null;
        vm.confirmPassword = null;
        vm.email = null;
        vm.roles = roles;
        vm.role = null;
        // Functions
        vm.close = close;
        vm.create = create;

        ////////////////

        /* ************************************* */
        /* ********  PRIVATE FUNCTIONS  ******** */
        /* ************************************* */

        /* ************************************* */
        /* ********   PUBLIC FUNCTIONS  ******** */
        /* ************************************* */

        /**
         * Create user.
         */
        function create() {
            var userData = {
                username: vm.username,
                password: vm.password,
                email: vm.email,
                role: vm.role
            };
            usersService.createUser(userData).then($mdDialog.hide, function (err) {
                // Error
                var toast = $mdToast.simple()
                    .textContent('Add user failed !')
                    .position('top right')
                    .hideDelay(3000);

                if (err.status === 409) {
                    // Conflict
                    toast.textContent('Conflict User !');
                }
                // Show toast
                $mdToast.show(toast);
            });
        }

        /**
         * Close modal.
         */
        function close() {
            $mdDialog.cancel();
        }
    }

})();


text:
package noaa

import (
	"bufio"
	"bytes"
	"crypto/tls"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"sync"
	"time"

	noaa_errors "github.com/cloudfoundry/noaa/errors"
	"github.com/cloudfoundry/sonde-go/events"
	"github.com/gogo/protobuf/proto"
	"github.com/gorilla/websocket"
)

var (
	// KeepAlive sets the interval between keep-alive messages sent by the client to loggregator.
	KeepAlive         = 25 * time.Second
	reconnectTimeout  = 500 * time.Millisecond
	boundaryRegexp    = regexp.MustCompile("boundary=(.*)")
	ErrNotOK          = errors.New("unknown issue when making HTTP request to Loggregator")
	ErrNotFound       = ErrNotOK // NotFound isn't an accurate description of how this is used; please use ErrNotOK instead
	ErrBadResponse    = errors.New("bad server response")
	ErrBadRequest     = errors.New("bad client request")
	ErrLostConnection = errors.New("remote server terminated connection unexpectedly")
)

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// Consumer represents the actions that can be performed against traffic controller.
type Consumer struct {
	trafficControllerUrl string
	tlsConfig            *tls.Config
	ws                   *websocket.Conn
	callback             func()
	proxy                func(*http.Request) (*url.URL, error)
	debugPrinter         DebugPrinter
	idleTimeout          time.Duration
	sync.RWMutex
	stopChan chan struct{}
	client   *http.Client
	dialer   websocket.Dialer
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// NewConsumer creates a new consumer to a traffic controller.
func NewConsumer(trafficControllerUrl string, tlsConfig *tls.Config, proxy func(*http.Request) (*url.URL, error)) *Consumer {
	log.Printf("You are using a deprecated noaa consumer (noaa.Consumer).  Please switch to 'github.com/cloudfoundry/noaa/consumer'.Consumer at your earliest convenience.")
	transport := &http.Transport{Proxy: proxy, TLSClientConfig: tlsConfig}
	consumer := &Consumer{
		trafficControllerUrl: trafficControllerUrl,
		tlsConfig:            tlsConfig,
		proxy:                proxy,
		debugPrinter:         NullDebugPrinter{},
		stopChan:             make(chan struct{}),
		client:               &http.Client{Transport: transport},
	}
	consumer.dialer = websocket.Dialer{
		NetDial:         consumer.proxyDial,
		TLSClientConfig: tlsConfig,
	}
	return consumer
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// TailingLogs behaves exactly as TailingLogsWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost and returns all errors from each attempt on errorChan.
func (cnsmr *Consumer) TailingLogs(appGuid string, authToken string, outputChan chan<- *events.LogMessage, errorChan chan<- error) {
	action := func() error {
		return cnsmr.TailingLogsWithoutReconnect(appGuid, authToken, outputChan)
	}

	cnsmr.retryAction(action, errorChan)
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// TailingLogsWithoutReconnect listens indefinitely for log messages only; other event types are dropped.
//
// If you wish to be able to terminate the listen early, run TailingLogsWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or
// other ordering is not guaranteed. It is the responsibility of the consumer of these channels
// to provide any desired sorting mechanism.
func (cnsmr *Consumer) TailingLogsWithoutReconnect(appGuid string, authToken string, outputChan chan<- *events.LogMessage) error {
	allEvents := make(chan *events.Envelope)

	streamPath := fmt.Sprintf("/apps/%s/stream", appGuid)
	errChan := make(chan error)
	go func() {
		err := cnsmr.stream(streamPath, authToken, allEvents)
		errChan <- err
		close(errChan)
	}()

	go func() {
		for event := range allEvents {
			if *event.EventType == events.Envelope_LogMessage {
				outputChan <- event.GetLogMessage()
			}
		}
	}()

	go func() {
		<-cnsmr.stopChan
		close(allEvents)
	}()

	return <-errChan
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// Stream behaves exactly as StreamWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost.
func (cnsmr *Consumer) Stream(appGuid string, authToken string, outputChan chan<- *events.Envelope, errorChan chan<- error) {
	action := func() error {
		return cnsmr.StreamWithoutReconnect(appGuid, authToken, outputChan)
	}

	cnsmr.retryAction(action, errorChan)
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// StreamWithoutReconnect listens indefinitely for all log and event messages.
//
// If you wish to be able to terminate the listen early, run StreamWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or other ordering
// is not guaranteed. It is the responsibility of the consumer of these channels to provide any desired sorting
// mechanism.
func (cnsmr *Consumer) StreamWithoutReconnect(appGuid string, authToken string, outputChan chan<- *events.Envelope) error {
	streamPath := fmt.Sprintf("/apps/%s/stream", appGuid)
	return cnsmr.stream(streamPath, authToken, outputChan)
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// Firehose behaves exactly as FirehoseWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost.
func (cnsmr *Consumer) Firehose(subscriptionId string, authToken string, outputChan chan<- *events.Envelope, errorChan chan<- error) {
	action := func() error {
		return cnsmr.FirehoseWithoutReconnect(subscriptionId, authToken, outputChan)
	}

	cnsmr.retryAction(action, errorChan)
}

func (cnsmr *Consumer) SetIdleTimeout(idleTimeout time.Duration) {
	cnsmr.idleTimeout = idleTimeout
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// FirehoseWithoutReconnect streams all data. All clients with the same subscriptionId will receive a proportionate share of the
// message stream. Each pool of clients will receive the entire stream.
//
// If you wish to be able to terminate the listen early, run FirehoseWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or other ordering
// is not guaranteed. It is the responsibility of the consumer of these channels to provide any desired sorting
// mechanism.
func (cnsmr *Consumer) FirehoseWithoutReconnect(subscriptionId string, authToken string, outputChan chan<- *events.Envelope) error {
	streamPath := "/firehose/" + subscriptionId
	return cnsmr.stream(streamPath, authToken, outputChan)
}

func (cnsmr *Consumer) stream(streamPath string, authToken string, outputChan chan<- *events.Envelope) error {
	var err error

	cnsmr.Lock()
	cnsmr.ws, err = cnsmr.establishWebsocketConnection(streamPath, authToken)
	cnsmr.Unlock()

	if err != nil {
		return err
	}

	return cnsmr.listenForMessages(outputChan)
}

func makeError(err error, code int32) *events.Envelope {
	return &events.Envelope{
		EventType: events.Envelope_Error.Enum(),
		Error: &events.Error{
			Source:  proto.String("NOAA"),
			Code:    &code,
			Message: proto.String(err.Error()),
		},
	}
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// RecentLogs connects to traffic controller via its 'recentlogs' http(s) endpoint and returns a slice of recent messages.
// It does not guarantee any order of the messages; they are in the order returned by traffic controller.
//
// The SortRecent method is provided to sort the data returned by this method.
func (cnsmr *Consumer) RecentLogs(appGuid string, authToken string) ([]*events.LogMessage, error) {
	envelopes, err := cnsmr.readEnvelopesFromTrafficController(appGuid, authToken, "recentlogs")

	if err != nil {
		return nil, err
	}

	messages := make([]*events.LogMessage, 0, 200)
	for _, envelope := range envelopes {
		messages = append(messages, envelope.GetLogMessage())
	}

	return messages, err
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// ContainerMetrics connects to traffic controller via its 'containermetrics' http(s) endpoint and returns the most recent messages for an app.
// The returned metrics will be sorted by InstanceIndex.
func (cnsmr *Consumer) ContainerMetrics(appGuid string, authToken string) ([]*events.ContainerMetric, error) {
	envelopes, err := cnsmr.readEnvelopesFromTrafficController(appGuid, authToken, "containermetrics")

	if err != nil {
		return nil, err
	}

	messages := make([]*events.ContainerMetric, 0, 200)

	for _, envelope := range envelopes {
		if envelope.GetEventType() == events.Envelope_LogMessage {
			return []*events.ContainerMetric{}, errors.New(fmt.Sprintf("Upstream error: %s", envelope.GetLogMessage().GetMessage()))
		}

		messages = append(messages, envelope.GetContainerMetric())
	}

	SortContainerMetrics(messages)

	return messages, err
}

func (cnsmr *Consumer) readEnvelopesFromTrafficController(appGuid string, authToken string, endpoint string) ([]*events.Envelope, error) {
	trafficControllerUrl, err := url.ParseRequestURI(cnsmr.trafficControllerUrl)
	if err != nil {
		return nil, err
	}

	scheme := "https"

	if trafficControllerUrl.Scheme == "ws" {
		scheme = "http"
	}

	recentPath := fmt.Sprintf("%s://%s/apps/%s/%s", scheme, trafficControllerUrl.Host, appGuid, endpoint)

	req, _ := http.NewRequest("GET", recentPath, nil)
	req.Header.Set("Authorization", authToken)

	resp, err := cnsmr.client.Do(req)

	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error dialing traffic controller server: %s.\nPlease ask your Cloud Foundry Operator to check the platform configuration (traffic controller endpoint is %s).", err.Error(), cnsmr.trafficControllerUrl))
	}

	defer resp.Body.Close()

	err = checkForErrors(resp)
	if err != nil {
		return nil, err
	}

	reader, err := getMultipartReader(resp)
	if err != nil {
		return nil, err
	}

	var envelopes []*events.Envelope
	var buffer bytes.Buffer

	for part, loopErr := reader.NextPart(); loopErr == nil; part, loopErr = reader.NextPart() {
		buffer.Reset()

		_, err := buffer.ReadFrom(part)
		if err != nil {
			break
		}

		envelope := new(events.Envelope)
		proto.Unmarshal(buffer.Bytes(), envelope)

		envelopes = append(envelopes, envelope)
	}

	return envelopes, nil
}

func checkForErrors(resp *http.Response) error {
	if resp.StatusCode == http.StatusUnauthorized {
		data, _ := ioutil.ReadAll(resp.Body)
		return noaa_errors.NewUnauthorizedError(string(data))
	}

	if resp.StatusCode == http.StatusBadRequest {
		return ErrBadRequest
	}

	if resp.StatusCode != http.StatusOK {
		return ErrNotOK
	}
	return nil
}

func getMultipartReader(resp *http.Response) (*multipart.Reader, error) {
	contentType := resp.Header.Get("Content-Type")

	if len(strings.TrimSpace(contentType)) == 0 {
		return nil, ErrBadResponse
	}

	matches := boundaryRegexp.FindStringSubmatch(contentType)

	if len(matches) != 2 || len(strings.TrimSpace(matches[1])) == 0 {
		return nil, ErrBadResponse
	}
	reader := multipart.NewReader(resp.Body, matches[1])
	return reader, nil
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// Close terminates the websocket connection to traffic controller.
func (cnsmr *Consumer) Close() error {
	cnsmr.Lock()
	defer cnsmr.Unlock()
	defer close(cnsmr.stopChan)
	if cnsmr.ws == nil {
		return errors.New("connection does not exist")
	}

	cnsmr.ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Time{})
	return cnsmr.ws.Close()
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// SetOnConnectCallback sets a callback function to be called with the websocket connection is established.
func (cnsmr *Consumer) SetOnConnectCallback(cb func()) {
	cnsmr.callback = cb
}

// noaa.Consumer is deprecated.  Use the one in the consumer package.
//
// SetDebugPrinter enables logging of the websocket handshake.
func (cnsmr *Consumer) SetDebugPrinter(debugPrinter DebugPrinter) {
	cnsmr.debugPrinter = debugPrinter
}

func (cnsmr *Consumer) listenForMessages(msgChan chan<- *events.Envelope) error {
	defer cnsmr.ws.Close()

	for {
		if cnsmr.idleTimeout != 0 {
			cnsmr.ws.SetReadDeadline(time.Now().Add(cnsmr.idleTimeout))
		}
		_, data, err := cnsmr.ws.ReadMessage()
		if err != nil {
			return err
		}

		envelope := &events.Envelope{}
		err = proto.Unmarshal(data, envelope)
		if err != nil {
			continue
		}

		msgChan <- envelope
	}
}

func headersString(header http.Header) string {
	var result string
	for name, values := range header {
		result += name + ": " + strings.Join(values, ", ") + "\n"
	}
	return result
}

func (cnsmr *Consumer) establishWebsocketConnection(path string, authToken string) (*websocket.Conn, error) {
	header := http.Header{"Origin": []string{"http://localhost"}, "Authorization": []string{authToken}}

	url := cnsmr.trafficControllerUrl + path

	cnsmr.debugPrinter.Print("WEBSOCKET REQUEST:",
		"GET "+path+" HTTP/1.1\n"+
			"Host: "+cnsmr.trafficControllerUrl+"\n"+
			"Upgrade: websocket\nConnection: Upgrade\nSec-WebSocket-Version: 13\nSec-WebSocket-Key: [HIDDEN]\n"+
			headersString(header))

	ws, resp, err := cnsmr.dialer.Dial(url, header)

	if resp != nil {
		cnsmr.debugPrinter.Print("WEBSOCKET RESPONSE:",
			resp.Proto+" "+resp.Status+"\n"+
				headersString(resp.Header))
	}

	if resp != nil && resp.StatusCode == http.StatusUnauthorized {
		bodyData, _ := ioutil.ReadAll(resp.Body)
		err = noaa_errors.NewUnauthorizedError(string(bodyData))
		return ws, err
	}

	if err == nil && cnsmr.callback != nil {
		cnsmr.callback()
	}

	if err != nil {

		return nil, errors.New(fmt.Sprintf("Error dialing traffic controller server: %s.\nPlease ask your Cloud Foundry Operator to check the platform configuration (traffic controller is %s).", err.Error(), cnsmr.trafficControllerUrl))
	}

	return ws, err
}

func (cnsmr *Consumer) proxyDial(network, addr string) (net.Conn, error) {
	targetUrl, err := url.Parse("http://" + addr)
	if err != nil {
		return nil, err
	}

	proxy := cnsmr.proxy
	if proxy == nil {
		proxy = http.ProxyFromEnvironment
	}

	proxyUrl, err := proxy(&http.Request{URL: targetUrl})
	if err != nil {
		return nil, err
	}
	if proxyUrl == nil {
		return net.Dial(network, addr)
	}

	proxyConn, err := net.Dial(network, proxyUrl.Host)
	if err != nil {
		return nil, err
	}

	connectReq := &http.Request{
		Method: "CONNECT",
		URL:    targetUrl,
		Host:   targetUrl.Host,
		Header: make(http.Header),
	}
	connectReq.Write(proxyConn)

	connectResp, err := http.ReadResponse(bufio.NewReader(proxyConn), connectReq)
	if err != nil {
		proxyConn.Close()
		return nil, err
	}
	if connectResp.StatusCode != http.StatusOK {
		f := strings.SplitN(connectResp.Status, " ", 2)
		proxyConn.Close()
		return nil, errors.New(f[1])
	}

	return proxyConn, nil
}

func (cnsmr *Consumer) retryAction(action func() error, errorChan chan<- error) {
	reconnectAttempts := 0

	oldConnectCallback := cnsmr.callback
	defer func() { cnsmr.callback = oldConnectCallback }()

	defer close(errorChan)

	cnsmr.callback = func() {
		reconnectAttempts = 0
		if oldConnectCallback != nil {
			oldConnectCallback()
		}
	}

	for ; reconnectAttempts < 5; reconnectAttempts++ {
		select {
		case <-cnsmr.stopChan:
			return
		default:
		}

		errorChan <- action()
		time.Sleep(reconnectTimeout)
	}
}


text:
package aQute.bnd.maven;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;

import aQute.bnd.build.Project;
import aQute.bnd.header.Parameters;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.bnd.service.Deploy;
import aQute.bnd.service.Plugin;
import aQute.libg.command.Command;
import aQute.service.reporter.Reporter;

public class MavenDeploy implements Deploy, Plugin {

	String		repository;
	String		url;
	String		homedir;
	String		keyname;

	String		passphrase;
	Reporter	reporter;

	public void setProperties(Map<String,String> map) {
		repository = map.get("repository");
		url = map.get("url");
		passphrase = map.get("passphrase");
		homedir = map.get("homedir");
		keyname = map.get("keyname");

		if (url == null)
			throw new IllegalArgumentException("MavenDeploy plugin must get a repository URL");
		if (repository == null)
			throw new IllegalArgumentException("MavenDeploy plugin must get a repository name");
	}

	public void setReporter(Reporter processor) {
		this.reporter = processor;
	}

	/**
	 */
	public boolean deploy(Project project, String jarName, InputStream jarStream) throws Exception {
		Parameters deploy = project.parseHeader(project.getProperty(Constants.DEPLOY));

		Map<String,String> maven = deploy.get(repository);
		if (maven == null)
			return false; // we're not playing for this bundle

		project.progress("deploying %s to Maven repo: %s", jarName, repository);
		File target = project.getTarget();
		File tmp = Processor.getFile(target, repository);
		if (!tmp.exists() && !tmp.mkdirs()) {
			throw new IOException("Could not create directory " + tmp);
		}

		Jar original = new Jar(jarName, jarStream);
		try {
			Manifest manifest = original.getManifest();
			if (manifest == null)
				project.error("Jar has no manifest: %s", original);
			else {
				project.progress("Writing pom.xml");
				PomResource pom = new PomResource(manifest);
				pom.setProperties(maven);
				File pomFile = write(tmp, pom, "pom.xml");

				Jar main = new Jar("main");
				Jar src = new Jar("src");
				try {
					split(original, main, src);
					Parameters exports = project
							.parseHeader(manifest.getMainAttributes().getValue(Constants.EXPORT_PACKAGE));
					File jdoc = new File(tmp, "jdoc");
					jdoc.mkdirs();
					project.progress("Generating Javadoc for: " + exports.keySet());
					Jar javadoc = javadoc(jdoc, project, exports.keySet());
					project.progress("Writing javadoc jar");
					File javadocFile = write(tmp, new JarResource(javadoc), "javadoc.jar");
					project.progress("Writing main file");
					File mainFile = write(tmp, new JarResource(main), "main.jar");
					project.progress("Writing sources file");
					File srcFile = write(tmp, new JarResource(main), "src.jar");

					project.progress("Deploying main file");
					maven_gpg_sign_and_deploy(project, mainFile, null, pomFile);
					project.progress("Deploying main sources file");
					maven_gpg_sign_and_deploy(project, srcFile, "sources", null);
					project.progress("Deploying main javadoc file");
					maven_gpg_sign_and_deploy(project, javadocFile, "javadoc", null);

				} finally {
					main.close();
					src.close();
				}
			}
		} finally {
			original.close();
		}
		return true;
	}

	private void split(Jar original, Jar main, Jar src) {
		for (Map.Entry<String,Resource> e : original.getResources().entrySet()) {
			String path = e.getKey();
			if (path.startsWith("OSGI-OPT/src/")) {
				src.putResource(path.substring("OSGI-OPT/src/".length()), e.getValue());
			} else {
				main.putResource(path, e.getValue());
			}
		}
	}

	// gpg:sign-and-deploy-file \
	// -Durl=http://oss.sonatype.org/service/local/staging/deploy/maven2
	// \
	// -DrepositoryId=sonatype-nexus-staging \
	// -DupdateReleaseInfo=true \
	// -DpomFile=pom.xml \
	// -Dfile=/Ws/bnd/biz.aQute.bndlib/tmp/biz.aQute.bndlib.jar \
	// -Dpassphrase=a1k3v3t5x3

	private void maven_gpg_sign_and_deploy(Project b, File file, String classifier, File pomFile) throws Exception {
		Command command = new Command();
		command.setTrace();
		command.add(b.getProperty("mvn", "mvn"));
		command.add("gpg:sign-and-deploy-file", "-DreleaseInfo=true", "-DpomFile=pom.xml");
		command.add("-Dfile=" + file.getAbsolutePath());
		command.add("-DrepositoryId=" + repository);
		command.add("-Durl=" + url);
		optional(command, "passphrase", passphrase);
		optional(command, "keyname", keyname);
		optional(command, "homedir", homedir);
		optional(command, "classifier", classifier);
		optional(command, "pomFile", pomFile == null ? null : pomFile.getAbsolutePath());

		StringBuilder stdout = new StringBuilder();
		StringBuilder stderr = new StringBuilder();

		int result = command.execute(stdout, stderr);
		if (result != 0) {
			b.error("Maven deploy to %s failed to sign and transfer %s because %s", repository, file,
					"" + stdout + stderr);
		}
	}

	private void optional(Command command, @SuppressWarnings("unused") String key, String value) {
		if (value == null)
			return;

		command.add("-D=" + value);
	}

	private Jar javadoc(File tmp, Project b, Set<String> exports) throws Exception {
		Command command = new Command();

		command.add(b.getProperty("javadoc", "javadoc"));
		command.add("-d");
		command.add(tmp.getAbsolutePath());
		command.add("-sourcepath");
		command.add(Processor.join(b.getSourcePath(), File.pathSeparator));

		for (String packageName : exports) {
			command.add(packageName);
		}

		StringBuilder out = new StringBuilder();
		StringBuilder err = new StringBuilder();
		Command c = new Command();
		c.setTrace();
		int result = c.execute(out, err);
		if (result == 0) {
			Jar jar = new Jar(tmp);
			b.addClose(jar);
			return jar;
		}
		b.error("Error during execution of javadoc command: %s / %s", out, err);
		return null;
	}

	private File write(File base, Resource r, String fileName) throws Exception {
		File f = Processor.getFile(base, fileName);
		OutputStream out = new FileOutputStream(f);
		try {
			r.write(out);
		} finally {
			out.close();
		}
		return f;
	}

}


text:
#ifndef WPANCTL_UTILS_H
#define WPANCTL_UTILS_H

#include <dbus/dbus.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "wpan-error.h"

#define ERRORCODE_OK                   (0)
#define ERRORCODE_HELP                 (1)
#define ERRORCODE_BADARG               (2)
#define ERRORCODE_NOCOMMAND            (3)
#define ERRORCODE_UNKNOWN              (4)
#define ERRORCODE_BADCOMMAND           (5)
#define ERRORCODE_NOREADLINE           (6)
#define ERRORCODE_QUIT                 (7)
#define ERRORCODE_BADCONFIG            (8)
#define ERRORCODE_ERRNO                (9)
#define ERRORCODE_NOT_IMPLEMENTED      (10)
#define ERRORCODE_TIMEOUT              (11)
#define ERRORCODE_BADVERSION           (12)
#define ERRORCODE_ALLOC                (13)
#define ERRORCODE_NOTFOUND             (14)
#define ERRORCODE_REFUSED              (15)
#define ERRORCODE_INTERRUPT            (128 + SIGINT)
#define ERRORCODE_SIGHUP               (128 + SIGHUP)

#define DEFAULT_TIMEOUT_IN_SECONDS     60

#define WPANCTL_PREFIX_SIZE            8
#define WPANCTL_XPANID_SIZE            8
#define WPANCTL_NETWORK_KEY_SIZE       16
#define WPANCTL_IPv6_ADDRESS_SIZE      16
#define WPANCTL_NETWORK_NAME_MAX_LEN   16  // Max number of chars

struct command_info_s {
	const char* name;
	const char* desc;
	int (*entrypoint)(
	    int argc, char* argv[]);
	int isHidden;
};

struct wpan_network_info_s {
	char network_name[17];
	dbus_bool_t allowing_join;
	uint16_t pan_id;
	int16_t channel;
	uint64_t xpanid;
	int8_t rssi;
	uint8_t type;
	uint8_t hwaddr[8];
};

enum joiner_state{
    JOINER_STATE_IDLE = 0,
    JOINER_STATE_DISCOVER = 1,
    JOINER_STATE_CONNECT = 2,
    JOINER_STATE_CONNECTED = 3,
    JOINER_STATE_ENTRUST = 4,
    JOINER_STATE_JOINED = 5,
};

void print_error_diagnosis(int error);
int parse_network_info_from_iter(struct wpan_network_info_s *network_info, DBusMessageIter *iter);
int parse_energy_scan_result_from_iter(int16_t *channel, int8_t *maxRssi, DBusMessageIter *iter);

// Parses a given (ULA, mesh-local) prefix string `prefix_str` and output the result in `prefix` array (expected 8 bytes)
// Returns ERRORCODE_OK on success or otherwise the error code.
int parse_prefix(const char *prefix_str, uint8_t *prefix);

// Parses a node type argument (e.g., for `form` or `join` command) and converts it to `kWPANTUNDNodeType_<type>`
// string.
const char *parse_node_type(const char *type_arg);

int lookup_dbus_name_from_interface(char* dbus_bus_name, const char* interface_name);
void dump_info_from_iter(FILE* file, DBusMessageIter *iter, int indent, bool bare, bool indentFirstLine);
uint16_t node_type_str2int(const char *node_type);
const char *node_type_int2str(uint16_t node_type);
const char *joiner_state_int2str(uint8_t state);

int create_new_wpan_dbus_message(DBusMessage **message, const char *dbus_command);
void append_dbus_dict_entry_basic(DBusMessageIter *dict_iter, const char *key, char dbus_basic_type, void *value);
void append_dbus_dict_entry_byte_array(DBusMessageIter *dict_iter, const char *key, const uint8_t *data, int data_len);

extern char gInterfaceName[32];
extern int gRet;

#endif


text:
var express = require('express')(),
  qr = require('qr-image');

var packageInfo = require('./package.json');
var config = {
  "paramName": process.env['PARAM_NAME'] || 'uri',
  "uriPrefix": process.env['URI_PREFIX'] || '',
  "port": process.env['PORT'] || process.env['HTTP_PORT'] || 8080
};

// Only respond to requests on /
express.get('/', function (req, res) {
  // Build the URI
  var uriSuffix = (req.query[config.paramName] || '');
  var uri = config.uriPrefix + uriSuffix;

  // Generate the SVG image
  var svg_string = qr.imageSync(uri, {type: 'svg'});

  // Respond with the SVG string using the appropriate MIME type
  res.setHeader('Content-Type', 'image/svg+xml');
  res.end(svg_string);
});

// Start listening for HTTP requests
express.listen(config.port, function () {
  console.info(packageInfo.name, 'is now listening on port', config.port);
});


text:
package org.restler.spring.data.calls;

import org.restler.client.Call;
import org.restler.client.CallExecutor;

import java.lang.reflect.Type;
import java.util.List;
import java.util.function.BinaryOperator;

/**
 * Call is used for executing chain of calls.
 */
public class ChainCall implements Call {

    /**
     * {@code} accumulator is used to combine multiple results of nested calls into single result of chain call.
     * Probably it's should be replaced by full-blown reduce framework (with identity, accumulator and combiner)
     */
    private final BinaryOperator<Object> accumulator;
    private final List<Call> calls;
    private final Type returnType;

    public ChainCall(BinaryOperator<Object> modifierFunction, List<Call> calls, Type returnType) {
        this.accumulator = modifierFunction;
        this.calls = calls;
        this.returnType = returnType;
    }

    public ChainCall(List<Call> calls, Type returnType) {
        this(null, calls, returnType);
    }

    /**
     * Executes chain of calls using {@link CallExecutor}.
     */
    Object execute(CallExecutor executor) {
        Object result = null;

        if (accumulator != null) {
            result = calls.stream().
                    map(executor::execute).
                    reduce(null, accumulator);
        } else {
            calls.forEach(executor::execute);
        }

        return result;
    }

    @Override
    public Type getReturnType() {
        return returnType;
    }

    @Override
    public Call withReturnType(Type type) {
        return new ChainCall(calls, type);
    }
}


text: env GOOS=linux GOARCH=arm CC=arm-linux-gnueabi-gcc go build -o binary/link022_agent agent/agent.go


text:
<meta charset="UTF-8">
<title>KClassLoader - test</title>

test / KClassLoader

KClassLoader

object KClassLoader

Functions

foo

fun foo(c: Enum<*>): Unit


text:
package com.github.luiz.lamusique.models;

import java.util.Objects;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "artist", uniqueConstraints = {
		@UniqueConstraint(columnNames = {"name"})
})
public class Artist {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "artist_id")
	private Integer id;

	@Column(name = "name", nullable = false)
	@NotNull
	private String name;

	public Integer getId() {
		return this.id;
	}

	public void setId(final Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		return this.name.hashCode();
	}

	@Override
	public boolean equals(final Object obj) {
		if (!(obj instanceof Artist)) {
			return false;
		}
		final Artist other = (Artist) obj;
		return Objects.equals(this.name, other.name);
	}
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('events', '0002_auto_20150325_1453'),
    ]

    operations = [
        migrations.AlterField(
            model_name='event',
            name='section',
            field=models.ForeignKey(blank=True, to='events.Section', null=True),
            preserve_default=True,
        ),
    ]


text:
(function ( window, document ) {
  "use strict";

  var metaQuery = {
    breakpoints: {},
    _isTicking: false,
    _debounceLastTime: 0,
    _namedEvents: {},
    _eventMatchCache: {},
    _globalEvents: [],
    onBreakpointChange: function () {
      var args = Array.prototype.slice.call( arguments ),
            fn = args.pop(),
            name = args.pop();

      if ( typeof name === "undefined" ) {
        metaQuery._globalEvents.push( fn );
      } else {
        ( metaQuery._namedEvents[name] = [] ).push( fn );
      }
      mqChange();
    }
  },

  // Pinched domready
  // http://www.dustindiaz.com/smallest-domready-ever/
  readyState = function ( fn ) {
    if ( /in/.test( document.readyState ) ) {
      window.setTimeout( function () {
        readyState( fn );
      }, 9 );
    } else {
      fn();
    }
  },

  removeClass = function( element, className ) {
    var classes = element.className.split( ' ' ),
        index = classes.indexOf( className );

    if ( index > -1 ) {
      classes.splice( index, 1 );
      element.className = classes.join( ' ' );
    }
  },

  addClass = function(element, className) {
    if ( element.className.indexOf(className) === -1 ) {
      element.className = ( element.className !== '' ) ? ( element.className + ' ' + className ) : className;
    }
  },

  updateClasses = function ( matches, name ) {
    var breakpoint = 'breakpoint-' + name,
        htmlNode = document.documentElement;

    if ( matches ) {
      addClass( htmlNode, breakpoint );
    } else {
      removeClass( htmlNode, breakpoint );
    }
  },

  callGlobalEvents = function( activeBreakpoints ) {
    metaQuery._globalEvents.forEach(function(gfn) {
      if ( typeof gfn === 'function' ) { gfn(activeBreakpoints); }
    });
  },

  requestMqChange = function() {
    if( !metaQuery._isTicking ) {
      requestAnimationFrame( mqChange );
    }
    metaQuery._isTicking = true;
  },

  // A rAF fallback, adapted from https://gist.github.com/paulirish/1579671
  requestAnimationFrame = function( callback, element ) {
    if ( window.requestAnimationFrame ) {
      window.requestAnimationFrame( callback, element );
    } else {
      var currTime = new Date().getTime();
      var timeToCall = Math.max( 0, 16 - ( currTime - metaQuery._debounceLastTime ) );
      var id = window.setTimeout(function () {
        callback( currTime + timeToCall );
      }, timeToCall );

      metaQuery._debounceLastTime = currTime + timeToCall;

      return id;
    }
  },

  // Called when a media query changes state
  mqChange = function () {
    metaQuery._isTicking = false;
    var activeBreakpoints = [];

    for( var name in metaQuery.breakpoints ) {
      var query = metaQuery.breakpoints[name],
          matches = window.matchMedia( query ).matches;

      // Call events bound to a given breakpoint
      if ( metaQuery._namedEvents[name] && metaQuery._eventMatchCache[name] !== matches ) {
        metaQuery._eventMatchCache[name] = matches;
        for ( var i = 0; i < metaQuery._namedEvents[name].length; i++ ) {
          var fn = metaQuery._namedEvents[name][i];

          if ( typeof fn === 'function' ) { fn( matches ); }
        }
      }

      // store the matching mq
      if ( matches ) {
        activeBreakpoints.push( name );
      }

      updateClasses( matches, name );
    }

    // call any global events
    if ( activeBreakpoints.length !== 0 ) {
      callGlobalEvents( activeBreakpoints );
    }
  },

  collectMediaQueries = function () {
    var meta = document.getElementsByTagName( 'meta' );

    // Add classes to the HTML node when a breakpoint matches
    for ( var i = 0; i < meta.length; i++ ) {
      if ( meta[i].name === 'breakpoint' ) {
        var name = meta[i].getAttribute( 'content' ),
            query = meta[i].getAttribute( 'media' );

        metaQuery.breakpoints[name] = query;
      }
    }
  },

  // If the META tags are defined above this script,
  // we don't need to wait for domReady to set the breakpoint
  // class on the HTML element, fighting the FOUT.
  preDomReady = function () {
    collectMediaQueries();
    mqChange();
  },

  // After domReady, we can be sure all our META and IMG tags
  // are in the DOM.
  onDomReady = function () {
    collectMediaQueries();
    mqChange();
    window.addEventListener( 'resize', requestMqChange );
  };

  if ( typeof module !== 'undefined' && module.exports ) {
    module.exports = metaQuery;
  } else {
    window.metaQuery = metaQuery;
  }

  preDomReady();
  readyState( onDomReady );

}( window, document ));


text:
<?xml version="1.0" ?>
<project name="xdocs" default="site" basedir=".">

	<property name="docs.src" value="./src" />
	<property name="docs.dest" value="../doc" />

	<property name="logging-site" value="../../../site/trunk" />

	<!-- Construct classpath for building the html pages -->
	<path id="site.classpath">
		<fileset dir="${logging-site}/lib">
			<include name="*.jar" />
		</fileset>
	</path>

	<!-- ============================ -->
	<!-- ======= New targets ======== -->
	<!-- ============================ -->

	<target name="prepareSite">
		<available classname="org.apache.velocity.anakia.AnakiaTask" property="AnakiaTask.present">
			<classpath refid="site.classpath" />
		</available>
	</target>

	<target name="checkSite" depends="prepareSite" unless="AnakiaTask.present">
		<echo>AnakiaTask is not present! Please check to make sure that velocity.jar is in your classpath.</echo>
	</target>

	<target name="site" depends="checkSite" if="AnakiaTask.present">
		<taskdef name="anakia" classname="org.apache.velocity.anakia.AnakiaTask">
			<classpath refid="site.classpath" />
		</taskdef>

		<mkdir dir="${docs.dest}/css" />
		<copy file="${logging-site}/docs/css/site.css" tofile="${docs.dest}/css/site.css" />

		<anakia
			basedir="${docs.src}"
			destdir="${docs.dest}/"
			extension=".html"
			style="site.vsl"
			projectFile="stylesheets/project.xml"
			excludes="empty.xml, anakia-project.xml, **/stylesheets/**"
			includes="**/*.xml"
			lastModifiedCheck="true"
			templatePath="${docs.src}/stylesheets">
		</anakia>

	</target>

</project>