package moe.tristan.easyfxml.model.components.listview;

import moe.tristan.easyfxml.api.FxmlController;
import moe.tristan.easyfxml.api.FxmlFile;
import moe.tristan.easyfxml.api.FxmlNode;
import moe.tristan.easyfxml.model.components.listview.cell.ComponentCellFxmlSampleController;
import moe.tristan.easyfxml.model.components.listview.view.ComponentListViewSampleFxmlController;

public enum CustomListViewTestComponents implements FxmlNode {
    VIEW("view/ComponentListViewSample.fxml", ComponentListViewSampleFxmlController.class),
    CELL("cell/ComponentCell.fxml", ComponentCellFxmlSampleController.class);

    private final String relFileName;
    private final Class<? extends FxmlController> controllerClass;

    CustomListViewTestComponents(String relFileName, Class<? extends FxmlController> controllerClass) {
        this.relFileName = relFileName;
        this.controllerClass = controllerClass;
    }

    @Override
    public FxmlFile getFile() {
        return () -> "moe/tristan/easyfxml/model/components/listview/" + relFileName;
    }

    @Override
    public Class<? extends FxmlController> getControllerClass() {
        return controllerClass;
    }
}

Use a FxmlNode-implementing enum for ComponentListView testing


package javaEndOfFile;

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int iterationNumber = 1;
        while(scanner.hasNext()) {
        	String line = scanner.nextLine();
        	System.out.println((iterationNumber++) + " " + line);
        }
        scanner.close();
    }
}

Add solution for problem Java End-of-file, HackerRank/Java/Introduction/Java End-of-file


package net.floodlightcontroller.acamp.msgele;

import net.floodlightcontroller.packet.BasePacket;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.PacketParsingException;

public class APBoardData extends BasePacket implements IPacket {

	private String boardDiscription;
	@Override
	public byte[] serialize() {
		byte[] boardDataBytes = null;
		if(boardDiscription != null) {
			boardDataBytes = boardDiscription.getBytes();
		}
		return boardDataBytes;
	}

	@Override
	public IPacket deserialize(byte[] data, int offset, int length)
			throws PacketParsingException {
		if(data.length != 0) {
			this.boardDiscription = new String(data);
		}
		return this;
	}

	public String getBoardDiscription() {
		return boardDiscription;
	}

	public void setBoardDiscription(String boardDiscription) {
		this.boardDiscription = boardDiscription;
	}

}

Complete ALL message element specification, wait for a test!


package org.verapdf.metadata.fixer.utils;

import org.verapdf.metadata.fixer.entity.Metadata;
import org.verapdf.metadata.fixer.entity.PDFDocument;
import org.verapdf.metadata.fixer.utils.parser.ProcessedObjectsParser;
import org.verapdf.validation.profile.model.ValidationProfile;
import org.verapdf.validation.report.model.Result;

/**
 * @author Evgeniy Muravitskiy
 */
public interface FixerConfig {

	Result getValidationResult();

	ValidationProfile getValidationProfile();

	Metadata getMetadata();

	PDFDocument getDocument();

	ProcessedObjectsParser getParser();
}

Add config object for metadata fixer


package net.buycraft.plugin.sponge.util;

import com.google.common.collect.ImmutableList;
import lombok.Getter;
import net.buycraft.plugin.util.CommandOutput;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.source.ConsoleSource;
import org.spongepowered.api.service.context.Context;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.service.permission.SubjectData;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.util.Tristate;

import java.util.List;
import java.util.Optional;
import java.util.Set;

public class LoggingCommandSource implements ConsoleSource {
    @Getter
    private final CommandOutput output = new CommandOutput();

    @Override
    public String getName() {
        return "CONSOLE^BC";
    }

    @Override
    public String getIdentifier() {
        return Sponge.getServer().getConsole().getIdentifier();
    }

    @Override
    public Set<Context> getActiveContexts() {
        return Sponge.getServer().getConsole().getActiveContexts();
    }

    @Override
    public void sendMessage(Text text) {
        output.addLine(text.toPlain());
    }

    @Override
    public MessageChannel getMessageChannel() {
        return MessageChannel.fixed(this);
    }

    @Override
    public void setMessageChannel(MessageChannel messageChannel) {

    }

    @Override
    public Optional<CommandSource> getCommandSource() {
        return Optional.of(this);
    }

    @Override
    public SubjectCollection getContainingCollection() {
        return Sponge.getServer().getConsole().getContainingCollection();
    }

    @Override
    public SubjectData getSubjectData() {
        return Sponge.getServer().getConsole().getSubjectData();
    }

    @Override
    public SubjectData getTransientSubjectData() {
        return Sponge.getServer().getConsole().getTransientSubjectData();
    }

    @Override
    public boolean hasPermission(Set<Context> set, String s) {
        return true;
    }

    @Override
    public Tristate getPermissionValue(Set<Context> set, String s) {
        return Tristate.TRUE;
    }

    @Override
    public boolean isChildOf(Set<Context> set, Subject subject) {
        return true;
    }

    @Override
    public List<Subject> getParents(Set<Context> set) {
        return ImmutableList.of();
    }
}

Add command sender logging support for Sponge


/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document.util;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.junit.Test;

public class UTF8EncoderTest {

    private static char[] SURROGATE_PAIR = Character.toChars(0x1f4a9);

    @Test
    public void encodeValid() throws IOException {

        // a a-umlaut euro plane-1-char
        String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR);

        byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8);
        byte[] withUtilsClass = UTF8Encoder.encodeAsByteArray(test);
        assertArrayEquals(withStringClass, withUtilsClass);
        assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8));
    }

    @Test
    public void encodeInValid() {

        // a a-umlaut euro plane-1-char, second char in surrogate pair missing
        String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0];

        try {
            UTF8Encoder.encodeAsByteArray(test);
            fail("expected encoding to fail");
        } catch (IOException expected) {
            // expected
        }
    }

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

        for (int i = 0; i < tc; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // encode and decode 100 random UUID strings
                    for (int j = 0; j < 100; j++) {
                        String test = UUID.randomUUID().toString();
                        String roundtripped = null;
                        try {
                            byte[] bytes = UTF8Encoder.encodeAsByteArray(test);
                            roundtripped = new String(bytes, StandardCharsets.UTF_8);
                        } catch (IOException exignored) {
                        }
                        assertEquals(test, roundtripped);
                    }

                }
            });
        }
        for (int i = 0; i < tc; i++) {
            threads[i].start();
        }
        for (int i = 0; i < tc; i++) {
            threads[i].join();
        }
    }
}

Create charset encoding utility that detects malformed input


package org.biojava.nbio.structure.symmetry.core;

/**
 * Method used for symmetry perception in the {@link QuatSymmetryDetector}.
 *
 * @author Aleix Lafita
 * @since 5.0.0
 *
 */
public enum SymmetryPerceptionMethod {
	NO_ROTATION,
	C2_ROTATION,
	ROTATION,
	ROTO_TRANSLATION;
}

Create an ENUM for the symmetry perception methods


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

package org.scijava.notebook.converter;

import org.scijava.Priority;
import org.scijava.convert.Converter;
import org.scijava.notebook.converter.output.HTMLNotebookOutput;
import org.scijava.plugin.Plugin;

@Plugin(type = Converter.class, priority = Priority.LOW_PRIORITY)
public class NumberToHTMLNotebookConverter
        extends NotebookOutputConverter<Number, HTMLNotebookOutput> {

    @Override
    public Class<Number> getInputType() {
        return Number.class;
    }

    @Override
    public Class<HTMLNotebookOutput> getOutputType() {
        return HTMLNotebookOutput.class;
    }

    @Override
    public HTMLNotebookOutput convert(Object object) {
        return new HTMLNotebookOutput(object.toString());
    }

}

Add number to HTML converter


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

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.impl.root.component.BaseComponentDefImpl;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class BaseComponentDefImplTest extends AuraImplTestCase{

    @Test
    public void testHasFacetLocalDependenciesWhenServerDependedCmpOnFacet() throws Exception {
        // Arrange
        String cmpWithServerProvider =
                "<aura:component abstract='true' extensible='true' provider='java://org.auraframework.impl.java.provider.TestProviderAbstractBasic'>\n" +
                "</aura:component>";
        DefDescriptor<ComponentDef> facetCmp = addSourceAutoCleanup(ComponentDef.class, cmpWithServerProvider);

        String cmpMarkup = String.format("<aura:component> <%s/> </aura:component>", facetCmp.getDescriptorName());
        DefDescriptor<ComponentDef> desc = addSourceAutoCleanup(ComponentDef.class, cmpMarkup);

        // Act
        BaseComponentDefImpl<ComponentDef> def = (BaseComponentDefImpl<ComponentDef>) definitionService.getDefinition(desc);
        boolean actual = def.hasFacetLocalDependencies();

        // Assert
        assertTrue(actual);
    }

}

