text:
package org.deeplearning4j.models.embeddings.learning.impl.elements;

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.RandomUtils;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.learning.ElementsLearningAlgorithm;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.sequencevectors.interfaces.SequenceIterator;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.nd4j.autodiff.samediff.internal.memory.ArrayCacheMemoryMgr;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.CustomOp;
import org.nd4j.linalg.api.ops.aggregates.Aggregate;
import org.nd4j.linalg.api.ops.impl.nlp.SkipGramInference;
import org.nd4j.linalg.api.ops.impl.nlp.SkipGramRound;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.DeviceLocalNDArray;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class SkipGram<T extends SequenceElement> implements ElementsLearningAlgorithm<T> {
    protected VocabCache<T> vocabCache;
    protected WeightLookupTable<T> lookupTable;
    protected VectorsConfiguration configuration;
    private ArrayCacheMemoryMgr  arrayCacheMemoryMgr;
    protected int window;
    protected boolean useAdaGrad;
    protected double negative;
    protected double sampling;
    protected int[] variableWindows;
    protected int vectorLength;
    protected int workers = Runtime.getRuntime().availableProcessors();

    public int getWorkers() {
        return workers;
    }

    public void setWorkers(int workers) {
        this.workers = workers;
    }

    @Getter
    @Setter
    protected DeviceLocalNDArray syn0, syn1, syn1Neg, table, expTable;

    protected ThreadLocal<List<Aggregate>> batches = new ThreadLocal<>();

    /**
     * Dummy construction is required for reflection
     */
    public SkipGram() {
    }

    public List<Aggregate> getBatch() {
        return batches.get();
    }

    /**
     * Returns implementation code name
     *
     * @return
     */
    @Override
    public String getCodeName() {
        return "SkipGram";
    }

    /**
     * SkipGram initialization over given vocabulary and WeightLookupTable
     *
     * @param vocabCache
     * @param lookupTable
     * @param configuration
     */
    @Override
    public void configure(@NonNull VocabCache<T> vocabCache, @NonNull WeightLookupTable<T> lookupTable,
                          @NonNull VectorsConfiguration configuration) {
        this.vocabCache = vocabCache;
        this.lookupTable = lookupTable;
        this.configuration = configuration;
        arrayCacheMemoryMgr = new ArrayCacheMemoryMgr();
        if (configuration.getNegative() > 0) {
            if (((InMemoryLookupTable<T>) lookupTable).getSyn1Neg() == null) {
                log.info("Initializing syn1Neg...");
                ((InMemoryLookupTable<T>) lookupTable).setUseHS(configuration.isUseHierarchicSoftmax());
                ((InMemoryLookupTable<T>) lookupTable).setNegative(configuration.getNegative());
                lookupTable.resetWeights(false);
            }
        }

        this.syn0 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn0());
        this.syn1 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1());
        this.syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
        this.expTable = new DeviceLocalNDArray(Nd4j.create(((InMemoryLookupTable<T>) lookupTable).getExpTable(),
                new long[]{((InMemoryLookupTable<T>) lookupTable).getExpTable().length}, syn0.get() == null ? DataType.DOUBLE
                        : syn0.get().dataType()));
        this.table = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getTable());

        this.window = configuration.getWindow();
        this.useAdaGrad = configuration.isUseAdaGrad();
        this.negative = configuration.getNegative();
        this.sampling = configuration.getSampling();
        this.variableWindows = configuration.getVariableWindows();

        this.vectorLength = configuration.getLayersSize();
    }

    /**
     * SkipGram doesn't involve any pretraining
     *
     * @param iterator
     */
    @Override
    public void pretrain(SequenceIterator<T> iterator) {
        // no-op
    }

    public Sequence<T> applySubsampling(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom) {
        Sequence<T> result = new Sequence<>();

        // subsampling implementation, if subsampling threshold met, just continue to next element
        if (sampling > 0) {
            result.setSequenceId(sequence.getSequenceId());
            if (sequence.getSequenceLabels() != null)
                result.setSequenceLabels(sequence.getSequenceLabels());
            if (sequence.getSequenceLabel() != null)
                result.setSequenceLabel(sequence.getSequenceLabel());

            for (T element : sequence.getElements()) {
                double numWords = vocabCache.totalWordOccurrences();
                double ran = (Math.sqrt(element.getElementFrequency() / (sampling * numWords)) + 1)
                        * (sampling * numWords) / element.getElementFrequency();

                nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));

                if (ran < (nextRandom.get() & 0xFFFF) / (double) 65536) {
                    continue;
                }
                result.addElement(element);
            }
            return result;
        } else
            return sequence;
    }

    public double learnSequence(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom, double learningRate,
                                BatchSequences<T> batchSequences) {
        Sequence<T> tempSequence = sequence;
        if (sampling > 0)
            tempSequence = applySubsampling(sequence, nextRandom);

        List<BatchItem<T>> batch = new ArrayList<>();

        double score = 0.0;

        int currentWindow = window;

        if (variableWindows != null && variableWindows.length != 0) {
            currentWindow = variableWindows[RandomUtils.nextInt(0, variableWindows.length)];
        }

        for (int i = 0; i < tempSequence.getElements().size(); i++) {
            nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
            if(currentWindow > 0)
                score = skipGram(i, tempSequence.getElements(), (int) nextRandom.get() % currentWindow, nextRandom,
                        learningRate, currentWindow, batch);
            else
                score = skipGram(i, tempSequence.getElements(), (int) nextRandom.get() , nextRandom,
                        learningRate, currentWindow, batch);

        }

        if (!batch.isEmpty()) {
            score = iterateSample(batch);
        }

        return score;
    }
    /**
     * Learns sequence using SkipGram algorithm
     *
     * @param sequence
     * @param nextRandom
     * @param learningRate
     */
    @Override
    public double learnSequence(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom, double learningRate) {
        Sequence<T> tempSequence = sequence;
        if (sampling > 0)
            tempSequence = applySubsampling(sequence, nextRandom);
        List<BatchItem<T>> batch = new ArrayList<>();

        double score = 0.0;

        int currentWindow = window;

        if (variableWindows != null && variableWindows.length != 0) {
            currentWindow = variableWindows[RandomUtils.nextInt(0, variableWindows.length)];
        }
        for (int i = 0; i < tempSequence.getElements().size(); i++) {
            nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
            score = skipGram(i, tempSequence.getElements(), (int) nextRandom.get() % currentWindow, nextRandom,
                    learningRate, currentWindow);
        }

        if (batches != null && batches.get() != null && batches.get().size() >= configuration.getBatchSize()) {
            score = iterateSample(batch);
        }

        return score;
    }

    @Override
    public void finish() {
        if (batches != null && batches.get() != null && !batches.get().isEmpty()) {
            Nd4j.getExecutioner().exec(batches.get());
            batches.get().clear();
        }
    }

    /**
     * SkipGram has no reasons for early termination ever.
     *
     * @return
     */
    @Override
    public boolean isEarlyTerminationHit() {
        return false;
    }

    private double skipGram(int i, List<T> sentence, int b, AtomicLong nextRandom, double alpha, int currentWindow) {
        final T word = sentence.get(i);
        if (word == null || sentence.isEmpty())
            return 0.0;

        double score = 0.0;

        int end = currentWindow * 2 + 1 - b;
        for (int a = b; a < end; a++) {
            if (a != currentWindow) {
                int c = i - currentWindow + a;
                if (c >= 0 && c < sentence.size()) {
                    T lastWord = sentence.get(c);
                    score = iterateSample(word, lastWord, nextRandom, alpha, false, null);
                }
            }
        }

        return score;
    }

    private double skipGram(int i, List<T> sentence, int b, AtomicLong nextRandom, double alpha, int currentWindow,
                            List<BatchItem<T>> batchSequences) {
        final T word = sentence.get(i);
        if (word == null || sentence.isEmpty() || word.isLocked())
            return 0.0;

        double score = 0.0;
        int batchSize = configuration.getBatchSize();

        int end = currentWindow * 2 + 1 - b;
        for (int a = b; a < end; a++) {
            if (a != currentWindow) {
                int c = i - currentWindow + a;
                if (c >= 0 && c < sentence.size()) {
                    T lastWord = sentence.get(c);
                    nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
                    if (batchSize <= 1) {
                        score = iterateSample(word, lastWord, nextRandom, alpha, false, null);
                    }
                    else {
                        BatchItem<T> batchItem = new BatchItem<>(word,lastWord,nextRandom.get(),alpha);
                        batchSequences.add(batchItem);
                    }
                }
            }
        }

        return score;
    }

    public CustomOp iterateSampleOp(T w1, T lastWord, AtomicLong nextRandom, double alpha, boolean isInference,
                                    INDArray inferenceVector) {
        if (w1 == null || lastWord == null || (lastWord.getIndex() < 0 && !isInference)
                || w1.getIndex() == lastWord.getIndex() || w1.getLabel().equals("STOP")
                || lastWord.getLabel().equals("STOP") || w1.getLabel().equals("UNK")
                || lastWord.getLabel().equals("UNK")) {
            return null;
        }

        int[] idxSyn1 = null;
        byte[] codes = null;
        if (configuration.isUseHierarchicSoftmax()) {
            idxSyn1 = new int[w1.getCodeLength()];
            codes = new byte[w1.getCodeLength()];
            for (int i = 0; i < w1.getCodeLength(); i++) {
                int code = w1.getCodes().get(i);
                int point = w1.getPoints().get(i);
                if (point >= vocabCache.numWords() || point < 0)
                    continue;

                codes[i] = (byte)code;
                idxSyn1[i] = point;
            }
        } else {
            idxSyn1 = new int[0];
            codes = new byte[0];
        }

        int target = w1.getIndex();
        //negative sampling
        if (negative > 0) {
            if (syn1Neg == null) {
                ((InMemoryLookupTable<T>) lookupTable).initNegative();
                syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
            }
        }

        if (batches.get() == null) {
            batches.set(new ArrayList<>());
        }

        nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));

        SkipGramInference sg = null;
        boolean useHS = configuration.isUseHierarchicSoftmax();
        boolean useNegative = configuration.getNegative() > 0;

        List<INDArray> release = new ArrayList<>();
        if (useHS && useNegative) {
            INDArray idxSyn1Arr = arrayCacheMemoryMgr.allocate(false,DataType.INT32,idxSyn1.length);

            sg = SkipGramInference.builder()
                    .target(lastWord.getIndex())
                    .ngStarter(target)
                    .syn0(syn0.get())
                    .syn1(syn1.get())
                    .syn1Neg(syn1Neg.get())
                    .expTable(expTable.get())
                    .negTable(table.get())
                    .nsRounds(0)
                    .indices(idxSyn1)
                    .codes(codes)
                    .randomValue((int) nextRandom.get())
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .alpha(alpha)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .build();

            release.add(idxSyn1Arr);

        }
        else if (useHS) {
            sg = SkipGramInference.builder()
                    .target(lastWord.getIndex())
                    .ngStarter(-1)
                    .syn0(syn0.get())
                    .syn1(syn1.get())
                    .syn1Neg(Nd4j.empty(syn0.get().dataType()))
                    .expTable(expTable.get() != null ? expTable.get() : Nd4j.empty(syn0.get().dataType()))
                    .negTable(table.get() != null ? table.get() : Nd4j.empty(syn0.get().dataType()))
                    .nsRounds((int) negative)
                    .alpha(alpha)
                    .randomValue((int) nextRandom.get())
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .codes(codes)
                    .indices(idxSyn1)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .build();

        }
        else if (useNegative) {
            INDArray negativeArr = arrayCacheMemoryMgr.allocate(false,DataType.INT32,1);
            negativeArr.putScalar(0,negative);

            sg = SkipGramInference.builder()
                    .ngStarter(target)
                    .target(lastWord.getIndex())
                    .syn0(syn0.get())
                    .syn1(Nd4j.empty(syn0.get().dataType()))
                    .codes(new byte[0])
                    .indices(new int[0])
                    .negTable(negativeArr)
                    .syn1Neg(syn1Neg.get())
                    .expTable(expTable.get())
                    .syn1(syn1.get())
                    .randomValue((int) nextRandom.get())
                    .alpha(alpha)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .build();

            release.add(negativeArr);

        }

        return sg;
    }

    public double iterateSample(T w1, T lastWord, AtomicLong nextRandom, double alpha, boolean isInference,
                                INDArray inferenceVector) {
        if (w1 == null || lastWord == null || (lastWord.getIndex() < 0 && !isInference)
                || w1.getIndex() == lastWord.getIndex() || w1.getLabel().equals("STOP")
                || lastWord.getLabel().equals("STOP") || w1.getLabel().equals("UNK")
                || lastWord.getLabel().equals("UNK")) {
            return 0.0;
        }

        double score = 0.0;

        int[] idxSyn1 = null;
        byte[] codes = null;
        if (configuration.isUseHierarchicSoftmax()) {
            idxSyn1 = new int[w1.getCodeLength()];
            codes = new byte[w1.getCodeLength()];
            for (int i = 0; i < w1.getCodeLength(); i++) {
                int code = w1.getCodes().get(i);
                int point = w1.getPoints().get(i);
                if (point >= vocabCache.numWords() || point < 0)
                    continue;

                codes[i] = (byte)code;
                idxSyn1[i] = point;
            }
        } else {
            idxSyn1 = new int[0];
            codes = new byte[0];
        }

        int target = w1.getIndex();
        //negative sampling
        if (negative > 0) {
            if (syn1Neg == null) {
                ((InMemoryLookupTable<T>) lookupTable).initNegative();
                syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
            }
        }

        if (batches.get() == null) {
            batches.set(new ArrayList<>());
        }

        nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));

        SkipGramInference sg = null;
        boolean useHS = configuration.isUseHierarchicSoftmax();
        boolean useNegative = configuration.getNegative() > 0;

        List<INDArray> release = new ArrayList<>();
        if (useHS && useNegative) {
            INDArray idxSyn1Arr = arrayCacheMemoryMgr.allocate(false,DataType.INT32,idxSyn1.length);

            sg = SkipGramInference.builder()
                    .target(lastWord.getIndex())
                    .ngStarter(target)
                    .syn0(syn0.get())
                    .syn1(syn1.get())
                    .syn1Neg(syn1Neg.get())
                    .expTable(expTable.get())
                    .negTable(table.get())
                    .nsRounds(0)
                    .indices(idxSyn1)
                    .codes(codes)
                    .randomValue((int) nextRandom.get())
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .alpha(alpha)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .build();

            release.add(idxSyn1Arr);

        }
        else if (useHS) {
            sg = SkipGramInference.builder()
                    .target(lastWord.getIndex())
                    .ngStarter(-1)
                    .syn0(syn0.get())
                    .syn1(syn1.get())
                    .syn1Neg(Nd4j.empty(syn0.get().dataType()))
                    .expTable(expTable.get() != null ? expTable.get() : Nd4j.empty(syn0.get().dataType()))
                    .negTable(table.get() != null ? table.get() : Nd4j.empty(syn0.get().dataType()))
                    .nsRounds((int) negative)
                    .alpha(alpha)
                    .randomValue((int) nextRandom.get())
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .codes(codes)
                    .indices(idxSyn1)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .build();

        }
        else if (useNegative) {
            INDArray negativeArr = arrayCacheMemoryMgr.allocate(false,DataType.INT32,1);
            negativeArr.putScalar(0,negative);

            sg = SkipGramInference.builder()
                    .ngStarter(target)
                    .target(lastWord.getIndex())
                    .syn0(syn0.get())
                    .syn1(Nd4j.empty(syn0.get().dataType()))
                    .codes(new byte[0])
                    .indices(new int[0])
                    .negTable(negativeArr)
                    .syn1Neg(syn1Neg.get())
                    .expTable(expTable.get())
                    .syn1(syn1.get())
                    .randomValue((int) nextRandom.get())
                    .alpha(alpha)
                    .preciseMode(configuration.isPreciseMode())
                    .numWorkers(workers)
                    .inferenceVector(inferenceVector != null ? inferenceVector : Nd4j.empty(syn0.get().dataType()))
                    .build();

            release.add(negativeArr);

        }

        Nd4j.getExecutioner().exec(sg);

        //release after use
        for(INDArray arr : release)
            arrayCacheMemoryMgr.release(arr);

        return score;
    }

    public double iterateSample(List<BatchItem<T>> items) {
        boolean useHS = configuration.isUseHierarchicSoftmax();
        boolean useNegative = configuration.getNegative() > 0;

        double score = 0.0;
        boolean isInference = false;

        int[] targets = new int[items.size()];
        int[] starters = new int[items.size()];
        double[] alphas = new double[items.size()];
        long[] randomValues = new long[items.size()];

        int maxCols = 1;
        for (int i = 0; i < items.size(); ++i) {
            int curr = items.get(i).getWord().getCodeLength();
            if (curr > maxCols)
                maxCols = curr;
        }

        byte[][] codes = new byte[items.size()][maxCols];
        int[][] indices = new int[items.size()][maxCols];

        for (int cnt = 0; cnt < items.size(); ++cnt) {
            T w1 = items.get(cnt).getWord();
            T lastWord = items.get(cnt).getLastWord();
            randomValues[cnt] = items.get(cnt).getRandomValue();
            double alpha = items.get(cnt).getAlpha();

            if (w1 == null || lastWord == null || (lastWord.getIndex() < 0 && !isInference)
                    || w1.getIndex() == lastWord.getIndex() || w1.getLabel().equals("STOP")
                    || lastWord.getLabel().equals("STOP") || w1.getLabel().equals("UNK")
                    || lastWord.getLabel().equals("UNK")) {
                continue;
            }

            int target = lastWord.getIndex();
            int ngStarter = w1.getIndex();

            targets[cnt] = target;
            starters[cnt] = ngStarter;
            alphas[cnt] = alpha;

            int[] idxSyn1 = null;
            byte[] interimCodes = null;
            if (useHS) {
                idxSyn1 = new int[w1.getCodeLength()];
                interimCodes = new byte[w1.getCodeLength()];
                for (int i = 0; i < w1.getCodeLength(); i++) {
                    int code = w1.getCodes().get(i);
                    int point = w1.getPoints().get(i);
                    if (point >= vocabCache.numWords() || point < 0)
                        continue;

                    interimCodes[i] = (byte) code;
                    idxSyn1[i] = point;
                }
                for (int i = 0; i < maxCols; ++i) {
                    if (i < w1.getCodeLength())
                        codes[cnt][i] = interimCodes[i];
                    else
                        codes[cnt][i] = -1;
                }
                for (int i = 0; i < maxCols; ++i) {
                    if (i < w1.getCodeLength())
                        indices[cnt][i]  = idxSyn1[i];
                    else
                        indices[cnt][i] = -1;
                }

            } else {
                idxSyn1 = new int[0];
                interimCodes = new byte[0];
                codes = new byte[0][0];
                indices = new int[0][0];
            }

            //negative sampling
            if (negative > 0) {
                if (syn1Neg == null) {
                    ((InMemoryLookupTable<T>) lookupTable).initNegative();
                    syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
                }
            }
        }

        INDArray targetArray = Nd4j.createFromArray(targets);
        INDArray ngStarterArray = Nd4j.createFromArray(starters);
        INDArray alphasArray = Nd4j.createFromArray(alphas);
        INDArray randomValuesArray = Nd4j.createFromArray(randomValues);
        INDArray indicesArray = Nd4j.createFromArray(indices);
        INDArray codesArray = Nd4j.createFromArray(codes);
        SkipGramRound sg = SkipGramRound.builder()
                .target(targetArray)
                .expTable(expTable.get())
                .ngStarter( (negative > 0) ? ngStarterArray : Nd4j.empty(DataType.INT32))
                .syn0(syn0.get())
                .syn1(useHS ? syn1.get() : Nd4j.empty(syn0.get().dataType()))
                .syn1Neg( (negative > 0) ? syn1Neg.get() : Nd4j.empty(syn0.get().dataType()))
                .negTable( (negative > 0) ? table.get() : Nd4j.empty(syn0.get().dataType()))
                .indices( useHS ? indicesArray : Nd4j.empty(DataType.INT32))
                .codes(useHS ? codesArray : Nd4j.empty(DataType.INT8))
                .alpha(alphasArray)
                .randomValue(randomValuesArray)
                .inferenceVector( Nd4j.empty(syn0.get().dataType()))
                .preciseMode(configuration.isPreciseMode())
                .numWorkers(workers)
                .build();

        Nd4j.getExecutioner().exec(sg);

        return score;
    }
}