Add a test for local dependencies


package com.jwetherell.algorithms.strings.test;

import com.jwetherell.algorithms.strings.StringInformations;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;

public class StringInformationTest {

    @Test
    public void getPrefixSuffixes() throws Exception {
        List<Object[]> data = Arrays.asList(new Object[][]{
                {"", new ArrayList<Integer>()},
                {"a", Arrays.asList(0)},
                {"aaa", Arrays.asList(0, 1, 2)},
                {"abbabb", Arrays.asList(0, 0, 0, 1, 2, 3)},
                {"bbabbbbaab", Arrays.asList(0, 1, 0, 1, 2, 2, 2, 3, 0, 1)},
                {
                    "( ͡° ͜ʖ ͡° )( ͡° a( ͡° ͜ʖ ͡°",
                     Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
                }
        });
        for(Object[] testCase: data) {
            String input = (String) testCase[0];
            List<Integer> expected = (List<Integer>) testCase[1];
            assertEquals(expected, StringInformations.getPrefSufTable(input));
        }
    }

}

Test for finding prefix-suffix table


import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
	  // When array size is less than 3, returns an error.
	  if (input.length % 3 != 0 ) {
			System.out.println("Error! Array cannot be divided into three equal parts");
			return;
		}
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

Update to handle an edge case


package com.xtremelabs.robolectric.shadows;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;

import android.media.AudioManager;

@RunWith(WithTestDefaultsRunner.class)
public class AudioManagerTest {

	private AudioManager audioManager;
	private ShadowAudioManager shadowAudioManager;

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();

        audioManager = Robolectric.newInstanceOf( AudioManager.class );
        shadowAudioManager = Robolectric.shadowOf( audioManager );
	}

	@After
	public void tearDown() throws Exception {
	}

    @Test
    public void shouldGetStreamMaxVolume() throws Exception {
    	shadowAudioManager.setStreamMaxVolume( 45 );

    	assertEquals( 45, audioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC ));
    }

    @Test
    public void shouldGetVolume() throws Exception {
    	shadowAudioManager.setStreamVolume( 5 );

    	assertEquals( 5, audioManager.getStreamVolume( AudioManager.STREAM_MUSIC ));
    }

    @Test
    public void shouldSetVolume() throws Exception {
    	audioManager.setStreamVolume( AudioManager.STREAM_MUSIC, 8, 0 );

    	assertEquals( 8, audioManager.getStreamVolume( AudioManager.STREAM_MUSIC ));
    	assertEquals( 8, shadowAudioManager.getStreamVolume() );
    }

}

Remove streamType field for ShadowAudioManager, as it is not used. Add test case.


package org.tinyj.lava;

/**
 * A supplier of `boolean` values. This is the exception declaring version of
 * Java's [`BooleanSupplier`](https://docs.oracle.com/javase/8/docs/api/java/util/function/BooleanSupplier.html)
 *
 * There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * This is a functional interface whose functional method is `checkedGetAsBoolean()`.
 *
 * @param <E> upper limit of thrown exception types
 */
@FunctionalInterface
public interface LavaBooleanSupplier<E extends Exception> {

  /**
   * Produce a value.
   *
   * @return a value
   */
  boolean checkedGetAsBoolean() throws E;

  /**
   * Safely casts between different (#LavaSupplier) parametrization
   *
   * @param <E> required exception limit
   * @param supplier supplier to adopt
   * @return `supplier` casted to the compatible parametrization (#LavaSupplier)`<R, E>`
   */
  @SuppressWarnings("unchecked")
  static <E extends Exception>
  LavaBooleanSupplier<E> castDown(LavaBooleanSupplier<? extends E> supplier) {
    return (LavaBooleanSupplier<E>) supplier;
  }
}

Add lava version of `BooleanSupplier`


package forager.server;

import java.util.HashMap;
import java.util.Map;

public class EventMap {

    protected static final Map<Integer, Class<?>> intToClass = new HashMap<>();
    protected static final Map<Class<?>, Integer> classToInt = new HashMap<>();

    public EventMap() { }

    protected static void addMapping(int id, Class<?> clazz) {
        intToClass.put(id, clazz);
        classToInt.put(clazz, id);
    }

    public static Class<?> getClass(int id) {
        return intToClass.get(id);
    }

    public static int getInt(Class<?> clazz) {
        return classToInt.get(clazz);
    }
}

Add event map base class


package tachyon.worker.block.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.io.Closer;

import tachyon.Constants;
import tachyon.util.CommonUtils;
import tachyon.worker.block.meta.BlockMeta;

/**
 * This class provides write access to a block data file locally stored in managed storage.
 * <p>
 * This class does not provide thread-safety. Corresponding lock must be acquired.
 */
public class LocalFileBlockWriter implements BlockWriter {
  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
  private final BlockMeta mBlockMeta;
  private final String mFilePath;
  private final RandomAccessFile mLocalFile;
  private final FileChannel mLocalFileChannel;
  private final Closer mCloser = Closer.create();

  public LocalFileBlockWriter(BlockMeta blockMeta) throws IOException {
    mBlockMeta = Preconditions.checkNotNull(blockMeta);
    mFilePath = mBlockMeta.getPath();
    mLocalFile = mCloser.register(new RandomAccessFile(mFilePath, "w"));
    mLocalFileChannel = mCloser.register(mLocalFile.getChannel());
  }

  @Override
  public WritableByteChannel getChannel() {
    return mLocalFileChannel;
  }

  @Override
  public long append(ByteBuffer inputBuf) throws IOException {
    return write(mLocalFileChannel.size(), inputBuf);
  }

  /**
   * Writes data to the block from an input ByteBuffer.
   *
   * @param offset starting offset of the block file to write
   * @param inputBuf ByteBuffer that input data is stored in
   * @return the size of data that was written
   * @throws IOException
   */
  private long write(long offset, ByteBuffer inputBuf) throws IOException {
    int inputBufLength = inputBuf.limit();
    ByteBuffer outputBuf =
        mLocalFileChannel.map(FileChannel.MapMode.READ_WRITE, offset, inputBufLength);
    outputBuf.put(inputBuf);
    CommonUtils.cleanDirectBuffer(outputBuf);
    return outputBuf.limit();
  }

  @Override
  public boolean delete() {
    return new File(mFilePath).delete();
  }

  @Override
  public boolean move(String dstPath) {
    // Check if destPath equals the current path, in this case, do nothing.
    if (mFilePath.equals(dstPath)) {
      return true;
    }
    return new File(mFilePath).renameTo(new File(dstPath));
  }
}

Add a implementation of BlockWriter based on local file


package com.pspdfkit.vangogh.api;

import io.reactivex.Completable;

/**
 * Class containing convenient animation scheduling methods.
 */
public final class AnimationSchedulers {

    public static Completable together(Completable... animations) {
        return Completable.mergeArray(animations);
    }

    public static Completable sequentially(Completable... animations) {
        return Completable.concatArray(animations);
    }

}

Add simple animation scheduling methods


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

package com.ibm.mobilefirstplatform.clientsdk.android.analytics.api.internal;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

/**
 * Implements the android life cycle callbacks to be registered with the application.
 *
 * Implemented as a singleton so that application callbacks can only be registered once.
 */
public class MFPAnalyticsActivityLifecycleListener implements Application.ActivityLifecycleCallbacks{
    private static MFPAnalyticsActivityLifecycleListener instance;

    public static void init(Application app) {
        if (instance == null) {
            instance = new MFPAnalyticsActivityLifecycleListener();
            app.registerActivityLifecycleCallbacks(instance);
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
        //WLLifecycleHelper.getInstance().onPause();
    }

    @Override
    public void onActivityPaused(Activity activity) {
        //WLLifecycleHelper.getInstance().onResume();
    }

    // we do not currently instrument any other lifecycle callbacks
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

    @Override
    public void onActivityStarted(Activity activity) {}

    @Override
    public void onActivityStopped(Activity activity) {}

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

    @Override
    public void onActivityDestroyed(Activity activity) {}
}

Add activity lifecycle listener that will be used with ActivityManager.


package org.nuxeo.ecm.platform.content.template.tests;

import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;

/**
*   Simple test class for ContentCreationListener
* @ JULIEN THIMONIER < jt@nuxeo.com >
**/
public class ContentCreationListenerTest extends RepositoryOSGITestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        deployBundle("org.nuxeo.ecm.platform.content.template");
        deployBundle("org.nuxeo.ecm.relations");
        openRepository();
    }

    public void testContentCreationListener() throws Exception {
        DocumentModel root = getCoreSession().getRootDocument();
        DocumentModel model = getCoreSession().createDocumentModel(
                root.getPathAsString(), "mondomaine", "Domain");
        DocumentModel doc = getCoreSession().createDocument(model);
        getCoreSession().saveDocument(doc);
        assert (doc != null);

        DocumentModelList modelList = getCoreSession().getChildren(doc.getRef());

        // Check that 3 elements have been created on the new domain
        // (Section,Workspace and Templates)
        // This should be done by ContentCreationListener
        assert (modelList.size() == 3);
    }
}