text: 0 {{namespace}}

redpajama_set_name: RedPajamaGithub


text:
package org.ldp4j.generic.ldp.runtime;

import com.hp.hpl.jena.rdf.model.*;
import org.ldp4j.generic.http.RepresentationPreference;
import org.ldp4j.generic.ldp.model.Preference;
import org.ldp4j.generic.rdf.vocab.LDP;
import org.ldp4j.generic.util.RdfUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.ldp4j.generic.util.RdfUtils.property;
import static org.ldp4j.generic.util.RdfUtils.resource;

public class DirectContainerStrategy extends BaseContainerStrategy {

    private static final Logger logger = LoggerFactory.getLogger(DirectContainerStrategy.class);

    protected Resource membershipResource;

    protected boolean isInverse;

    protected Resource hasMemberRelation;

    protected Resource isMemberOfRelation;

    @Override
    public void addMemberTriple(String containerURI, String newURI, Model resource, Model container) {

        logger.debug("Adding the new member '{}' to the  Direct container {}", newURI, containerURI);

        process(containerURI, container);

        if(isInverse){
            logger.debug("Adding the member triple ...\n <{}> <{}> <{}>", newURI, isMemberOfRelation.getURI(),
                    membershipResource.getURI());
            container.add(resource(newURI), property(isMemberOfRelation.getURI()), membershipResource);
        } else {
            logger.debug("Adding the member triple ...\n <{}> <{}> <{}>", membershipResource.getURI(), hasMemberRelation.getURI(),
                    newURI);
            container.add(membershipResource, property(hasMemberRelation.getURI()), resource(newURI));
        }

    }