Add a new test case for ContentCreationListener


/*
 * #%L
 * SciJava mathematical expression parser.
 * %%
 * Copyright (C) 2015 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package org.scijava.sjep;

/**
 * A mutable parse position. Similar to {@link java.text.ParsePosition}, but
 * less complex.
 *
 * @author Curtis Rueden
 */
public class Position {

	private int index;

	public int get() {
		return index;
	}

	public void set(final int index) {
		this.index = index;
	}

	public void inc() {
		inc(1);
	}

	public void inc(final int count) {
		index += count;
	}

	/** Throws {@link IllegalArgumentException} when syntax is incorrect. */
	public void die(final String message) {
		throw new IllegalArgumentException(messageWithDetails(message));
	}

	/** Throws {@link IllegalStateException} if something goes wrong. */
	public void assertThat(final boolean condition, final String message) {
		if (condition) return;
		fail(message);
	}

	/** Throws {@link IllegalStateException} when something is wrong. */
	public void fail(final String message) {
		throw new IllegalStateException(messageWithDetails(message));
	}

	// -- Object methods --

	@Override
	public String toString() {
		return "" + get();
	}

	// -- Helper methods --

	private String messageWithDetails(final String message) {
		return message + " at index " + get();
	}

}

Add a little helper for tracking parse position


package nl.hsac.fitnesse.fixture.slim;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import nl.hsac.fitnesse.fixture.util.FileUtil;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

/**
 * Fixture to deal with Base64 values.
 */
public class Base64Fixture extends SlimFixture {
    private String saveBase = new File(filesDir, "base64").getPath() + "/";

    /**
     * Gets the content of specified file base64 encoded.
     * @param fileUrl either absolute path, or link to file inside wiki's files section.
     * @return base64 encoded file content.
     */
    public String encode(String fileUrl) {
        String file = getFilePathFromWikiUrl(fileUrl);
        try {
            byte[] content = IOUtils.toByteArray(new FileInputStream(file));
            return base64Encode(content);
        } catch (IOException e) {
            throw new SlimFixtureException("Unable to read: " + file, e);
        }
    }

    /**
     * Creates a new file with content read from base64 encoded string.
     * @param fileName (base) file name to create (if a file with specified name already exists
     *                 a number will be added to make the name unique).
     * @param base64String base64 encoded string to decode and use as file content.
     * @return location of created file.
     */
    public String createFrom(String fileName, String base64String) {
        String result;
        String baseName = FilenameUtils.getBaseName(fileName);
        String target = saveBase + baseName;
        String ext = FilenameUtils.getExtension(fileName);
        byte[] content = base64Decode(base64String);
        String downloadedFile = FileUtil.saveToFile(target, ext, content);
        String wikiUrl = getWikiUrl(downloadedFile);
        if (wikiUrl != null) {
            // make href to file
            result = String.format("%s", wikiUrl, fileName);
        } else {
            result = downloadedFile;
        }
        return result;
    }

    protected String base64Encode(byte[] content) {
        return org.apache.commons.codec.binary.Base64.encodeBase64String(content);
    }
    protected byte[] base64Decode(String base64String) {
        return org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
    }

    public String getSaveBase() {
        return saveBase;
    }

    public void setSaveBase(String saveBase) {
        this.saveBase = saveBase;
    }
}

Add fixture to deal with base64 encoded binary values


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

package org.cyanogenmod.hardware;

import org.cyanogenmod.hardware.util.FileUtils;

/*
 * Disable capacitive keys
 *
 * This is intended for use on devices in which the capacitive keys
 * can be fully disabled for replacement with a soft navbar. You
 * really should not be using this on a device with mechanical or
 * otherwise visible-when-inactive keys
 */

public class KeyDisabler {

    private static String CONTROL_PATH = "/sys/class/sec/sec_touchkey/input/enabled";

    public static boolean isSupported() {
        return true;
    }

    public static boolean isActive() {
        return (FileUtils.readOneLine(CONTROL_PATH).equals("0"));
    }

    public static boolean setActive(boolean state) {
        return FileUtils.writeLine(CONTROL_PATH, (state ? "0" : "1"));
    }

}

Allow capacitive buttons to be disabled


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

package org.springframework.boot.actuate.autoconfigure.metrics.export.properties;

import java.time.Duration;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Base test for {@link StepRegistryPropertiesConfigAdapter} implementations.
 *
 * @author Stephane Nicoll
 */
public abstract class StepRegistryPropertiesConfigAdapterTests<P extends StepRegistryProperties, A extends StepRegistryPropertiesConfigAdapter<P>> {

	protected abstract P createProperties();

	protected abstract A createConfigAdapter(P properties);

	@Test
	public void whenPropertiesStepIsSetAdapterStepReturnsIt() {
		P properties = createProperties();
		properties.setStep(Duration.ofSeconds(42));
		assertThat(createConfigAdapter(properties).step())
				.isEqualTo(Duration.ofSeconds(42));
	}

	@Test
	public void whenPropertiesEnabledIsSetAdapterEnabledReturnsIt() {
		P properties = createProperties();
		properties.setEnabled(false);
		assertThat(createConfigAdapter(properties).enabled()).isFalse();
	}

	@Test
	public void whenPropertiesConnectTimeoutIsSetAdapterConnectTimeoutReturnsIt() {
		P properties = createProperties();
		properties.setConnectTimeout(Duration.ofMinutes(42));
		assertThat(createConfigAdapter(properties).connectTimeout())
				.isEqualTo(Duration.ofMinutes(42));
	}

	@Test
	public void whenPropertiesReadTimeoutIsSetAdapterReadTimeoutReturnsIt() {
		P properties = createProperties();
		properties.setReadTimeout(Duration.ofMillis(42));
		assertThat(createConfigAdapter(properties).readTimeout())
				.isEqualTo(Duration.ofMillis(42));
	}

	@Test
	public void whenPropertiesNumThreadsIsSetAdapterNumThreadsReturnsIt() {
		P properties = createProperties();
		properties.setNumThreads(42);
		assertThat(createConfigAdapter(properties).numThreads()).isEqualTo(42);
	}

	@Test
	public void whenPropertiesBatchSizeIsSetAdapterBatchSizeReturnsIt() {
		P properties = createProperties();
		properties.setBatchSize(10042);
		assertThat(createConfigAdapter(properties).batchSize()).isEqualTo(10042);
	}

}

Add base test for StepRegistryPropertiesConfigAdapter


/*
 * Copyright (C) 2014  Ohm Data
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package c5db.util;

import com.google.common.collect.Iterators;

import java.util.Iterator;

public class C5Iterators {

  /**
   * Lazily advance the passed Iterator the given number of times. A lazy variant of
   * {@link com.google.common.collect.Iterators#advance}
   *
   * @return A new Iterator object representing the given Iterator advanced a specified
   * number of times, calling the given Iterator's next() method when needed.
   */
  public static <T> Iterator<T> advanced(Iterator<T> backingIterator, int numberToAdvance) {
    return new Iterator<T>() {
      private boolean advanced;

      @Override
      public boolean hasNext() {
        lazilyAdvance();
        return backingIterator.hasNext();
      }

      @Override
      public T next() {
        lazilyAdvance();
        return backingIterator.next();
      }

      @Override
      public void remove() {
        lazilyAdvance();
        backingIterator.remove();
      }

      private void lazilyAdvance() {
        if (!advanced) {
          Iterators.advance(backingIterator, numberToAdvance);
          advanced = true;
        }
      }
    };
  }
}

Add a lazy Iterator advance method


package fr.tvbarthel.apps.sayitfromthesky.helpers;

import android.database.Cursor;

/**
 * Static utility methods for dealing with cursor.
 */
public final class CursorHelper {

    // Non-instantiability
    private CursorHelper() {
    }

    public static String getString(Cursor cursor, String columnName, String defaultValue) {
        final int columnIndex = cursor.getColumnIndex(columnName);
        if (columnIndex == -1) return defaultValue;
        return cursor.getString(columnIndex);
    }

    public static long getLong(Cursor cursor, String columnName, long defaultValue) {
        final int columnIndex = cursor.getColumnIndex(columnName);
        if (columnIndex == -1) return defaultValue;
        return cursor.getLong(columnIndex);
    }

}

Add an helper class to deal with cursor


// Use an enum constructor, instance variable, and method.
enum Transport {
	CAR(65), TRUCK(55), AIRPLANE(600), TRAIN(70), BOAT(22);

	private int speed; // typical speed of each transport

	// Constructor
	Transport(int s) { speed = s; }

	int getSpeed() { return speed; }
}

class EnumDemo3 {
	public static void main(String args[]) {
		Transport tp;
		// Display speed of an airplane.
		System.out.println("Typical speed for an airplane is " + Transport.AIRPLANE.getSpeed() + " miles per hour.\n");

		// Display all Transports and speeds.
		System.out.println("All Transport speeds: ");
		for(Transport t : Transport.values())
			System.out.println(t + " typical speed is " + t.getSpeed() + " miles per hour.");
	}
}


package info.u_team.u_team_core.tileentity;

import net.minecraft.tileentity.*;

public abstract class UTickableTileEntity extends UTileEntity implements ITickableTileEntity {

	private boolean first;

	public UTickableTileEntity(TileEntityType<?> type) {
		super(type);
	}

	@Override
	public void tick() {
		if (!first) {
			first = true;
			firstTick();
		}
		if (world.isRemote()) {
			tickClient();
		} else {
			tickServer();
		}
	}

	protected void firstTick() {
	}

	protected void tickServer() {
	}

	protected void tickClient() {
	}

}

Add u tickable tile entity


package water;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.util.JProfile;

public class ProfilerTest extends TestUtil {

  @BeforeClass public static void stall() { stall_till_cloudsize(3); }

  @Test public void testProfiler() {
    for( int i=0; i<10; i++ ) {
      JProfile jp = new JProfile(5);
      jp.execImpl();
      Assert.assertEquals(jp.nodes.length,H2O.CLOUD.size());
      for (int j=0; j<H2O.CLOUD.size(); ++j) {
        Assert.assertTrue(jp.nodes[j].profile != null);
      }
    }
  }
}

Add JUnit test for Profiler.


package org.tinylog.impl.test;

import org.tinylog.impl.LogEntry;
import org.tinylog.impl.format.Placeholder;

/**
 * Renderer for {@link Placeholder Placeholders}.
 */
public class PlaceholderRenderer {

	private final Placeholder placeholder;

	/**
	 * @param placeholder The placeholder to render
	 */
	public PlaceholderRenderer(Placeholder placeholder) {
		this.placeholder = placeholder;
	}

	/**
	 * Renders the stored placeholder with the passed log entry as input.
	 *
	 * @param logEntry The log entry as input for {@link Placeholder#render(StringBuilder, LogEntry)}
	 * @return The render result
	 */
	public String render(LogEntry logEntry) {
		StringBuilder builder = new StringBuilder();
		placeholder.render(builder, logEntry);
		return builder.toString();
	}

}

Add placeholder renderer for JUnit tests


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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HealthController {

  @GetMapping("/health")
  public String health() {
    return "up";
  }
}

Add simple health check controller


package com.yahoo.searchdefinition.processing;

import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.document.DataType;
import com.yahoo.document.Field;
import com.yahoo.searchdefinition.DocumentReference;
import com.yahoo.searchdefinition.Search;
import com.yahoo.searchdefinition.document.ImportedField;
import com.yahoo.searchdefinition.document.ImportedFields;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.document.SDField;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Collections;

/**
 * @author bjorncs
 */
public class ValidateFieldTypesTest {

    private static final String IMPORTED_FIELD_NAME = "imported_myfield";
    private static final String DOCUMENT_NAME = "mydoc";

    @Rule
    public final ExpectedException exceptionRule = ExpectedException.none();

    @Test
    public void throws_exception_if_type_of_document_field_does_not_match_summary_field() {
        Search search = createDocumentWithImportedFieldInDocumentSummary();
        ValidateFieldTypes validator = new ValidateFieldTypes(search, null, null, null);
        exceptionRule.expect(IllegalArgumentException.class);
        exceptionRule.expectMessage(
                "For search '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " +
                "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string.");
        validator.process();
    }

    private static Search createDocumentWithImportedFieldInDocumentSummary() {
        // Create search with a single imported field
        Search search = new Search(DOCUMENT_NAME, MockApplicationPackage.createEmpty());
        SDDocumentType document = new SDDocumentType("mydoc", search);
        search.addDocument(document);
        Search targetDocument = new Search("otherdoc", MockApplicationPackage.createEmpty());
        SDField targetField = new SDField("myfield", DataType.INT);
        DocumentReference documentReference = new DocumentReference(new Field("reference_field"), targetDocument);
        ImportedField importedField = new ImportedField(IMPORTED_FIELD_NAME, documentReference, targetField);
        search.setImportedFields(new ImportedFields(Collections.singletonMap(IMPORTED_FIELD_NAME, importedField)));

        // Create document summary
        DocumentSummary summary = new DocumentSummary("mysummary");
        summary.add(new SummaryField(IMPORTED_FIELD_NAME, DataType.STRING));
        search.addSummary(summary);
        return search;
    }
}

Verify validation of types in summary fields


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel.component.seda;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

public class SedaWireTapOnCompleteTest extends ContextTestSupport {

    @Test
    public void testSeda() throws Exception {
        getMockEndpoint("mock:done").expectedHeaderValuesReceivedInAnyOrder("foo", "123", "456");
        getMockEndpoint("mock:first").expectedHeaderReceived("foo", "123");
        getMockEndpoint("mock:second").expectedHeaderReceived("foo", "456");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                onCompletion().log("Done ${header.foo}").to("mock:done");

                from("direct:start")
                    .setHeader("foo", constant("123"))
                    .log("First ${header.foo}")
                    .wireTap("seda:cheese")
                    .to("mock:first");

                from("seda:cheese")
                    .setHeader("foo", constant("456"))
                    .log("Second ${header.foo}")
                    .to("mock:second");
            }
        };
    }
}

Add test based on user forum issue


package edu.colorado.csdms.wmt.client.ui.cell;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.TextBox;

import edu.colorado.csdms.wmt.client.data.ParameterJSO;

/**
 * Displays an editable text box in a {@link ValueCell}. It's initialized with
 * the default value of a "string" parameter type.
 *
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class TextCell extends TextBox {

  private ValueCell parent;
  private ParameterJSO parameter;

  public TextCell(ValueCell parent) {

    this.parent = parent;
    this.parameter = this.parent.getParameter();

    this.addKeyUpHandler(new TextEditHandler());
    this.setStyleName("wmt-TextBoxen");
    this.setText(parameter.getValue().getDefault());
  }

  /**
   * The handler for keyboard events in a TextCell.
   */
  public class TextEditHandler implements KeyUpHandler {
    @Override
    public void onKeyUp(KeyUpEvent event) {
      GWT.log("(onKeyUp:text)");
      TextCell cell = (TextCell) event.getSource();
      parent.setParameterValue(cell.getText());
    }
  }
}

package edu.colorado.csdms.wmt.client.ui.cell;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.TextBox;

import edu.colorado.csdms.wmt.client.data.ParameterJSO;

/**
 * Creates an editable text box in a {@link ValueCell}. {@link KeyUpHandler}
 * events are handled in {@link TextCellHandler}.
 *
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class TextCell extends TextBox {

  private ValueCell parent;
  private ParameterJSO parameter;

  /**
   * Makes a {@link TextCell} initialized with the default value of a "string"
   * parameter type.
   *
   * @param parent the parent of the TextCell, a ValueCell
   */
  public TextCell(ValueCell parent) {

    this.parent = parent;
    this.parameter = this.parent.getParameter();

    this.addKeyUpHandler(new TextCellHandler());
    this.setStyleName("wmt-TextBoxen");
    this.setText(parameter.getValue().getDefault());
  }

  /**
   * The handler for keyboard events in a TextCell.
   */
  public class TextCellHandler implements KeyUpHandler {
    @Override
    public void onKeyUp(KeyUpEvent event) {
      GWT.log("(onKeyUp:text)");
      TextCell cell = (TextCell) event.getSource();
      parent.setParameterValue(cell.getText());
    }
  }
}

Rename event handler, add docstrings


package de.asw.java.training2016.net;

import java.net.URI;

public class UriExample {
	public static void main(String[] args) {

		URI uri = URI.create("https://user:password@www.example.com:8042/over/there?name=ferret#nose");
		System.out.println(uri);
		System.out.println("Scheme: " + uri.getScheme());
		System.out.println("Scheme-SpecificPart: " + uri.getSchemeSpecificPart());
		System.out.println("Userinfo: " + uri.getUserInfo());
		System.out.println("Host: " + uri.getHost());
		System.out.println("Authority: " + uri.getAuthority());
		System.out.println("Port: " + uri.getPort());
		System.out.println("Path: " + uri.getPath());
		System.out.println("Query: " + uri.getQuery());
		System.out.println("Fragment: " + uri.getFragment());
	}
}