    protected void process(String containerURI, Model model) {

        Resource container = model.getResource(containerURI);

        membershipResource = container.getPropertyResourceValue(LDP.membershipResource);
        hasMemberRelation = container.getPropertyResourceValue(LDP.hasMemberRelation);
        if(hasMemberRelation == null){
            isMemberOfRelation = container.getPropertyResourceValue(LDP.isMemberOfRelation);
            isInverse = true;
        }

        if (membershipResource == null || (hasMemberRelation == null && isMemberOfRelation == null)) {
            logger.error("Invalid direct container state ... \n{}", RdfUtils.toString(model));
            throw new IllegalStateException("Invalid direct container state");
        }

    }

    @Override
    public Model getPreferredRepresentation(String containerURI, Model model, RepresentationPreference preference) {

        boolean isMinital = preference.isMinimalInclusionRequired();

        Model preferredModel = null;

        // Remove the containment triples
        if ( isMinital || preference.isOmissiontRequired(Preference.CONTAINMENT_TRIPLES)) {
            StmtIterator containStatements = model.listStatements(model.createResource(containerURI), LDP.contains, (RDFNode) null);
            Model containmentTriples = ModelFactory.createDefaultModel();
            containmentTriples.add(containStatements);

            preferredModel = model.difference(containmentTriples);

        }
        //TODO finish the removal of membership triples

        return preferredModel;

    }

}


text:
<resources>
    <dimen name="ld_side_margin">22dp</dimen>
    <dimen name="ld_side_cb_margin">16dp</dimen>
</resources>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Text;

namespace System.Linq.Expressions
{
  // Summary:
  //     Represents an initializer for a single element of an System.Collections.IEnumerable
  //     collection.
  public sealed class ElementInit
  {
    private ElementInit() { }

    // Summary:
    //     Gets the instance method that is used to add an element to an System.Collections.IEnumerable
    //     collection.
    //
    // Returns:
    //     A System.Reflection.MethodInfo that represents an instance method that adds
    //     an element to a collection.
    public MethodInfo AddMethod
    {
      get
      {
        Contract.Ensures(Contract.Result<MethodInfo>() != null);
        return default(MethodInfo);
      }
    }
    //
    // Summary:
    //     Gets the collection of arguments that are passed to a method that adds an
    //     element to an System.Collections.IEnumerable collection.
    //
    // Returns:
    //     A System.Collections.ObjectModel.ReadOnlyCollection<T> of System.Linq.Expressions.Expression
    //     objects that represent the arguments for a method that adds an element to
    //     a collection.
    public ReadOnlyCollection<Expression> Arguments
    {
      get
      {
        Contract.Ensures(Contract.Result<ReadOnlyCollection<Expression>>() != null);
        Contract.Ensures(Contract.Result<ReadOnlyCollection<Expression>>().Count >= 1);
        return default(ReadOnlyCollection<Expression>);
      }
    }

#if NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0
    //
    // Summary:
    //     Creates a new expression that is like this one, but using the supplied children.
    //     If all of the children are the same, it will return this expression.
    //
    // Parameters:
    //   arguments:
    //     The System.Linq.Expressions.ElementInit.Arguments property of the result.
    //
    // Returns:
    //     This expression if no children are changed or an expression with the updated
    //     children.
    [Pure]
    public ElementInit Update(IEnumerable<Expression> arguments)
    {
      Contract.Requires(arguments != null);
      Contract.Ensures(Contract.Result<ElementInit>() != null);
      return default(ElementInit);
    }
#endif
  }
}


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

<TITLE>
Wildcards
</TITLE>

<META NAME="date" CONTENT="2013-08-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.openflow.protocol

Class Wildcards

java.lang.Object
  org.openflow.protocol.Wildcards

public class Wildcards
extends java.lang.Object

a more user friendly representation of the wildcards bits in an OpenFlow
 match. The Wildcards object is

immutable (i.e., threadsafe)

instance managed (don't instantiate it yourself), instead call "of"

 You can construct a Wildcard object from either its integer representation

    Wildcard.of(0x3820e0);

 Or start with either an empty or full wildcard, and select/unselect foo.

  Wildcard w = Wildcards.NONE
                .set(Flag.DL_SRC, Flag. DL_DST, Flag.DL_VLAN_PCP)
                .setNwDstMask(8)
                .setNwSrcMask(8);

 Remember: Wildcards objects are immutable. set... operations have
 NO EFFECT on the current wildcard object. You HAVE to use the returned
 changed object.

Author:

Andreas Wundsam <andreas.wundsam@bigswitch.com>

Nested Class Summary

static class
Wildcards.Flag

          enum type for the binary flags that can be set in the wildcards field of
 an OFMatch.

Field Summary

private static com.google.common.base.Joiner
commaJoiner

static Wildcards
EXACT

private  int
flags

static Wildcards
FULL

private static int
FULL_INT

static Wildcards
INPORT_L2_MATCH

static int
INT_INPORT_L2_MATCH

private static com.google.common.base.Joiner
pipeJoiner

Constructor Summary

private
Wildcards(int flags)

          private constructor.

Method Summary

 boolean
equals(java.lang.Object obj)

 int
getInt()

          return the OpenFlow 'wire' integer representation of these wildcards

 int
getNwDstMask()

          return the nw dst mask in normal CIDR style, e.g., 8 means x.x.x.x/8
 means 8 bits wildcarded

 int
getNwSrcMask()

          return the nw src mask in normal CIDR style, e.g., 8 means x.x.x.x/8
 means 8 bits wildcarded

 java.util.EnumSet<Wildcards.Flag>
getWildcardedFlags()

          return all wildcard flags that are fully wildcarded as an EnumSet.

 int
hashCode()

 Wildcards
inverted()

          return a Wildcard object that is inverted to this wildcard object.

 boolean
isExact()

          is this a wildcard of an exact match

 boolean
isFull()

          is this a wildcard set that has all flags set + and full (/0) nw_src and
 nw_dst wildcarding ?

 boolean
isWildcarded(Wildcards.Flag flag)

 Wildcards
matchOn(Wildcards.Flag... setFlags)

          return a Wildcards object that matches on exactly the given flags

 Wildcards
matchOn(Wildcards.Flag flag)

          return a Wildcards object that matches on exactly the given flag

 Wildcards
matchOn(Wildcards.Flag flag,
        Wildcards.Flag flag2)

          return a Wildcards object that matches on exactly the given flags

static Wildcards
of(int paramFlags)

          return a wildcard object matching the given int flags.

static Wildcards
of(Wildcards.Flag... setFlags)

          convience method return a wildcard for an arbitrary number of set flags

static Wildcards
of(Wildcards.Flag setFlag)

          convience method return a wildcard for exactly one set flag

static Wildcards
of(Wildcards.Flag setFlag,
   Wildcards.Flag setFlag2)

          convience method return a wildcard for exactly two set flags

static Wildcards
ofMatches(Wildcards.Flag... setFlags)

          convience method return a wildcard for an ofmatch that amtch on an
 arbitrary number of set flags

static Wildcards
ofMatches(Wildcards.Flag setFlag)

          convience method return a wildcards for ofmatches that match on one flag

static Wildcards
ofMatches(Wildcards.Flag setFlag,
          Wildcards.Flag setFlag2)

          convience method return a wildcard for for an ofmatch that match on two
 flags

private  java.util.Iterator<java.lang.String>
prefix(java.lang.String prefix,
       java.util.Iterator<?> i)

static int
sanitizeInt(int flags)

          return the OpenFlow 'wire' integer representation of these wildcards.

 java.lang.String
toJava()

          a Java expression that constructs 'this' wildcards set

 java.lang.String
toString()

 Wildcards
wildcard(Wildcards.Flag... setFlags)

          return a Wildcards object that has the given flags wildcarded

 Wildcards
wildcard(Wildcards.Flag flag)

          return a Wildcards object that has the given flags set

 Wildcards
wildcard(Wildcards.Flag flag,
         Wildcards.Flag flag2)

          return a Wildcards object that has the given flags set

 Wildcards
withNwDstMask(int dstCidrMask)

          return a Wildcard object that has the given nwDstCidrMask set.

 Wildcards
withNwSrcMask(int srcCidrMask)

          return a Wildcard object that has the given nwSrcCidrMask set.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

FULL

public static final Wildcards FULL

FULL_INT

private static final int FULL_INT

EXACT

public static final Wildcards EXACT

INT_INPORT_L2_MATCH

public static final int INT_INPORT_L2_MATCH

See Also:
Constant Field Values

INPORT_L2_MATCH

public static final Wildcards INPORT_L2_MATCH

flags

private final int flags

pipeJoiner

private static final com.google.common.base.Joiner pipeJoiner

commaJoiner

private static final com.google.common.base.Joiner commaJoiner

Constructor Detail

Wildcards

private Wildcards(int flags)

private constructor. use Wildcard.of() instead

Method Detail

of

public static Wildcards of(int paramFlags)

return a wildcard object matching the given int flags. May reuse / cache
 frequently used wildcard instances. Don't rely on it though (use equals
 not ==).

Parameters:
flags -

Returns:

of

public static Wildcards of(Wildcards.Flag setFlag)

convience method return a wildcard for exactly one set flag

of

public static Wildcards of(Wildcards.Flag setFlag,
                           Wildcards.Flag setFlag2)

convience method return a wildcard for exactly two set flags

of

public static Wildcards of(Wildcards.Flag... setFlags)

convience method return a wildcard for an arbitrary number of set flags

ofMatches

public static Wildcards ofMatches(Wildcards.Flag setFlag)

convience method return a wildcards for ofmatches that match on one flag

ofMatches

public static Wildcards ofMatches(Wildcards.Flag setFlag,
                                  Wildcards.Flag setFlag2)

convience method return a wildcard for for an ofmatch that match on two
 flags

ofMatches

public static Wildcards ofMatches(Wildcards.Flag... setFlags)

convience method return a wildcard for an ofmatch that amtch on an
 arbitrary number of set flags

wildcard

public Wildcards wildcard(Wildcards.Flag flag)

return a Wildcards object that has the given flags set

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

wildcard

public Wildcards wildcard(Wildcards.Flag flag,
                          Wildcards.Flag flag2)

return a Wildcards object that has the given flags set

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

wildcard

public Wildcards wildcard(Wildcards.Flag... setFlags)

return a Wildcards object that has the given flags wildcarded

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

matchOn

public Wildcards matchOn(Wildcards.Flag flag)

return a Wildcards object that matches on exactly the given flag

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

matchOn

public Wildcards matchOn(Wildcards.Flag flag,
                         Wildcards.Flag flag2)

return a Wildcards object that matches on exactly the given flags

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

matchOn

public Wildcards matchOn(Wildcards.Flag... setFlags)

return a Wildcards object that matches on exactly the given flags

 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

getNwSrcMask

public int getNwSrcMask()

return the nw src mask in normal CIDR style, e.g., 8 means x.x.x.x/8
 means 8 bits wildcarded

getNwDstMask

public int getNwDstMask()

return the nw dst mask in normal CIDR style, e.g., 8 means x.x.x.x/8
 means 8 bits wildcarded

withNwSrcMask

public Wildcards withNwSrcMask(int srcCidrMask)

return a Wildcard object that has the given nwSrcCidrMask set.
 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

Parameters:
srcCidrMask - source mask to set in normal CIDR notation, i.e., 8
            means x.x.x.x/8

Returns:
a modified object

withNwDstMask

public Wildcards withNwDstMask(int dstCidrMask)

return a Wildcard object that has the given nwDstCidrMask set.
 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

Parameters:
dstCidrMask - dest mask to set in normal CIDR notation, i.e., 8 means
            x.x.x.x/8

Returns:
a modified object

inverted

public Wildcards inverted()

return a Wildcard object that is inverted to this wildcard object.
 NOTE: NOT a mutator function. 'this' wildcard object stays
 unmodified.

Returns:
a modified object

isWildcarded

public boolean isWildcarded(Wildcards.Flag flag)

getWildcardedFlags

public java.util.EnumSet<Wildcards.Flag> getWildcardedFlags()

return all wildcard flags that are fully wildcarded as an EnumSet. Do not
 modify. Note: some flags (like NW_SRC and NW_DST) that are partially
 wildcarded are not returned in this set.

Returns:
the EnumSet of wildcards

getInt

public int getInt()

return the OpenFlow 'wire' integer representation of these wildcards

sanitizeInt

public static int sanitizeInt(int flags)