Add example for parsing an URI with Java


/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */

public class Solution extends GuessGame {

    public int guessNumber(int n) {

        int low = 1;
        int hight = n;

        while (low < hight) {

            int mid = low + (hight - low) / 2;

            if (guess(mid) == 0) {
                return mid;
            }

            if (guess(mid) == 1) {
                low = mid + 1;
            } else {
                hight = mid;
            }

        }

        return low;

    }

}

Create : 374 Guess Number Higher or Lower


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.el;

import jakarta.el.ELContext;
import jakarta.el.ExpressionFactory;

import org.junit.Assert;
import org.junit.Test;

import org.apache.jasper.el.ELContextImpl;

public class TestExpressionFactory {

    @Test(expected = NullPointerException.class)
    public void testCreateValueExpression2ParamNullExpectedType() {
        ExpressionFactory factory = ExpressionFactory.newInstance();
        Assert.assertNotNull(factory);

        factory.createValueExpression("foo", null);
    }

    @Test(expected = NullPointerException.class)
    public void testCreateValueExpression3ParamNullExpectedType() {
        ExpressionFactory factory = ExpressionFactory.newInstance();
        Assert.assertNotNull(factory);

        ELContext context = new ELContextImpl(factory);
        Assert.assertNotNull(context);

        factory.createValueExpression(context, "foo", null);
    }
}

Expand coverage of unit tests


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.game.runner.manager;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.andengine.engine.Engine;
import org.andengine.util.FileUtils;
import org.game.runner.GameActivity;
import org.helllabs.android.xmp.ModPlayer;

/**
 *
 * @author Karl
 */
public class AudioManager {
    private static final AudioManager INSTANCE = new AudioManager();

    private Engine engine = ResourcesManager.getInstance().engine;
    private GameActivity activity = ResourcesManager.getInstance().activity;

    private final ModPlayer mModPlayer = ModPlayer.getInstance();
    private boolean looping = true;

    public void prepareModFile(final String dir, final String file){
        if(FileUtils.isExternalStorageReadable() && FileUtils.isExternalStorageWriteable() && !FileUtils.isFileExistingOnExternalStorage(this.activity, dir + file)) {
            AudioManager.this.activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileUtils.ensureDirectoriesExistOnExternalStorage(AudioManager.this.activity, dir);
                        FileUtils.copyToExternalStorage(AudioManager.this.activity, dir + file, dir + file);
                    } catch (IOException ex) {
                        Logger.getLogger(GameActivity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
    }

    public void playModFile(final String dir, final String file){
        if(FileUtils.isExternalStorageReadable()){
            if(!FileUtils.isFileExistingOnExternalStorage(this.activity, dir + file)){
                this.prepareModFile(dir, file);
            }
            this.mModPlayer.play(FileUtils.getAbsolutePathOnExternalStorage(this.activity, dir + file), this.looping);
        }
    }

    public void setLooping(boolean looping){
        this.looping = looping;
    }

    public static AudioManager getInstance(){
        return INSTANCE;
    }
}

Add bases of Audio manager


package test;

import jscompile.JSCompile;
import jscompile.exceptions.CircularDependencyException;
import jscompile.exceptions.UnknownImportException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class JSCompileTest {

    public String ROOT_DIR = "";

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testProjectCompilationFromNonLocalDirectory() throws CircularDependencyException, UnknownImportException, IOException {
        String[] args = {"./test-resources/mockproject", "./test-resources/mockCompileTargetDirectory/mockproject.js"};
        JSCompile.main(args);
        File expectedFile = new File("./test-resources/mockCompileTargetDirectory/mockproject.js");
        assert(expectedFile.exists());
    }
}

Test added for non-local directories, is passing. (Fixed in refactoring to JSCompile V2)


package leetcode.contains_duplicate_iii;

import java.util.ArrayList;

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(k == 0) return false;
        ArrayList<Integer> window = new ArrayList<Integer>(k);
        if(nums == null || nums.length == 0) return false;
        window.add(nums[0]);
        int L, U;
        for(int i = 1; i < nums.length; i++){
            L = -1;
            U = window.size();
            while(L + 1 < U){
                int mid = L + (U - L) / 2;
                if(window.get(mid) > nums[i]){
                    U = mid;
                }else{
                    L = mid;
                }
            }
            if(L >= 0 && (long)nums[i] - window.get(L) <= (long)t) return true;
            if(U < window.size() && (long)window.get(U) - nums[i] <= (long)t) return true;
            window.add(U, nums[i]);
            if(i >= k){
                L = -1;
                U = window.size();
                while(L + 1 < U){
                    int mid = L + (U - L) / 2;
                    if(window.get(mid) > nums[i - k]){
                        U = mid;
                    }else{
                        L = mid;
                    }
                }
                window.remove(L);
            }
        }
        return false;
    }
}

Add java solution for 220. Contains Duplicate III


package ge.edu.freeuni.sdp.arkanoid.model;

import ge.edu.freeuni.sdp.arkanoid.model.geometry.Point;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Size;

/**
 * Created By Nika Doghonadze 4/10/2016.
 */
public class TestACapsuleLevelBuilder extends TestFrameBuilder {
    public TestACapsuleLevelBuilder(Size size) {
        super(size);
    }

    @Override
    public void build(Room room, ScoreCounter scoreCounter) {
        super.build(room, scoreCounter);
        int brickDistance = 4;
        int roomWidth = Configuration.getInstance().getSize().getWidth();

        for (int i = 0; i < roomWidth; i += brickDistance) {
            Point position = new Point(i, 5);
            Capsule capsule = new LaserCapsule(position, room);
            Brick current = new NormalBrick(position, BrickColor.Red, capsule);
            room.add(current);
        }
    }
}

Add Laser Capsule Tester Level


package com.byndyusoft.calculator.domain.eval;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class ExpressionEvalTest {

    /**
     * Test if (10 * (3 + 8)) expression evaluates correctly
     */
    @Test
    public void testExpressionEvaluations() {
        AbstractNode plus = new PlusNode(new NumberNode(3), new NumberNode(8));
        AbstractNode multiply = new MultiplyNode(new NumberNode(10), plus);
        double value = multiply.eval();

        assertEquals(110, value, 0.0);
    }
}

Add test for complex expression evaluation


package org.bouncycastle.crypto.tls;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;

/**
 * HMAC implementation based on original internet draft for HMAC (RFC 2104)
 *
 * The difference is that padding is concatentated versus XORed with the key
 *
 * H(K + opad, H(K + ipad, text))
 */
public class SSL3Mac implements Mac
{
    private final static byte IPAD = (byte)0x36;
    private final static byte OPAD = (byte)0x5C;

    private Digest digest;

    private byte[] secret;
    private byte[] ipad, opad;

    /**
     * Base constructor for one of the standard digest algorithms that the byteLength of
     * the algorithm is know for. Pad length should be 48 for MD5 or 40 for SHA1.
     *
     * @param digest the digest.
     */
    public SSL3Mac(Digest digest, int padLength)
    {
        this.digest = digest;
        this.ipad = genPad(IPAD, padLength);
        this.opad = genPad(OPAD, padLength);
    }

    public String getAlgorithmName()
    {
        return digest.getAlgorithmName() + "/SSL3MAC";
    }

    public Digest getUnderlyingDigest()
    {
        return digest;
    }

    public void init(CipherParameters params)
    {
        secret = Arrays.clone(((KeyParameter)params).getKey());

        reset();
    }

    public int getMacSize()
    {
        return digest.getDigestSize();
    }

    public void update(byte in)
    {
        digest.update(in);
    }

    public void update(byte[] in, int inOff, int len)
    {
        digest.update(in, inOff, len);
    }

    public int doFinal(byte[] out, int outOff)
    {
        byte[] tmp = new byte[digest.getDigestSize()];
        digest.doFinal(tmp, 0);

        digest.update(secret, 0, secret.length);
        digest.update(opad, 0, opad.length);
        digest.update(tmp, 0, tmp.length);

        int len = digest.doFinal(out, outOff);

        reset();

        return len;
    }

    /**
     * Reset the mac generator.
     */
    public void reset()
    {
        digest.reset();
        digest.update(secret, 0, secret.length);
        digest.update(ipad, 0, ipad.length);
    }

    private static byte[] genPad(byte b, int count)
    {
        byte[] padding = new byte[count];
        Arrays.fill(padding, b);
        return padding;
    }
}

Add SSL3MAC (early draft of HMac)


package in.webplay.poker;

import java.util.*;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class DeckTest {
    Deck deck;

    @Before
    public void before() {
        deck = new Deck();
    }

    @Test
    public void canCreateAFullDeck() {
        assertEquals(52, deck.size());
    }

    @Test
    public void shouldRemoveDealtCardsFromDeck() {
        List<Card> hand = deck.deal(5);
        assertEquals(47, deck.size());
        assertEquals(5, hand.size());
    }

    @Test
    public void shouldOnlyDealAsManyCardsAsInDeck() {
        List<Card> hand = deck.deal(100);
        assertEquals(0, deck.size());
        assertEquals(52, hand.size());
    }

    @Test
    public void shouldBeAbleToShuffleDeck() {
        String preShuffle = deck.toString();
        deck.shuffle();
        String postShuffle = deck.toString();
        assertFalse(preShuffle.equals(postShuffle));
    }

    @Test
    public void shuffledDeckShouldBeFullAgain() {
        deck.deal(5);
        deck.shuffle();
        assertEquals(52, deck.size());
    }

}

Add tests for Deck class


package hdfs.jsr203;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;

public class HadoopFileChannel extends FileChannel {

    private SeekableByteChannel internalChannel;

    public HadoopFileChannel(SeekableByteChannel newByteChannel) {
        this.internalChannel = newByteChannel;
    }

    @Override
    public int read(ByteBuffer dst) throws IOException {
        return this.internalChannel.read(dst);
    }

    @Override
    public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public int write(ByteBuffer src) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public long position() throws IOException {
        return this.internalChannel.position();
    }

    @Override
    public FileChannel position(long newPosition) throws IOException {
        this.internalChannel.position(newPosition);
        return this;
    }

    @Override
    public long size() throws IOException {
        return this.internalChannel.size();
    }

    @Override
    public FileChannel truncate(long size) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public void force(boolean metaData) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public long transferTo(long position, long count, WritableByteChannel target) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public int read(ByteBuffer dst, long position) throws IOException {
        this.internalChannel = this.internalChannel.position(position);
        return this.internalChannel.read(dst);
    }

    @Override
    public int write(ByteBuffer src, long position) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public FileLock lock(long position, long size, boolean shared) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    public FileLock tryLock(long position, long size, boolean shared) throws IOException {
        throw new IOException("Imcomplete implementation");
    }

    @Override
    protected void implCloseChannel() throws IOException {
        this.internalChannel.close();
    }

}

Add basic support for FileChannel


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

import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;

public class TestBaseConnectorTest
{
    @Test
    public void testThatAllTestsAreCopied()
    {
        assertThat(getMethods(BaseConnectorTest.class)).containsAll(getMethods(AbstractTestIntegrationSmokeTest.class));
    }

    private List<MethodSignature> getMethods(Class<?> clazz)
    {
        return Arrays.stream(clazz.getMethods())
                .map(method -> new MethodSignature(method.getName(), method.getParameterTypes()))
                .collect(toImmutableList());
    }

    private static final class MethodSignature
    {
        private final String name;
        private final List<Class<?>> parameters;

        private MethodSignature(String name, Class<?>[] parameters)
        {
            this.name = requireNonNull(name, "name is null");
            this.parameters = ImmutableList.copyOf(requireNonNull(parameters, "fields is null"));
        }

        @Override
        public boolean equals(Object o)
        {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MethodSignature that = (MethodSignature) o;
            return Objects.equals(name, that.name) &&
                    Objects.equals(parameters, that.parameters);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(name, parameters);
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("name", name)
                    .add("fields", parameters)
                    .toString();
        }
    }
}

Verify that BaseConnectorTest contains all tests


package org.iotbricks.core.binding.proton;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.message.Message;
import org.iotbricks.core.binding.amqp.AmqpRequestContext;
import org.iotbricks.core.binding.common.MessageResponseHandler;

/**
 * A specialized {@link MessageResponseHandler} for errors.
 * <p>
 * This handler also sets the application property {@code status} to {@code 500}
 * on the proton message. Indicating an error to the receiver.
 */
public class ProtonErrorMessageResponseHandler extends MessageResponseHandler<ProtonRequestContext, Message> {

    private static final Consumer<Message> SET_TO_500 = message -> {
        final Map<String, ?> properties = Collections.singletonMap("status", 500);
        message.setApplicationProperties(new ApplicationProperties(properties));
    };

    public ProtonErrorMessageResponseHandler(
            final Function<ProtonRequestContext, Optional<String>> responseAddressProvider) {
        super(responseAddressProvider, SET_TO_500);
    }

    public ProtonErrorMessageResponseHandler() {
        super(AmqpRequestContext::getReplyToAddress);
    }

}

Add a proton specific error response handler


import java.util.*;
import java.io.*;

class ArrayDS2D {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a[][] = new int[6][6];
		for(int i = 0; i < 6; i++) {
			for(int j = 0; j < 6; j++) {
				a[i][j] = sc.nextInt();
			}
		}
		int max = a[0][0] + a[0][1] + a[1][1] + a[0][2] + a[2][0] + a[2][1] + a[2][2];
		int hourglass;
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				hourglass = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
				if(hourglass > max)
					max = hourglass;
			}
		}
		System.out.println(max);
	}
}

Add solution to 2D Arrays problem


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

package org.cyanogenmod.hardware;

import org.cyanogenmod.hardware.util.FileUtils;

/*
 * Disable capacitive keys
 *
 * This is intended for use on devices in which the capacitive keys
 * can be fully disabled for replacement with a soft navbar. You
 * really should not be using this on a device with mechanical or
 * otherwise visible-when-inactive keys
 */

public class KeyDisabler {

    private static String CONTROL_PATH = "/sys/class/sec/sec_touchkey/input/enabled";

    public static boolean isSupported() {
        return true;
    }

    public static boolean isActive() {
        return (FileUtils.readOneLine(CONTROL_PATH).equals("0"));
    }

    public static boolean setActive(boolean state) {
        return FileUtils.writeLine(CONTROL_PATH, (state ? "0" : "1"));
    }

}

Allow capacitive buttons to be disabled


package com.pennapps.labs.pennmobile;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }

    @Override
    protected void setUp() throws Exception {
        createApplication();
    }

    public void testApplicationPackageName() {
        Application mApplication = getApplication();
        assertEquals("com.pennapps.labs.pennmobile", mApplication.getPackageName());
    }
}

Add super basic testing to app


package emergencylanding.k.library.debug;

import emergencylanding.k.library.util.DataStruct;

public class DataStructTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

	// A data struct with all thpes in one.
	DataStruct dec = new DataStruct(new Object[] { "string", 1, 1.1d, 1.1f,
		1l, (byte) 1, (char) 1, true, new DataStructTest() });
	DataStruct enc = new DataStruct(dec.toString());
    }

}

Add test for DataStruct not based on netty


package leetcode.trapping_rain_water;

public class Solution {
    public int trap(int[] A) {
    	if(A == null || A.length == 0) return 0;
    	int len = A.length;
    	int maxi = len - 1;
    	int max = A[len - 1];
    	for(int i = len - 1; i >= 0; i--){
    		if(A[i] > max){
    			maxi = i;
    			max = A[i];
    		}
    	}
        int cur = 0;
        int water = 0;
        for(int i = 0; i < maxi; i++){
        	if(A[i] > cur){
        		cur = A[i];
        	}else{
        		water += cur - A[i];
        	}
        }
        cur = 0;
        for(int i = len - 1; i > maxi; i--){
        	if(A[i] > cur){
        		cur = A[i];
        	}else{
        		water += cur - A[i];
        	}
        }
        return water;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().trap(new int[]{0, 1, 0, 2, 3, 0, 1, 3, 2, 1, 2, 1}));
    }
}

Add java solution for 42. Trapping Rain Water


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.logging.log4j.core.config.plugins.visitors;

import java.util.Map;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;

/**
 * PluginVisitor for PluginBuilderAttribute. If {@code null} is returned for the
 * {@link #visit(org.apache.logging.log4j.core.config.Configuration, org.apache.logging.log4j.core.config.Node, org.apache.logging.log4j.core.LogEvent)}
 * method, then the default value of the field should remain untouched.
 *
 * @see org.apache.logging.log4j.core.config.plugins.util.PluginBuilder
 */
public class PluginBuilderAttributeVisitor extends AbstractPluginVisitor<PluginBuilderAttribute> {

    public PluginBuilderAttributeVisitor() {
        super(PluginBuilderAttribute.class);
    }