return the OpenFlow 'wire' integer representation of these wildcards.
 Sanitize nw_src and nw_dst to be max. 32 (values > 32 are technically
 possible, but don't make semantic sense)

isFull

public boolean isFull()

is this a wildcard set that has all flags set + and full (/0) nw_src and
 nw_dst wildcarding ?

isExact

public boolean isExact()

is this a wildcard of an exact match

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object

equals

public boolean equals(java.lang.Object obj)

Overrides:
equals in class java.lang.Object

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

toJava

public java.lang.String toJava()

a Java expression that constructs 'this' wildcards set

prefix

private java.util.Iterator<java.lang.String> prefix(java.lang.String prefix,
                                                    java.util.Iterator<?> i)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#include "incrementVersionInSourceCodeBlock.h"

#include <QtCore/QCoreApplication>

using namespace deployment::blocks;

IncrementVersionInSourceCodeBlock::IncrementVersionInSourceCodeBlock(ShellWidget *shellWidget)
	: ShellBlock(shellWidget)
{
}

QStringList IncrementVersionInSourceCodeBlock::arguments()
{
	return {
		QCoreApplication::applicationDirPath() + "/deployment-scripts/version_increment/increment_trik_studio.sh"
		, eval<QString>("Path")
		, eval<QString>("OldVersion")
		, eval<QString>("NewVersion")
	};
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>vn.tuan.app</groupId>
  <artifactId>flash-card</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>flash-card</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
      <dependency>
          <groupId>com.intellij</groupId>
          <artifactId>forms_rt</artifactId>
          <version>7.0.3</version>
      </dependency>
      <!--<dependency>-->
          <!--<groupId>de.sciss</groupId>-->
          <!--<artifactId>weblaf</artifactId>-->
          <!--<version>1.28</version>-->
      <!--</dependency>-->
      <dependency>
          <groupId>org.devzendo</groupId>
          <artifactId>Quaqua</artifactId>
          <version>7.3.4</version>
      </dependency>

  </dependencies>

	<build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>vn.tuan.app.App</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>ideauidesigner-maven-plugin</artifactId>
                <version>1.0-beta-1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>javac2</goal>
                        </goals>
                    </execution>
                </executions>

                <configuration>
                    <fork>true</fork>
                    <debug>true</debug>
                    <failOnError>true</failOnError>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-jar-plugin</artifactId>
                  <configuration>
                      <archive>
                          <manifest>
                              <mainClass>vn.tuan.app.App</mainClass>
                          </manifest>
                      </archive>
                  </configuration>
              </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.1</version>
                <executions>
                    <execution>
                        <phase>test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>Using env.test.properties</echo>
                                <copy file="db.csv" tofile="${basedir}/target/db.csv"/>
                                <copy file="LinuxLauncher.sh" tofile="${basedir}/target/LinuxLauncher.sh"/>
                            </tasks>

                        </configuration>
                    </execution>
                </executions>
            </plugin>
          </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/test/resources</directory>
            </resource>
        </resources>
	</build>

</project>


text:
package com.theoriginalbit.peripheral;

import com.google.common.base.Preconditions;
import com.theoriginalbit.peripheral.api.peripheral.IPeripheralHolder;
import com.theoriginalbit.peripheral.api.peripheral.Peripheral;
import com.theoriginalbit.peripheral.util.Validation;
import com.theoriginalbit.peripheral.wrapper.WrapperComputer;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.IPeripheralProvider;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

import java.util.WeakHashMap;

/**
 * @author Joshua Asbury (@theoriginalbit)
 */
public final class PeripheralProvider implements IPeripheralProvider {
    private final WeakHashMap<TileEntity, WrapperComputer> PERIPHERAL_CACHE = new WeakHashMap<TileEntity, WrapperComputer>();

    /**
     * {@inheritDoc}
     */
    @Override
    public final IPeripheral getPeripheral(World world, int x, int y, int z, int side) {
        TileEntity tile = world.getTileEntity(x, y, z);

        if (tile.isInvalid()) {
            return null;
        }

        // check if there is a cached peripheral for this TileEntity
        if (PERIPHERAL_CACHE.containsKey(tile)) {
            // return the cached value
            return PERIPHERAL_CACHE.get(tile);
        }

        // the potential peripheral wrapper
        WrapperComputer wrapper = null;

        // does the TileEntity specify that it provides an external peripheral
        if (tile instanceof IPeripheralHolder) {
            // it was an IPeripheralHolder, why is there a Peripheral annotation present?
            Preconditions.checkArgument(!isLuaPeripheral(tile), "Peripherals cannot implement IPeripheralHolder and have the Peripheral annotation present");
            // get the peripheral from the IPeripheralHolder
            final Object peripheral = ((IPeripheralHolder) tile).getPeripheral();
            // make sure the provided peripheral is annotated
            Preconditions.checkArgument(isLuaPeripheral(peripheral), "The peripheral returned from the IPeripheralHolder was not annotated with Peripheral");
            // wrap the return
            if (Validation.isEnabled(peripheral.getClass())) {
                wrapper = new WrapperComputer(peripheral);
            }
        } else if (Validation.isEnabled(tile.getClass())) { // if the TileEntity is annotated as a Peripheral
            wrapper = new WrapperComputer(tile);
        }

        // if there is a wrapper then this is a valid wrapper, cache and return it
        if (wrapper != null) {
            PERIPHERAL_CACHE.put(tile, wrapper);
            return wrapper;
        }

        return null;
    }

    private boolean isLuaPeripheral(Object peripheral) {
        return peripheral.getClass().isAnnotationPresent(Peripheral.class);
    }
}


text:
id: 419
title: 'LeetCode Anagram: Hashing and Sorting'
author: sigmainfy
excerpt: 'LeetCode Anagram: Sort each string and hash each string into the hash table keyed at the sorted form so all the anagrams would be hashed into the same place.'
layout: post
guid: http://tech-wonderland.net/?p=419
views:
  - 858
categories:
  - Algorithm
  - LeetCode
tags:
  - hash
  - LeetCode
  - sort
  - String
---
## Overview

LeetCode Anagram: Sort each string and hash each string into the hash table keyed at the sorted form so all the anagrams would be hashed into the same place.

## LeetCode Anagram

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

## Solution and **Precautions**: Hashing and Sorting

First, note what is Anagrams, you can google search it and let's claim that word *A* and *B* is called anagram to each other if we can get word B(A) from A(B)  by rearranging the letters of *A(B)* to produce B(A), using all the original letters exactly once.

Then, one straightforward way is to compare each pair of words and to see if they are anagrams, my first try is just like this, starting from the first word, I search through all the remaining words and get its corresponding anagrams (to the first word), of course, all such anagrams we found for the first word won't be anagrams to any other words so we don't have to consider them for further check. This method could pass the small data set test but will get TLE for large dataset test. The time complexity is O(N^2 * K log K) where N is the number of words and K is the length of the longest word, or you may say the average length of the words.

Finally, if we think deeper into this, we will find that we actually don't have to do the N^2 comparisons at all. The key observation is that A and B is anagram to each other if and only if their sorted form are exactly the same. As a result, one linear scan through the words list is enough, for each word we can get its sorted form in K log K time, and we can use map to store the groups of words which are in the same sorted form. The time complexity is O(N K log K), this approach could pass both small data test and large data test. The following code implements this idea and can pass the LeetCode OJ for this Anagrams problem:

{% highlight java linenos %}public class Solution {
    public List<String> anagrams(String[] strs) {
        List<String> results = new ArrayList<String>();
        Map<String, List<String>> groups = new HashMap<String, List<String>>();

        for (String s : strs) {
            char [] anagram = s.toCharArray();
            Arrays.sort(anagram);
            String sortedS = new String(anagram);

            if (null != groups.get(sortedS))
                groups.get(sortedS).add(s);
            else {
                List<String> g = new ArrayList<String>();
                g.add(s);
                groups.put(sortedS, g);
            }
        }

        for (List<String> l : groups.values()) {
            if (l.length() > 1)
            results.addAll(l);
        }
        return results;
    }
}
{% endhighlight %}

A final note that the LeetCode OJ for this Anagrams problem description is really confusing, we only need to return the anagrams if we find more than one such anagrams as the following test cases indicate:

Input:  [""]
Output: [""]
Expected:   []

Input:  ["a"]
Output: ["a"]
Expected:   []

## Summary

LeetCode Anagram: Sort each string and hash each string into the hash table keyed at the sorted form so all the anagrams would be hashed into the same place.


text:
/*	all web pages with Google Charts should include the following
 *	line in the of the web page to load the Google Chart libraries.
 */
google.charts.load('current', {packages: ['corechart','scatter']});

/*	decBin function is to convert (Decimal to Binary) with specify length of the output.
 *	The function take 2 arguments ( dec, length)
 *	dec   : is the decimal number, which need to be convert to binary
 *	length: is the desirable precision
 *	The function convert positive decimal as well as negative decimal
 */
function decBin(dec,length){
	var out = "";
	while(length--)
		out += (dec >> length ) & 1;
	return out;
}

/* checkIndex function is to check if the mobile variable has not run out of range to precArr length. */
function checkIndex(){
	if(mobile < precArr.length){return true;}else{return false;}
}

/* reset function is to reset all the interactive action from user with chart.
 * set the mobile variable to zero index ( the start of precArr )
 */
function reset(){
	mobile = 0;
	xValue = null;
	yValue = null;
	clickIndex = 0;
	getRequest();
}

/* getPrecision Function is to create array of the different dimensional to chart.
 * The function has to reset mobile variable to zero, which will point to the start of precArr.
 * The function will be execute onload of the body tag and when a user changes the selected option of a <select> element.
 */
var mobile = 0;
var precArr = [];

function getPrecision(){
	precArr = [];
	mobile  = 0;
	var temp = Math.pow(2, document.getElementById("precision").value);

	while((temp / 16) >= 1){
		temp /= 16;
		precArr.push(temp-1);
	}
	console.log(precArr);
}

/* getBack function provide to the user the previous event of chart.
 * The function provide event points to the appropriate function (current )
 */

 // Those global variable get thier sign value from drawChart function, only if the user has interacted with chart ( click on (x,y) point ).
var xValue = null;
var yValue = null;

var clickedX = [];
var clickedY = [];
var clickIndex = 0;

function getBack(){
	if(mobile != 0){ mobile -= 1;}else{ mobile = 0;}

	if(clickIndex == 0 || clickIndex == 1){
		xValue= null;
		yValue=null;
		clickIndex = 0;
	}else{
		xValue=clickedX[clickIndex-1];
		yValue=clickedY[clickIndex-1];
		clickIndex -= 1;
	}
	getRequest();
}

// Global variable to save the requested arithmetic operation
var arOp;
/*	getRequest function is to create object of the selected options
 *	and call the appropriate function depending on user request.
 */
function getRequest(){
	var op = document.getElementById("operations").value;
	switch(op){
		case "addition":
			add();
			break;
		case "subtraction":
			sub();
			break;
		case "multiplication":
			mult();
			break;
		case "division":
			divi();
			break;
		default:
			alert('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n'
				+ 'Something went wrong!\n'
				+ 'Please contact the publisher and let the author know about the bug.\n'
				+ 'amr11682@hotmail.com');
			break;
	}
}

// function to create the simulation of Arithmetics operation ( addition )
function add(){//xValue, yValue){
	var prec  = parseInt(document.getElementById("precision").value);
	// range to iteration (loop)
	var range = Math.pow(2, prec);

	var height= precArr[mobile];
	var width = precArr[mobile];

	var index = 0;
	var rows  = [];

	var f1; // axis data format
	var f2; // axis data format

	var getPixel = function(x, y, height, width, dictX, dictY) {
		var correct = 0;
		var overflow = 0;

		var check = function(x,y) {
			if (x + y < range) { correct += 1; } else { overflow += 1; }
		}
	    check(x, y);
		check(x, y + height);
		check(x + width, y);
	    check(x + width, y + height);
        console.log(x,y,correct, overflow, dictX, dictY, index);
	    if (correct > 0 && overflow == 0) {
	    	// Correct data
			rows[index] = [dictX, dictY, null, null];

		} else if(overflow > 0 && correct == 0) {
			// Overflow data
			rows[index] = [dictX, null, dictY, null];

		} else {
			// Mix data
			rows[index] = [dictX, null, null, dictY];
		}
	}
	var xV;
	var yV; // "(typeof(xValue) && typeof(yValue)) == null undefined"
	if(xValue == null && yValue == null){xV=0; yV=0}else{xV = xValue; yV = yValue;}
	if(clickIndex > 0){clickedX.push(xV);clickedY.push(yV);}
	//if((param+height) == range){f2 = decBin(param+height-1, prec);} f2 = decBin(param+height, prec);
	var getFormat = function(param){f1 = decBin(param, prec); f2 = decBin(param+height, prec);}
	//var x = 0
	for(var x = xV, i = 0; i < 16; i++, x += width+1){
		getFormat(x);
		var dictX = {v:x, f:'X: '+f1+' to '+f2};
		//var y = 0
		for(var y = yV, j = 0; j < 16; j++, y += height+1){
			getFormat(y);
			var dictY = {v:y, f:'Y: '+f1+' to '+f2};
			getPixel(x, y, height, width, dictX, dictY);
			index += 1;
		}
	}
	drawChart(rows, ['Overflow', 'Mix']);
}

// function to create the simulation of Arithmetics operation ( subtraction )
function sub(){//xValue, yValue){
	var prec  = parseInt(document.getElementById("precision").value);
	// range to iteration (loop)
	var range = Math.pow(2, prec);

	var height= precArr[mobile];
	var width = precArr[mobile];

	var index = 0;
	var rows  = [];

	var f1; // axis data format
	var f2; // axis data format

	var getPixel = function(x, y, height, width, dictX, dictY) {
		var correct = 0;
		var underflow = 0;
			// correct logic
			// format is:  x index , correct , overflow
			if ((i-j) >= 0 & (i-j) < range){
				rows[index] = [dictX, dictY, null];
			// else overflow
			}else{
				rows[index] = [dictX, , dictY];
			}

		var check = function(x,y) {
			if ((x - y) >=0 && (x - y) < range) { correct += 1; } else { underflow += 1; }
		}
	    check(x, y);
		check(x, y + height);
		check(x + width, y);
	    check(x + width, y + height);
        console.log(x,y,correct, underflow, dictX, dictY, index);
	    if (correct > 0 && underflow == 0) {
	    	// Correct data
			rows[index] = [dictX, dictY, null, null];

		} else if(underflow > 0 && correct == 0) {
			// Overflow data
			rows[index] = [dictX, null, dictY, null];

		} else {
			// Mix data
			rows[index] = [dictX, null, null, dictY];
		}
	}
	var xV;
	var yV; // "(typeof(xValue) && typeof(yValue)) == null undefined"
	if(xValue == null && yValue == null){xV=0; yV=0}else{xV = xValue; yV = yValue;}
	if(clickIndex > 0){clickedX.push(xV);clickedY.push(yV);}
	//if((param+height) == range){f2 = decBin(param+height-1, prec);} f2 = decBin(param+height, prec);
	var getFormat = function(param){f1 = decBin(param, prec); f2 = decBin(param+height, prec);}
	//var x = 0
	for(var x = xV, i = 0; i < 16; i++, x += width+1){
		getFormat(x);
		var dictX = {v:x, f:'X: '+f1+' to '+f2};
		//var y = 0
		for(var y = yV, j = 0; j < 16; j++, y += height+1){
			getFormat(y);
			var dictY = {v:y, f:'Y: '+f1+' to '+f2};
			getPixel(x, y, height, width, dictX, dictY);
			index += 1;
		}
	}
	drawChart(rows, ['Underflow', 'Mix']);
}

// function to create the simulation of Arithmetics operation ( multiplication )
function mult(){//xValue, yValue){
	var prec  = parseInt(document.getElementById("precision").value);
	// range to iteration (loop)
	var range = Math.pow(2, prec);

	var height= precArr[mobile];
	var width = precArr[mobile];

	var index = 0;
	var rows  = [];

	var f1; // axis data format
	var f2; // axis data format

	var getPixel = function(x, y, height, width, dictX, dictY) {
		var correct = 0;
		var overflow = 0;

		var check = function(x,y) {
			if (x * y < range) { correct += 1; } else { overflow += 1; }
		}
	    check(x, y);
		check(x, y + height);
		check(x + width, y);
	    check(x + width, y + height);
        console.log(x,y,correct, overflow, dictX, dictY, index);
	    if (correct > 0 && overflow == 0) {
	    	// Correct data
			rows[index] = [dictX, dictY, null, null];

		} else if(overflow > 0 && correct == 0) {
			// Overflow data
			rows[index] = [dictX, null, dictY, null];

		} else {
			// Mix data
			rows[index] = [dictX, null, null, dictY];
		}
	}
	var xV;
	var yV; // "(typeof(xValue) && typeof(yValue)) == null undefined"
	if(xValue == null && yValue == null){xV=0; yV=0}else{xV = xValue; yV = yValue;}
	if(clickIndex > 0){clickedX.push(xV);clickedY.push(yV);}
	//if((param+height) == range){f2 = decBin(param+height-1, prec);} f2 = decBin(param+height, prec);
	var getFormat = function(param){f1 = decBin(param, prec); f2 = decBin(param+height, prec);}
	//var x = 0
	for(var x = xV, i = 0; i < 16; i++, x += width+1){
		getFormat(x);
		var dictX = {v:x, f:'X: '+f1+' to '+f2};
		//var y = 0
		for(var y = yV, j = 0; j < 16; j++, y += height+1){
			getFormat(y);
			var dictY = {v:y, f:'Y: '+f1+' to '+f2};
			getPixel(x, y, height, width, dictX, dictY);
			index += 1;
		}
	}
	drawChart(rows, ['Overflow', 'Mix']);
}

// function to create the simulation of Arithmetics operation ( division )
function divi(){//xValue, yValue){
	var prec  = parseInt(document.getElementById("precision").value);
	// range to iteration (loop)
	var range = Math.pow(2, prec);

	var height= precArr[mobile];
	var width = precArr[mobile];

	var index = 0;
	var rows  = [];

	var f1; // axis data format
	var f2; // axis data format

	var getPixel = function(x, y, height, width, dictX, dictY) {
		var correct = 0;
		var infi    = 0;
		var Inexpressible = 0;

		var check = function(x,y) {
			if ((x/y) % 1 == 0) { correct += 1; }else if(isNaN(x/y) || !(isFinite(x/y))) { infi += 1;}else{ Inexpressible += 1; }
		}
	    check(x, y);
		check(x, y + height);
		check(x + width, y);
	    check(x + width, y + height);
        console.log(x,y,correct, Inexpressible, infi, dictX, dictY, index);
	    if (correct > 0 && Inexpressible == 0 && infi == 0) {
	    	// Correct data: does (1/3) which is 0.33.. mod 1  equal to zero
			rows[index] = [dictX, dictY, null, null, null];

		} else if(Inexpressible > 0 && correct == 0 && infi == 0) {
			// Inexpressible data
			rows[index] = [dictX, null, dictY, null, null];

		}else if(infi > 0 && correct == 0 && Inexpressible == 0) {
			// check if is NAN eg. 0/0  or is Infinity(not finite)  eg. 1/0 , 1000/0
			rows[index] = [dictX, null, null, dictY, null];

		} else {
			// Mix data
			rows[index] = [dictX, null, null, null, dictY];
		}
	}
	var xV;
	var yV; // "(typeof(xValue) && typeof(yValue)) == null undefined"
	if(xValue == null && yValue == null){xV=0; yV=0}else{xV = xValue; yV = yValue;}
	if(clickIndex > 0){clickedX.push(xV);clickedY.push(yV);}
	//if((param+height) == range){f2 = decBin(param+height-1, prec);} f2 = decBin(param+height, prec);
	var getFormat = function(param){f1 = decBin(param, prec); f2 = decBin(param+height, prec);}
	//var x = 0
	for(var x = xV, i = 0; i < 16; i++, x += width+1){
		getFormat(x);
		var dictX = {v:x, f:'X: '+f1+' to '+f2};
		//var y = 0
		for(var y = yV, j = 0; j < 16; j++, y += height+1){
			getFormat(y);
			var dictY = {v:y, f:'Y: '+f1+' to '+f2};
			getPixel(x, y, height, width, dictX, dictY);
			index += 1;
		}
	}
	drawChart(rows, ['Inexpressible', 'infinity','Mix']);
}

// Declare global variable
var globalChart;
var globalData;
var globalOptions;

function drawChart(obj, arg) {
	// Define the chart to be drawn.
	var data = new google.visualization.DataTable();
	data.addColumn('number', '');
	data.addColumn('number', 'correct');
	if (arg.length == 3){
		// numbers do not divide evenly  (Inexpressible)
		data.addColumn('number', arg[0]);
		// divide by zero
		data.addColumn('number', arg[1]);
		// Mixed
		data.addColumn('number', arg[2]);
	} else{
		data.addColumn('number', arg[0]);
		data.addColumn('number', arg[1]);
	}

   	data.addRows(obj);
    var options = {
    	chart: {
    		title: ' Plotting the simulation of floating point with Basic Arithmetics',
        	//subtitle: 'Based on precision 4 bits'
     	},
     	width: 1150,
     	height: 500,
     	explorer: {
     		actions: ['dragToZoom', 'rightClickToReset'],
        	axis: 'horizontal',
        	keepInBounds: true,
        	maxZoomIn: 4.0
    	},
    };
    var chart = new google.charts.Scatter(document.getElementById('chart_div1'));

    // Sign the gloabl variable to chart
    globalChart = chart;
    globalData  = data;
    globalOptions = options;

    chart.draw(data, google.charts.Scatter.convertOptions(options));

	// Listen for the 'select' event, and call my function selectHandler() when
	// the user selects something on the chart.

    google.visualization.events.addListener(chart, 'select', selectHandler);

    // This function to get the index of the selected element of chart.
	function selectHandler() {
		mobile += 1;
		var selectedItemRow = chart.getSelection()[0].row;
		var selectedItemCol = chart.getSelection()[0].column;
		if (selectedItemRow != null){
			//alert(data.getValue(selectedItemRow, 0));
			xValue = data.getValue(selectedItemRow, 0);
			yValue = data.getValue(selectedItemRow, selectedItemCol);
			var valid  = checkIndex();

			if(valid){
				clickIndex += 1;
				//clickedX.push(xValue);
				//clickedY.push(yValue);
				getRequest();//xValue, yValue);
			}
		}
	};
}

			//alert("Index: "+selectedItemRow);
			//alert("groupNr: "+selectedItemCol);
			//alert("x-axis Value: "+data.getValue(selectedItemRow, 0));
			//alert("y-axis Value: "+data.getValue(selectedItemRow, selectedItemCol));
			//alert(typeof(data.getValue(selectedItemRow, 0)));

		/*
		Oleks logic !
		check(x, y);
		check(x, y + width);
		check(x + height, y);
	    check(x + height, y + width); */

/*
			var value = chart.getValue(selectedItem.row, 0);//, selectedItem.column);
			alert('The user selected ' + value);
*/
			//document.getElementById("test1").innerHTML = glo;

/*
var currentlyPrec;
var currentlyOp;
function getBack(){
	getRequest(currentlyPrec, currentlyOp)
}
procParam, opParam
	if((typeof(procParam) && typeof(opParam)) == "undefined"){
		op   = document.getElementById("operations").value;

	}
*/

/*
function selectHandler(e) {
  alert('A table row was selected ');//+ chart.getSelection().rows);
}
*/
/*
$('circle').each(function(index,elem){

   alert("cx :"+elem.getAttribute("cx")+"...cy :"+elem.getAttribute("cy")); //using JavaScript

}
*/
/*
// Resize function to diffrent midea
$(window).resize(function(){
  	drawChart();
});

*/

/*
var mobile = 0;
var halfArr = [4095, 255, 15];

function testAmr(obj){
	var prec  = parseInt(obj);
	// range to iteration (loop)
	var range = Math.pow(2, prec);
	var index = 0;
	var rows  = [];
	for(x = 0; x < range; x += 4095){

	}
	for (i = 0; i < range; i += 4095 ){ //halfArr[mobile]
		// initialize dictX
		dictX = {};

		if(i == 0){
			var formatX = decBin(0, prec);
			// {v:0, f:'0000'}
			var dictX	= {v:0, f: formatX};
		}else{
			var formatX = decBin(i, prec);
			var dictX	= {v:i+1, f: formatX};
		}

		for(j=0; j < range; j += 4095 ){ //halfArr[mobile]
			// initialize dictY
			var dictY = {};

			if(j == 0){
				var formatY = decBin(0, prec);
			// {v:0, f:'0000'}
				var dictY = {v:0, f: formatY};
			}else{
				var formatY = decBin(j, prec);
				var dictY = {v:j+1, f: formatY};
			}

			// correct logic
			// format is:  x index , correct , overflow
			if ((i+j) < range){
				rows[index] = [dictX, dictY, null];
			// else overflow
			}else{
				rows[index] = [dictX, , dictY];
			}
			index += 1;
			//j += 1;
		}
		//i += 1;
	}
	alert("Index is :"+index);
	drawChart(rows, ['Overflow']);
}
*/

/*============================ Test START HERE =========================*/
/*============================ Test END HERE =========================*/

// function to create the simulation of Arithmetics operation ( addition )
/*
function add(obj){
	var prec  = parseInt(obj);
	// range to iteration (loop)
	var range = Math.pow(2, prec);
	var index = 0;
	var rows  = [];
	for (i = 0; i < range; i++){
		var formatX = decBin(i, prec);
		// initialize dictX
		dictX = {};
		// {v:0, f:'0000'}
		var dictX	= {v:i, f: formatX};
		for(j=0; j < range; j++){
			var formatY = decBin(j, prec);
			// initialize dictY
			dictY = {};
			// {v:0, f:'0000'}
			var dictY = {v:j, f: formatY};
			// correct logic
			// format is:  x index , correct , overflow
			if ((i+j) < range){
				rows[index] = [dictX, dictY, null];
			// else overflow
			}else{
				rows[index] = [dictX, , dictY];
			}
			index += 1;
		}
	}

	drawChart(rows, ['Overflow']);
}

// function to create the simulation of Arithmetics operation ( subtraction )
function subt_old(obj){
	var prec  = parseInt(obj);
	// range to iteration (loop)
	var range = Math.pow(2, prec);
	var index = 0;
	var rows  = [];
	for (i = 0; i < range; i++){
		var formatX = decBin(i, prec);
		// initialize dictX
		dictX = {};
		// {v:0, f:'0000'}
		var dictX	= {v:i, f: formatX};
		for(j=0; j < range; j++){
			var formatY = decBin(j, prec);
			// initialize dictY
			var dictY = {};
			// {v:0, f:'0000'}
			var dictY = {v:j, f: formatY};
			// correct logic
			// format is:  x index , correct , overflow
			if ((i-j) >= 0 & (i-j) < range){
				rows[index] = [dictX, dictY, null];
			// else overflow
			}else{
				rows[index] = [dictX, , dictY];
			}
			index += 1;
		}
	}

	drawChart(rows, ['Underflow']);
}

// function to create the simulation of Arithmetics operation ( multiplication )
function mult_old(obj){
	var prec  = parseInt(obj);
	// range to iteration (loop)
	var range = Math.pow(2, prec);
	var index = 0;
	var rows  = [];
	for (i = 0; i < range; i++){
		var formatX = decBin(i, prec);
		// initialize dictX
		dictX = {};
		// {v:0, f:'0000'}
		var dictX	= {v:i, f: formatX};
		for(j=0; j < range; j++){
			var formatY = decBin(j, prec);
			// initialize dictY
			var dictY = {};
			// {v:0, f:'0000'}
			var dictY = {v:j, f: formatY};
			// correct logic
			// format is:  x index , correct , overflow
			if ((i*j) < range){
				rows[index] = [dictX, dictY, null];
			// else overflow
			}else{
				rows[index] = [dictX, , dictY];
			}
			index += 1;
		}
	}

	drawChart(rows, ['Overflow']);
}

// function to create the simulation of Arithmetics operation ( division )
function divi_old(obj){
	var prec  = parseInt(obj);
	// range to iteration (loop)
	var range = Math.pow(2, prec);
	var index = 0;
	var rows  = [];
	for (i = 0; i < range; i++){
		var formatX = decBin(i, prec);
		// initialize dictX
		dictX = {};
		// {v:0, f:'0000'}
		var dictX	= {v:i, f: formatX};
		for(j= 0; j < range; j++){
			var formatY = decBin(j, prec);
			// initialize dictY
			var dictY = {};
			// {v:0, f:'0000'}
			var dictY = {v:j, f: formatY};
			// correct logic
			if((i/j) % 1 == 0 ){ // does (1/3) which is 0.33.. mod 1  equal to zero
				rows[index] = [dictX, dictY, null, null];
			// check if is NAN eg. 0/0  or is Infinity(not finite)  eg. 1/0 , 1000/0
			}else if(isNaN(i/j) || !(isFinite(i/j))){
				rows[index] = [dictX, null, null, dictY];
			// else Inexpressible
			}else{
				rows[index] = [dictX, , dictY, null];
			}
			index += 1;
		}
	}
	drawChart(rows, ['Inexpressible', 'Infinity']);
}

*/


text:
.btn-group, .btn-group-vertical { position: relative; display: inline-block; vertical-align: middle; }
.btn-group > .btn, .btn-group-vertical > .btn { position: relative; float: left; margin-bottom: 0; }
.btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn:focus, .btn-group-vertical > .btn:active, .btn-group-vertical > .btn.active { z-index: 2; }
.btn-group > .btn:hover, .btn-group-vertical > .btn:hover { z-index: 2; }

.btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group { margin-left: -1px; }

.btn-toolbar { margin-left: -.5rem; }
.btn-toolbar::after { content: ""; display: table; clear: both; }
.btn-toolbar .btn-group, .btn-toolbar .input-group { float: left; }
.btn-toolbar > .btn, .btn-toolbar > .btn-group, .btn-toolbar > .input-group { margin-left: .5rem; }

.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; }

.btn-group > .btn:first-child { margin-left: 0; }
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-bottom-right-radius: 0; border-top-right-radius: 0; }

.btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; }

.btn-group > .btn-group { float: left; }

.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; }

.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-top-right-radius: 0; }

.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { border-bottom-left-radius: 0; border-top-left-radius: 0; }

.btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; }

.btn-group-sm .btn { padding: .25rem 1rem; font-size: .875rem; border-radius: .2rem; line-height: 1; }

.btn-group-lg .btn { padding: 1.5rem 2rem; font-size: 1.25rem; border-radius: .3rem; line-height: .3rem; }

.btn + .dropdown-toggle-split { padding-right: 0.75rem; padding-left: 0.75rem; }
.btn + .dropdown-toggle-split::after { margin-left: 0; }

.btn-sm + .dropdown-toggle-split { padding-right: 0.75rem-sm; padding-left: 0.75rem-sm; }

.btn-lg + .dropdown-toggle-split { padding-right: 0.75rem-lg; padding-left: 0.75rem-lg; }

.btn-group.open .dropdown-toggle.btn-link { box-shadow: none !important; }

.btn .caret { margin-left: 0; }

.btn-lg .caret { border-width: 0.3em 0.3em 0; border-bottom-width: 0; }

.dropup .btn-lg .caret { border-width: 0 0.3em 0.3em; }

.btn-group-vertical > .btn, .btn-group-vertical > .btn-group, .btn-group-vertical > .btn-group > .btn { display: block; float: none; width: 100%; max-width: 100%; }
.btn-group-vertical > .btn-group::after { content: ""; display: table; clear: both; }
.btn-group-vertical > .btn-group > .btn { float: none; }
.btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; }

.btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; }
.btn-group-vertical > .btn:first-child:not(:last-child) { border-bottom-right-radius: 0; border-bottom-left-radius: 0; }
.btn-group-vertical > .btn:last-child:not(:first-child) { border-top-right-radius: 0; border-top-left-radius: 0; }

.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; }

.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; }

.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-right-radius: 0; border-top-left-radius: 0; }

[data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; }


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="theme-color" content="#5d4037" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>The Harlem Hotel</title>

<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="favicon-128.png" sizes="128x128" />
<meta name="application-name" content=" "/>
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="mstile-310x310.png" />

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

Gallery

Culture

Book a Suite

Gallery

Culture

Book a Suite

      menu

      mode_edit

insert_chart

format_quote

publish

attach_file

    <form class="col s12">

account_circle
          <input placeholder="E.g. Ryan" id="first_name" type="text" class="validate">
          First Name

          <input placeholder="E.g. Wernlund" id="last_name" type="text" class="validate">
          Last Name

lock
          <input id="password" type="password" class="validate">
          SSN

email
          <input id="email" type="email" class="validate">
          Email

          phone
          <input id="icon_telephone" type="tel" class="validate">
          Telephone

          mode_edit
          <textarea id="icon_prefix2" class="materialize-textarea"></textarea>
          Special Requests