    @Override
    public Object visit(final Configuration configuration, final Node node, final LogEvent event) {
        final String overridden = this.annotation.value();
        final String name = overridden.isEmpty() ? this.member.getName() : overridden;
        final Map<String, String> attributes = node.getAttributes();
        final String rawValue = removeAttributeValue(attributes, name, this.aliases);
        final String replacedValue = this.substitutor.replace(event, rawValue);
        final Object value = convert(replacedValue, null);
        LOGGER.debug("Attribute({}=\"{}\")", name, value);
        return value;
    }
}

Add visitor strategy for @PluginBuilderAttribute.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// https://www.hackerrank.com/challenges/new-year-chaos/problem
public class NewYearChaos {

    private static final String SPACE = " ";
    private static final String TOO_CHAOTIC = "Too chaotic";

    private static List<int[]> readQueues() throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            int testCases = Integer.parseInt(reader.readLine());
            List<int[]> queues = new ArrayList<>(testCases);
            for (int i = 0; i < testCases; i++) {
                reader.readLine(); // Ignore this line
                String[] split = reader.readLine().split(SPACE);
                int[] queue = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
                queues.add(queue);
            }
            return queues;
        }
    }

    private static void checkQueueIsPossible(int[] queue) {
        for (int i = 0; i < queue.length; i++) {
            int correctedIndex = i + 1;
            int currentPosition = queue[i];
            int positionDifference = currentPosition - correctedIndex;
            if (positionDifference > 2) {
                throw new IllegalStateException(TOO_CHAOTIC);
            }
        }
    }

    private static int getMinSwitches(int[] queue) {
        int minSwitches = 0;
        for (int i = queue.length - 1; i >= 0; i--) {
            int initialPosition = queue[i];
            // if someone pass me it should be maximum in my initial position - 2.
            int maxBribedPosition = (initialPosition - 2 > 0) ? initialPosition - 2: 0;
            for (int j = maxBribedPosition; j < i; j++) {
                int first = queue[j];
                boolean wasBrived = first > initialPosition;
                minSwitches += wasBrived ? 1: 0;
            }
        }
        return minSwitches;
    }

    public static void main(String[] args) throws IOException {
        List<int[]> queues = readQueues();
        for (int[] queue : queues) {
            try {
                checkQueueIsPossible(queue);
                int minSwitches = getMinSwitches(queue);
                System.out.println(minSwitches);
            } catch (IllegalStateException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

Add solution for New Year Chaos problem.


package ru.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Maria on 20.07.2016.
 */
public class SearchFilm extends TestNgTestBase {
    private WebDriverWait wait;
    private String filmIwant;

    @BeforeSuite
    public void login() {
        driver.get(baseUrl + "/php4dvd/");
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
        wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username")));
        driver.findElement(By.id("username")).clear();
        driver.findElement(By.id("username")).sendKeys("admin");
        driver.findElement(By.name("password")).clear();
        driver.findElement(By.name("password")).sendKeys("admin");
        driver.findElement(By.name("submit")).click();
    }

    @Test // фильм найден
    public void testFoundFilm() throws Exception {
        List<WebElement> films = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("movie_box")));

        WebElement searchField = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("q")));
        searchField.clear();
        filmIwant = "Ice Age";
        searchField.sendKeys(filmIwant + Keys.RETURN);

        Boolean rsltsInvsbl = wait.until(ExpectedConditions.invisibilityOfAllElements(films));
        Assert.assertTrue(rsltsInvsbl);

        List<WebElement> searchResult = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("movie_box")));
        for (WebElement webElement : searchResult) {
            Assert.assertTrue(filmIwant.equals(webElement.findElement(By.className("title")).getText()));
        }
    }

    @Test // фильм не найден
    public void testNotFoundFilm(){
        List<WebElement> films = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("movie_box")));

        WebElement searchField = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("q")));
        searchField.clear();
        filmIwant = "klflvk";
        searchField.sendKeys(filmIwant + Keys.RETURN);

        Boolean rsltsInvsbl = wait.until(ExpectedConditions.invisibilityOfAllElements(films));
        Assert.assertTrue(rsltsInvsbl);

        WebElement notFound = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("content")));
        String title = notFound.getText();

        Assert.assertTrue(title.equals("No movies where found."));
    }
}

Add tests FılmFound and FılmNotFound


package leetcode.text_justification;

import java.util.ArrayList;

public class Solution {
    public ArrayList<String> fullJustify(String[] words, int L) {
    	ArrayList<String> ans = new ArrayList<String>();
    	ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
    	if(words.length == 0) return ans;
    	int lineIdx = 0;
    	int wordIdx = 0;
    	int lineUsage = 0;
    	while(wordIdx < words.length){
    		ArrayList<String> currLine;
    		if(lines.size() <= lineIdx){
    			currLine = new ArrayList<String>();
    			lines.add(currLine);
    			lineUsage = 0;
    		}else{
    			currLine = lines.get(lineIdx);
    		}
    		if(lineUsage > 0){
    			if(lineUsage + 1 + words[wordIdx].length() > L){
    				lineIdx++;
    			}else{
    				lineUsage += 1 + words[wordIdx].length();
    				currLine.add(words[wordIdx]);
    				wordIdx++;
    			}
    		}else{
    			lineUsage = words[wordIdx].length();
    			currLine.add(words[wordIdx]);
    			wordIdx++;
    		}
    	}
    	for(int idx = 0; idx < lines.size(); idx++){
    		ArrayList<String> line = lines.get(idx);
    		StringBuilder sb = new StringBuilder();
    		int lengthSum = 0;
    		for(String s : line){
    			lengthSum += s.length();
    		}
    		int spaceSize;
    		int extraSpaceSize;
    		int used = 0;
    		if(line.size() == 1 || idx == lines.size() - 1){
    			spaceSize = 1;
    			extraSpaceSize = 0;
    		}else{
    			spaceSize = (L - lengthSum) / (line.size() - 1);
    			extraSpaceSize = (L - lengthSum) % (line.size() - 1);
    		}

    		for(int i = 0; i < line.size(); i++){
    			if(i > 0){
    				if(i <= extraSpaceSize){
    					sb.append(' ');
    					used++;
    				}
    				for(int j = 0; j < spaceSize; j++){
    					sb.append(' ');
    				}
    				used += spaceSize;
    			}
    			sb.append(line.get(i));
    			used += line.get(i).length();
    		}
    		for(int i = L - used; i > 0; i--){
    			sb.append(' ');
    		}

    		ans.add(sb.toString());
    	}
    	return ans;
    }

    public static void main(String[] args){
    	for(String s : new Solution().fullJustify(new String[]{"What","must","be","shall","be."}, 12)){
    		System.err.println("'" + s + "'");
    	}
    }
}

Add java solution for 68. Text Justification


// Copyright 2013 Judson D Neer

package com.singledsoftware.mixmaestro;

import java.io.Serializable;

/**
 * Stores data for an individual channel.
 *
 * @see Serializable
 * @author Judson D Neer
 */
public class Channel implements Serializable {

    // Unique serializable version ID
    private static final long serialVersionUID = -3705403776567370897L;

    // Unique numeric identifier for the channel
    private final int id;

    // Single character that identifies a channel type
    // TODO make this an enumeration
    private final char type;

    // User-assigned name for the channel
    private final String name;

    /**
     * Constructor.
     *
     * @param i New id
     * @param t New type
     * @param n New name
     */
    public Channel(int i, char t, String n) {
        id = i;
        type = t;
        name = n;
    }

    /**
     * @see java.io.Serializable#toString()
     */
    @Override
    public String toString() {
        // TODO put id and type in parens?
        return name;
    }

}

Add storage class for channels.


/*
 * #%L
 * mosaic-cloudlets
 * %%
 * Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania)
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

package eu.mosaic_cloud.examples.realtime_feeds.indexer;

import eu.mosaic_cloud.components.implementations.basic.MosBasicComponentLauncher;

import com.google.common.base.Preconditions;

public final class IndexerComponentLauncher
{
	private IndexerComponentLauncher ()
	{
		super ();
		throw (new UnsupportedOperationException ());
	}

	public static void main (final String[] arguments)
			throws Throwable
	{
		Preconditions.checkNotNull (arguments);
		final String[] finalArguments = new String[arguments.length + 1];
		System.arraycopy (arguments, 0, finalArguments, 0, arguments.length);
		finalArguments[arguments.length] = String.format ("{\"%s\":\"%s\"}", "descriptor", "indexer-cloudlet.properties");
		MosBasicComponentLauncher.main ("eu.mosaic_cloud.cloudlets.implementation.container.CloudletComponent$ComponentCallbacksProvider", finalArguments, IndexerComponentLauncher.class.getClassLoader ());
	}
}

Add examples indexer cloudlet launcher


package com.steelseries;

import org.json.JSONObject;

/**
 * Created by Mene on 11/26/2016.
 */