Start Date
<input type="date" class="datepicker">

End Date
<input type="date" class="datepicker">

    </form>

<form action="#">

Room Size

      <input name="group1" type="radio" id="test1" />
      Parsimonious

      <input name="group1" type="radio" id="test2" />
      Normal

      <input name="group1" type="radio" id="test3" />
      Exorbitant

</form>

<form action="#">

Optional Add-Ons

      <input type="checkbox" id="test5" />
      Room Service

      <input type="checkbox" id="test6" />
      A/C

      <input type="checkbox" id="test7" />
      Dignity

</form>

 <button class="btn waves-effect waves-light brown" type="submit" name="action" onclick="submitPressed()">Submit
    send
  </button>

Contact Us

 You can contact us with any questions/inquires at: theharlemhotel@harlem.renaissance

Why a Website?

Although it is unlikely that the African-Americans could afford access to the internet during the 1920s even if it was invented then, a website more accuratly depicts the real-estate buisness we envisioned, and provides a digital platform for the buisness's design in a way that isn't possible on a brochure. Plus - you have to admit - this website is freaking awesome!

      Coded by Ronak Parikh.


text:
using System.Collections;
using NUnit.Framework;

namespace Atata.Tests
{
    public class UIComponentContentTests : UITestFixture
    {
        private static IEnumerable ComplexTextTestCaseSource =>
            new[]
            {
                new TestCaseData(ContentSource.Text).Returns("The quick brown fox jumps over the lazy dog."),
                new TestCaseData(ContentSource.TextContent).Returns("The quick brown fox jumps over the lazy dog."),
                new TestCaseData(ContentSource.InnerHtml).Returns("The quick brown fox jumps over the lazy dog."),
                new TestCaseData(ContentSource.ChildTextNodes).Returns("The quick  fox  the lazy dog."),
                new TestCaseData(ContentSource.ChildTextNodesTrimmed).Returns("The quickfoxthe lazy dog."),
                new TestCaseData(ContentSource.ChildTextNodesTrimmedAndSpaceJoined).Returns("The quick fox the lazy dog."),
                new TestCaseData(ContentSource.FirstChildTextNode).Returns("The quick"),
                new TestCaseData(ContentSource.LastChildTextNode).Returns("the lazy dog.")
            };

        [Test]
        public void Content()
        {
            Go.To<ContentPage>().
                VisibleDiv.Should.Equal("Some text").
                VisibleDiv.Content.Should.Equal("Some text");
        }

        [Test]
        public void Content_Invisible()
        {
            Go.To<ContentPage>().
                HiddenDiv.Should.Not.BeVisible().
                HiddenDiv.Should.BeEmpty().
                HiddenDiv.Content.Should.BeEmpty().
                HiddenDivUsingTextContent.Should.Equal("Some text").
                HiddenDivUsingTextContent.Content.Should.Equal("Some text").
                HiddenDivUsingInnerHtml.Should.Equal("Some text").
                HiddenDivUsingInnerHtml.Content.Should.Equal("Some text");
        }

        [TestCaseSource(nameof(ComplexTextTestCaseSource))]
        public string Content_UsingGetsContentFromSourceAttribute(ContentSource contentSource)
        {
            return Go.To<ContentPage>().
                GetComplexText(contentSource).Value;
        }

        [TestCaseSource(nameof(ComplexTextTestCaseSource))]
        public string GetContent(ContentSource contentSource)
        {
            return Go.To<ContentPage>().
                ComplexTextControl.GetContent(contentSource);
        }
    }
}


text:
npm run mergecoverage
npm run reportcoverage