public class RegisterGame {

    private String id;
    private String name;
    private Integer color;

    /**
     * Constructor for the RegtisterGame object.
     * The value for {@code id} is limited to uppercase A-Z, 0-9, hyphen, and underscore characters.

     * The value for {@code name} are limited to uppercase A-Z, lowercase a-z, 0-9, hyphen, and underscore characters.

     * The {@code color} is an integer value between 0 and 11 see
     * here.
     *

     * 0:  Orange

     * 1:  Gold

     * 2:  Yellow

     * 3:  Green

     * 4:  Teal

     * 5:  Light blue

     * 6:  Blue

     * 7:  Purple

     * 8:  Fuschia

     * 9:  Pink

     * 10: Red

     * 11: Silver

     *
     * @param id
     * @param name
     * @param color
     */
    public RegisterGame(String id, String name, Integer color){
        this.id = id;
        this.name = name;
        this.color = color;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getColor() {
        return color;
    }

    public void setColor(Integer color) {
        this.color = color;
    }

    /**
     * This method returns a JSON format of the current object, provided that all parameters are properly set.
     *
     * @return JSONObject
     * @throws Exception
     */
    public JSONObject toJSONObject() throws Exception {
        JSONObject jsnObj = new JSONObject();
        if(this.id==null||this.id.trim()==""
            ||this.name==null||this.name.trim()==""
            ||this.color==null||this.color<0||this.color>11){
            throw new Exception(this.getClass() + ": not all parameters are set.");
        }

        jsnObj.put("game", this.id);
        jsnObj.put("game_display_name", this.name);
        jsnObj.put("icon_color_id", this.color);

        return jsnObj;
    }

}

Add http request support and first snippet to perform game registration inside the Engine.


package sfBugs;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Bug1874856 {

	public static void main(String args[]) {
		falsePositive();
	}

	public static void falsePositive() {
		  Calendar c = new GregorianCalendar(1993, 4, 23);
		   String s1 = String.format("Duke's Birthday: %1$tm %1$te, %1$tY", c);
		   System.out.println(s1);
		   String s2 = String.format("Duke's Birthday: %1$tm %<te, %<tY", c);
		   System.out.println(s2);
	}
}

Add test case for problem with format string detector


package seedu.taskell.commons.events.storage;

import seedu.taskell.commons.events.BaseEvent;

//@@author A0139257X-reused
public class DuplicateDataExceptionEvent extends BaseEvent{

    public Exception exception;

    public DuplicateDataExceptionEvent(Exception exception) {
        this.exception = exception;
    }

    @Override
    public String toString(){
        return exception.toString();
    }
}
//@@author

Add new event class for duplicate data exception


/*
 * Copyright (c) 2014, Oracle America, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 *  * Neither the name of Oracle nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

package net.nineseventwo.benchmarks;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Warmup;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
public class ValueOfSideEffectBenchmark {

	@Benchmark
	public String concatPrefix() {
		int value = 31337;
		value--;

		String converted = "" + (value++);

		return converted;
	}

	@Benchmark
	public String concatPostFix() {
		int value = 31337;
		value--;

		String converted = (value++) + "";

		return converted;
	}

    @Benchmark
    public String valueOfInteger() {
    	int value = 31337;
    	value--;

        String converted = String.valueOf(value++);

        return converted;
    }

    @Benchmark
    public String valueOfString() {
    	int value = 31337;
        value--;

        String converted = String.valueOf(value++);

        return converted;
    }

}

Add side effect benchmark of valueOf


package au.gov.ga.geodesy.test.integration.standalone;

import static com.jayway.restassured.RestAssured.given;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import au.gov.ga.geodesy.support.TestResources;

/**
 * Upload all SOPAC site logs.
 */
public class UploadSopacSiteLogs extends StandaloneIntegrationTest {

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

    private void uploadSopacSiteLog(File siteLog) throws Exception {
        log.info("Uploading " + siteLog.getName() + " to " + getConfig().getWebServicesUrl());
        given()
            .contentType("text/xml; charset=ISO-8859-1")
            .body(FileUtils.readFileToString(siteLog, "ISO-8859-1"))
        .when()
            .post(getConfig().getWebServicesUrl() + "/siteLog/sopac/upload")
        .then()
            .statusCode(201);
    }

    @Test
    public void upload() throws Exception {
        for (File siteLog : TestResources.sopacSiteLogs()) {
            uploadSopacSiteLog(siteLog);
        }
    }
}

Add standalone test to upload SOPAC site logs


package com.cgi.eoss.ftep.catalogue.util;

/**
 *
Well-known file types which may be handled by f-tep-catalogue, e.g. Reference Data, Input or Output Products.

 */
public enum CatalogueFileType {
    GEOJSON,
    GEOTIFF,
    KML,
    SHAPEFILE,
    OTHER
}

Add enumeration of known catalogue filetypes


package leetcode.majority_element;

public class Solution {
    public int majorityElement(int[] num) {
        int candidate = 0, counter = 0;
        for(int x : num){
            if(counter == 0){
                candidate = x;
                counter = 1;
            }else{
                if(candidate == x){
                    counter++;
                }else{
                    counter--;
                }
            }
        }
        return candidate;
    }
}

Add java solution for 169. Majority Element


/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.rest;

import java.util.HashMap;
import java.util.Map;

import okhttp3.HttpUrl;
import retrofit2.BaseUrl;

/**
 * An instance of this class stores information of the host of a service.
 */
public class AutoRestBaseUrl implements BaseUrl {
    /** A template based URL with variables wrapped in {}s. */
    private String template;
    /** a mapping from {} wrapped variables in the template and their actual values. */
    private Map<CharSequence, String> mappings;

    @Override
    public HttpUrl url() {
        String url = template;
        for (Map.Entry<CharSequence, String> entry : mappings.entrySet()) {
            url = url.replace(entry.getKey(), entry.getValue());
        }
        mappings.clear();
        return HttpUrl.parse(url);
    }

    /**
     * Creates an instance of a template based URL.
     *
     * @param url the template based URL to use.
     */
    public AutoRestBaseUrl(String url) {
        this.template = url;
        this.mappings = new HashMap<>();
    }

    /**
     * Sets the value for the {} wrapped variables in the template URL.
     * @param matcher the {} wrapped variable to replace.
     * @param value the value to set for the variable.
     */
    public void set(CharSequence matcher, String value) {
        this.mappings.put(matcher, value);
    }
}

Support parameterized hosts in Java


package net.craftstars.general.money;

public enum AccountStatus {
	FROZEN(false),
	INSUFFICIENT(false),
	SUFFICIENT(true),
	BYPASS(true);
	public final boolean canContinue;
	public static double price;

	private AccountStatus(boolean b) {
		canContinue = b;
	}
}

Add missing file from a few commits back


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.HashMap;
import java.util.Scanner;

public class CoinChange {
    public static long makeChange(int[] coins, int n) {
        if (n < 0) {
            return 0;
        }
        return makeChange(coins, n, 0, new HashMap<String, Long>());
    }

    public static long makeChange(int[] coins, int n, int coinNumber, HashMap<String, Long> cache) {
        String key = n + "," + coinNumber;
        if (cache.containsKey(key)) {
            return cache.get(key);
        }

        if (coinNumber == coins.length - 1) {
            if (n % coins[coinNumber] == 0) {
                cache.put(key, 1L);
                return 1;
            } else {
                cache.put(key, 0L);
                return 0;
            }
        }

        long ways = 0;
        for (int i = 0; i <= n; i += coins[coinNumber]) {
            ways += makeChange(coins, n - i, coinNumber + 1, cache);
        }

        cache.put(key, ways);
        return ways;
    }

    public static void main(String[] args) {
        try (Scanner scan = new Scanner(System.in)) {
            int n = scan.nextInt();
            int m = scan.nextInt();
            int[] coins = new int[m];
            for (int i = 0; i < m; i++) {
                coins[i] = scan.nextInt();
            }
            scan.close();

            System.out.println(makeChange(coins, n));
        }
    }
}

Add coin change CTCI challenge


package net.ttddyy.dsproxy.support;

import javax.servlet.ServletRequestEvent;

/**
 * {@link javax.servlet.ServletRequestListener} to log query metrics per http request using {@link java.lang.System#out}.
 *
 * @author Tadaya Tsuyukubo
 * @since 1.4.1
 */
public class SystemOutQueryCountLoggingRequestListener extends AbstractQueryCountLoggingRequestListener {

    @Override
    protected void writeLog(ServletRequestEvent servletRequestEvent, String logEntry) {
        System.out.println(logEntry);
    }

}

Add query count logging impl for ServletRequestListener with JUL