/*
 * 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

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

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

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

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());
    }
}

ISSUE-3: 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

220. Contains Duplicate III: https://leetcode.com/problems/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

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)

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

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

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

Make sure that any tests that was added to
AbstractTestIntegrationSmokeTest is copied to BaseConnectorTest.


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

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

zero: 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

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

42. Trapping Rain Water: https://leetcode.com/problems/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.

git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1599076 13f79535-47bb-0310-9956-ffa450edef68


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

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

68. Text Justification: https://leetcode.com/problems/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.

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

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

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9264 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

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

Former-commit-id: 212021a7411b18d2c065be748d1ee5771e145590


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

Change-Id: I606ee8be1844de121934a7238f23290b839ad994


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

169. Majority Element: https://leetcode.com/problems/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

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

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


/*
 * Copyright (c) 2006-2014 DMDirc Developers
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.dmdirc.addons.ui_swing.components.vetoable;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VetoableListSelectionModelTest {

    @Mock private VetoableChangeListener listener;

    @Test
    public void testInitialState() {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        assertEquals(instance.getLeadSelectionIndex(), -1);
        assertEquals(instance.getSelectionMode(), SINGLE_SELECTION);
        assertFalse(instance.getValueIsAdjusting());
    }

    @Test
    public void testNonVetoed() {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), 5);
    }

    @Test
    public void testVetoedCalled() throws PropertyVetoException {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.addVetoableSelectionListener(listener);
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), 5);
        verify(listener).vetoableChange(any(PropertyChangeEvent.class));
    }

    @Test
    public void testVetoedCalledAndVetoed() throws PropertyVetoException {
        doThrow(new PropertyVetoException(null, null))
                .when(listener).vetoableChange(any(PropertyChangeEvent.class));
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.addVetoableSelectionListener(listener);
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), -1);
    }

}

Add unit test for vetoablelistselectionmodel

Change-Id: I7f4592bdfddc0fb628697219f2892591f4c6c2a4
Reviewed-on: http://gerrit.dmdirc.com/3581
Automatic-Compile: DMDirc Build Manager
Reviewed-by: Chris Smith <711c73f64afdce07b7e38039a96d2224209e9a6c@dmdirc.com>


package io.datakernel.http;

import io.datakernel.async.Promises;
import io.datakernel.eventloop.Eventloop;
import io.datakernel.test.TestUtils;
import io.datakernel.test.rules.ByteBufRule;
import io.datakernel.test.rules.EventloopRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static io.datakernel.async.TestUtils.await;
import static java.nio.charset.StandardCharsets.UTF_8;

public class AsyncHttpServerClientBreakConnectionTest {
	private final Logger logger = LoggerFactory.getLogger(AsyncHttpServerClientBreakConnectionTest.class);
	private final int FREE_PORT = TestUtils.getFreePort();

	@ClassRule
	public static final EventloopRule eventloopRule = new EventloopRule();

	@ClassRule
	public static final ByteBufRule bufRule = new ByteBufRule();

	private AsyncHttpServer server;
	private AsyncHttpClient client;
	private Eventloop eventloop = Eventloop.getCurrentEventloop();

	@Before
	public void init() throws IOException {
		server = AsyncHttpServer.create(eventloop,
				request -> {
					logger.info("Closing server...");
					eventloop.post(() ->
							server.close().whenComplete(() -> logger.info("Server Closed")));
					return Promises.delay(
							HttpResponse.ok200()
									.withBody("Hello World".getBytes()),
							100L);
				})
				.withListenPort(FREE_PORT)
				.withAcceptOnce();

		client = AsyncHttpClient.create(eventloop);
		server.listen();
	}

	@Test
	public void testBreakConnection() {
		await(client.request(
				HttpRequest.post("http://127.0.0.1:" + FREE_PORT)
						.withBody("Hello World".getBytes()))
				.map(response ->
						response.loadBody()
								.map(body -> body.getString(UTF_8))));
	}
}

Add test of concurrent closing of AsyncHttpServer


/*
 * See the file "LICENSE" for the full license governing this code.
 */
package sdp.tools;

import sdp.graph.Graph;
import sdp.io.GraphReader;
import sdp.io.GraphWriter;

/**
 *
 * @author Marco Kuhlmann <marco.kuhlmann@liu.se>
 */
public class Splitter {

    public static void main(String[] args) throws Exception {
        GraphReader reader = new GraphReader(args[0]);
        GraphWriter writerTrain = new GraphWriter(args[1]);
        GraphWriter writerDevel = new GraphWriter(args[2]);
        Graph graph;
        while ((graph = reader.readGraph()) != null) {
            if (graph.id.substring(2, 4).equals("20")) {
                writerDevel.writeGraph(graph);
            } else {
                writerTrain.writeGraph(graph);
            }
        }
        reader.close();
        writerTrain.close();
        writerDevel.close();
    }
}

Add a tool to split the training data into train/dev data according to the recommendations in our README.


package com.sunny.grokkingalgorithms.ctc.c2;

import com.sunny.grokkingalgorithms.ctc.c2.util.LinkedListUtil;
import com.sunny.grokkingalgorithms.ctc.c2.util.Node;

/**
 * Created by sundas on 3/15/2018.
 */
public class AddTwoNumbers {

  /*
  Add two numbers represented by linked list
  7->1->6  + 5->9->2
  617 + 295
  912
  stored as 2->1->9
   */

  /**
   *
   * @param numberA
   * @param numberB
   * @return
   */
  public static Node addTwoNumbers(Node numberA,Node numberB){
    Node sumRoot = null;
    int previousCarry = 0;
    Node aRunner = numberA;
    Node bRunner = numberB;
    Node previousDigitNode = null;
    /*
    Assuming that both the linked lists are of same size
     */
    while(aRunner != null && bRunner != null){
      int tempSum = aRunner.data + bRunner.data + previousCarry;
      int currentDigit = tempSum%10;
      previousCarry = tempSum/10;
      Node currentdigitNode = new Node();
      currentdigitNode.data = currentDigit;
      if(sumRoot == null){
        sumRoot = currentdigitNode;
      }
      if(previousDigitNode != null){
        previousDigitNode.next = currentdigitNode;
      }
      previousDigitNode = currentdigitNode;
      aRunner = aRunner.next;
      bRunner = bRunner.next;
    }
    if(previousCarry > 0){
      Node currentDigitNode = new Node();
      currentDigitNode.data = previousCarry;
      if(previousDigitNode != null){
        previousDigitNode.next = currentDigitNode;
      }
    }
    return sumRoot;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[] input = new int[]{7,1,6};
    Node numberA = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberA);
    input = new int[]{5,9,2};
    Node numberB = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberB);
    Node sumRoot = addTwoNumbers(numberA, numberB);
    LinkedListUtil.printLinkedList(sumRoot);
    System.out.println("next.......");
    input = new int[]{7,1,9};
    numberA = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberA);
    input = new int[]{5,9,9};
    numberB = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberB);
    sumRoot = addTwoNumbers(numberA,numberB);
    LinkedListUtil.printLinkedList(sumRoot);

  }

}

Add two numbers represented by linked lists stored in reverse direction.


package org.aslak.github.merge.service;

import java.util.HashSet;
import java.util.Set;

import org.aslak.github.merge.model.PullRequest;

public class PullRequestService {

    private Set<PullRequest> store;

    public PullRequestService() {
        this.store = new HashSet<>();
    }

    public PullRequest locate(String user, String repo, int pull) {
        for(PullRequest request : store) {
            if(
                    request.getSource().getUser().equals(user) &&
                    request.getSource().getRepository().equals(user) &&
                    request.getNumber() == pull) {
                return request;
            }
        }
        return null;
    }

    public void store(PullRequest pullrequest) {
        this.store.add(pullrequest);
    }
}

Add service for storing PullRequest metadata


package com.humbughq.android;

import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.TextView;

class AsyncLogin extends HumbugAsyncPushTask {

    public AsyncLogin(HumbugActivity humbugActivity, String username,
            String password) {
        super(humbugActivity);
        context = humbugActivity;
        this.context.email = username;
        this.setProperty("username", username);
        this.setProperty("password", password);
    }

    public final void execute() {
        execute("api/v1/fetch_api_key");
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {
            this.context.api_key = result.toString();
            Log.i("login", "Logged in as " + this.context.api_key);

            Editor ed = this.context.settings.edit();
            ed.putString("email", this.context.email);
            ed.putString("api_key", this.context.api_key);

            ed.commit();

            this.context.openLogin();
        } else {
            TextView errorText = (TextView) this.context
                    .findViewById(R.id.error_text);
            errorText.setText("Login failed");
        }
    }
}

package com.humbughq.android;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.TextView;

class AsyncLogin extends HumbugAsyncPushTask {

    public AsyncLogin(HumbugActivity humbugActivity, String username,
            String password) {
        super(humbugActivity);
        context = humbugActivity;
        this.context.email = username;
        this.setProperty("username", username);
        this.setProperty("password", password);
    }

    public final void execute() {
        execute("api/v1/fetch_api_key");
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {
            try {
                JSONObject obj = new JSONObject(result);

                if (obj.getString("result").equals("success")) {
                    this.context.api_key = obj.getString("api_key");
                    Log.i("login", "Logged in as " + this.context.api_key);

                    Editor ed = this.context.settings.edit();
                    ed.putString("email", this.context.email);
                    ed.putString("api_key", this.context.api_key);

                    ed.commit();

                    this.context.openLogin();
                    return;
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        TextView errorText = (TextView) this.context
                .findViewById(R.id.error_text);
        errorText.setText("Login failed");
    }
}

Refactor login code to handle JSON return values for api_key method.


package com.ushahidi.android.domain.repository;

import com.ushahidi.android.domain.entity.FormAttribute;
import com.ushahidi.android.domain.entity.From;

import java.util.List;

import rx.Observable;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface FormAttributeRepository {

    /**
     * Get a list of {@link FormAttribute} from either the database or online.
     *
     * @param deploymentId An ID of {@link com.ushahidi.android.domain.entity.Deployment}
     * @param from         Where to get the formattribute from. Either from local storage or online
     * @return The retrieved form attribute.
     */
    Observable<List<FormAttribute>> getForms(Long deploymentId, From from);

    /**
     * Add/Update a {@link FormAttribute}.
     *
     * @param form The FormAttribute to be saved.
     * @return The row affected
     */
    Observable<Long> putForm(FormAttribute form);
}

Add repo for form attribute

Add repo for form attribute


import java.util.Scanner;

/**
 * This program will print "HIRE!" if three of five inputted values are greater than
 * 50, and "REJECT" if not.
 **/
public class Type_Test {
    public static void main(String[] args) {
        int test = 0, count = 0, z;
        Scanner m = new Scanner(System.in);

        // Both conditions must be met
        while (test < 5 && count < 2) {
            System.out.println("Enter test score");
            z = m.nextInt();

            if (z >= 50) {
                count++;
            }
            test++;
        }

        if (count == 2) {
            System.out.println("HIRE!");
        } else {
            System.out.println("REJECT");
        }
    }
}

Add problem 8 to unit 1

Add problem 8 to unit 1


package test.gx.realtime.acceptance;

import gx.realtime.RealtimeLoader;
import gx.realtime.RealtimeOptions;
import org.junit.Test;

/**
 *
 */
public class LoaderTest {
    @Test
    public void testLoader() {
        RealtimeOptions options = new RealtimeOptions();
        options.setAppId("foo");
        options.setClientId("bar");

        options.setOnFileLoaded((document) -> {
            //...
        });

        RealtimeLoader rtLoader = new RealtimeLoader(options);
        rtLoader.start();
    }
}

Add acceptance test for top-level loading.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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 imagej.legacy;

import imagej.patcher.LegacyEnvironment;
import imagej.patcher.LegacyInjector;

/**
 * An interactive test for the legacy mode of ImageJ2.
 *
 * @author Johannes Schindelin
 */
public class TestDrive {

	static {
		LegacyInjector.preinit();
	}

	public static void main(String[] args) throws ClassNotFoundException,
			InterruptedException {
		System.setProperty("ij1.plugin.dirs", "/nirvana/");
		final LegacyEnvironment ij1 = new LegacyEnvironment(null, false);
		ij1.addPluginClasspath(TestDrive.class.getClassLoader());
		ij1.main();
	}
}

Add an interactive test for the legacy mode

This new test lets you start up ImageJ2 in legacy mode, for interactive
playing around and testing. You can execute it with

	mvn exec:java -Dexec.mainClass=imagej.legacy.TestDrive \
		-Dexec.classpathScope=test

or in Eclipse

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package cucumber.eclipse.editor.editors;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.Position;
import org.junit.Test;

public class GherkinModelTest {

    @Test
    public void stepContainerFoldRangeExtendsToNextStepContainer() throws BadLocationException {
        String source = "Feature: x\n"
                + "\n"
                + "  Scenario: 1\n" // line 2
                + "    Given y\n"
                + "\n"
                + "  Scenario: 2\n" // line 5
                + "    Given z\n";
        Document document = new Document(source);
        GherkinModel model = new GherkinModel();

        model.updateFromDocument(document);
        Position range = model.getFoldRanges().get(0);

        assertThat("offset", range.getOffset(), is(document.getLineOffset(2)));
        assertThat("range", range.getLength(), is(document.getLineOffset(5) - document.getLineOffset(2)));
    }

    @Test
    public void examplesFoldRangeExtendsToNextStepContainer() throws BadLocationException {
        String source = "Feature: x\n"
                + "\n"
                + "  Scenario Outline: 1\n"
                + "    Given y\n"
                + "\n"
                + "    Examples:\n" // line 5
                + "      | a | b |\n"
                + "      | 1 | 2 |\n"
                + "\n"
                + "  Scenario: 2\n" // line 9
                + "    Given z\n";
        Document document = new Document(source);
        GherkinModel model = new GherkinModel();

        model.updateFromDocument(document);
        Position range = model.getFoldRanges().get(0);

        assertThat("offset", range.getOffset(), is(document.getLineOffset(5)));
        assertThat("range", range.getLength(), is(document.getLineOffset(9) - document.getLineOffset(5)));
    }
}

Add tests for fold range calculation.

Add tests for fold range calculation.


/*
 * Copyright (c) 2015 Inocybe and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.*;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.ovsdb.plugin.api.Status;
import org.opendaylight.ovsdb.plugin.api.StatusCode;

/**
 * Unit test for {@link AbstractHandler}
 */
public class AbstractHandlerTest {

    @Test
    public void testAbstractHandler() {
        Status status = Mockito.mock(Status.class);

        Mockito.when(status.getCode())
                .thenReturn(StatusCode.BADREQUEST)
                .thenReturn(StatusCode.CONFLICT)
                .thenReturn(StatusCode.NOTACCEPTABLE)
                .thenReturn(StatusCode.NOTFOUND)
                .thenReturn(StatusCode.GONE);

        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_BAD_REQUEST,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_CONFLICT,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_NOT_ACCEPTABLE,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_NOT_FOUND,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_INTERNAL_ERROR,
                AbstractHandler.getException(status));
    }
}

Add JUnit testing for AbstractHandler class.

Change-Id: If172dff7ad5d98a6cabdb78a6c4067c3327e1f10
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


package com.denver.citiestate.utils;

import com.denver.citiestate.interfaces.Listable;
import com.denver.citiestate.pojo.ListHouse;

public class SortedList extends List {

	/**
	 *
	 * @param maxSpace
	 */
	public SortedList(int maxSpace) {
		super(maxSpace);
	}

}

Add Sorted List class with an overloaded constructor


package de.retest.recheck.ignore;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

import java.nio.file.Paths;

import org.junit.jupiter.api.Test;

import de.retest.recheck.ui.Path;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.MutableAttributes;
import de.retest.recheck.ui.diff.AttributeDifference;

class ContentFilterIT {

	@Test
	void should_filter_img_src_and_alt_diffs() throws Exception {
		final Filter filter = FilterLoader.load( Paths.get( "src/main/resources/filter/web/content.filter" ) ).load();

		final Element element = Element.create( "retestId", mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/html[1]/img[1]" ), "img" ),
				new MutableAttributes().immutable() );
		final AttributeDifference srcDiff =
				new AttributeDifference( "src", "https://old/img.jpg", "https://new/img.jpg" );
		final AttributeDifference altDiff = new AttributeDifference( "alt", "A house.", "A dog." );
		final AttributeDifference clipDiff = new AttributeDifference( "clip", "bla", "blub" );

		assertThat( filter.matches( element ) ).isFalse();
		assertThat( filter.matches( element, srcDiff ) ).isTrue();
		assertThat( filter.matches( element, altDiff ) ).isTrue();
		assertThat( filter.matches( element, clipDiff ) ).isFalse();
	}

	@Test
	void should_filter_text_diffs() throws Exception {
		final Filter filter = FilterLoader.load( Paths.get( "src/main/resources/filter/web/content.filter" ) ).load();

		final Element element = Element.create( "retestId", mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/html[1]/p[1]" ), "p" ),
				new MutableAttributes().immutable() );
		final AttributeDifference textDiff = new AttributeDifference( "text", "An ancient text.", "A hip new text." );
		final AttributeDifference otherDiff = new AttributeDifference( "alt", "A house.", "A dog." );

		assertThat( filter.matches( element ) ).isFalse();
		assertThat( filter.matches( element, textDiff ) ).isTrue();
		assertThat( filter.matches( element, otherDiff ) ).isFalse();
	}
}

Add some test for the filters...

Add some test for the filters...


/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig 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 the following location:
 *
 *   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.jasig.cas.adaptors.ldap.lppe.ad;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.LoginException;

import org.jasig.cas.authentication.AccountDisabledException;
import org.jasig.cas.authentication.AccountPasswordMustChangeException;
import org.jasig.cas.authentication.InvalidLoginLocationException;
import org.jasig.cas.authentication.InvalidLoginTimeException;
import org.junit.Test;

/**
 * Unit test for {@link org.jasig.cas.adaptors.ldap.lppe.ad.ActiveDirectoryAccountState}.
 *
 * @author Misagh Moayyed
 * @since 4.0
 */
public class ActiveDirectoryAccountStateTests {

    @Test(expected=InvalidLoginTimeException.class)
    public void testAccountStateLoginTime() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_LOGON_HOURS);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountDisabledException.class)
    public void testAccountStateDisabled() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_DISABLED);
        state.getError().throwSecurityException();
    }

    @Test(expected=InvalidLoginLocationException.class)
    public void testAccountStateInvalidLocation() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_WORKSTATION);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountPasswordMustChangeException.class)
    public void testAccountStatePswMustChange() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.PASSWORD_MUST_CHANGE);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountLockedException.class)
    public void testAccountStateNormalException() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_LOCKED_OUT);
        state.getError().throwSecurityException();
    }
}

Test case for account state detection in AD


package internal.org.springframework.content.solr;

import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.Describe;
import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.It;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.content.commons.operations.ContentOperations;
import org.springframework.content.solr.EnableFullTextSolrIndexing;
import org.springframework.content.solr.SolrConfig;
import org.springframework.content.solr.SolrIndexer;
import org.springframework.content.solr.SolrProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.convert.ConversionService;
import org.springframework.test.context.ContextConfiguration;

import com.github.paulcwarren.ginkgo4j.Ginkgo4jSpringRunner;

@RunWith(Ginkgo4jSpringRunner.class)
@ContextConfiguration(classes=EnableFullTextSolrIndexingTest.TestConfiguration.class)
public class EnableFullTextSolrIndexingTest {

	@Autowired private ApplicationContext context;

	{
		Describe("EnableFullTextSolrIndexing", () -> {
			It("should have a SolrProperties bean", () -> {
				assertThat(context.getBean(SolrProperties.class), is(not(nullValue())));
			});
			It("should have a SolrIndexer bean", () -> {
				assertThat(context.getBean(SolrIndexer.class), is(not(nullValue())));
			});
		});
	}

	@Configuration
	@EnableFullTextSolrIndexing
	@Import(ContentStoreConfiguration.class)
	public static class TestConfiguration {

		@Bean
	    public SolrClient solrClient() {
	        SolrClient sc = new HttpSolrClient("http://some/url");
	        return sc;
	    }

	}

	public static class ContentStoreConfiguration {

		// Infrastructure bean - would usually be supplied by a content store implementation
		@Bean
		public ContentOperations contentOperations() {
			return mock(ContentOperations.class);
		}

		// Developer bean - would usually be supplied by app developer
		@Bean
		public ConversionService conversionService() {
			return mock(ConversionService.class);
		}

	}

	@Test
	public void noop() {
	}

}

Add solr enablement annotation test

Add solr enablement annotation test


/**
 * @copyright
 * ====================================================================
 *    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.
 * ====================================================================
 * @endcopyright
 */

package org.apache.subversion.javahl.types;

public class Checksum implements java.io.Serializable
{
    // Update the serialVersionUID when there is a incompatible change
    // made to this class.  See any of the following, depending upon
    // the Java release.
    // http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/version.doc7.html
    // http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf
    // http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678
    // http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678
    private static final long serialVersionUID = 1L;

    /**
     * Constructor to be called from the native code
     * @param digest            bytes of the digest
     * @param kind              kind of checksum
     */
    public Checksum(byte[] digest, Kind kind)
    {
        this.digest = digest;
        this.kind = kind;
    }

    /** Digest of the checksum */
    private byte[] digest;

    /** Kind of the Checksum */
    private Kind kind;

    /**
     * Retrieve the digest
     * @return  the digest
     */
    public byte[] getDigest()
    {
        return digest;
    }

    /**
     * Retrieve the kind
     * @return  the kind
     */
    public Kind getKind()
    {
        return kind;
    }

    /**
     * Kinds of checksum
     */
    public enum Kind
    {
        MD5,
        SHA1;
    }
}

Add file missed in r1098736.

Add file missed in r1098736.

* subversion/bindings/javahl/src/org/apache/subversion/javahl/types/Checksum.java: New.


package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005;

import com.google.common.net.InetAddresses;

/**
 **/
public final class PceIdBuilder {
	private PceIdBuilder() {

	}

	/**
	 * Construct a new PCE ID, from either an IPv4 or IPv6 form.
	 *
	 * @param defaultValue Which is a PCE-ID in string form
	 * @return A PCE ID.
	 */
	public static PceId getDefaultInstance(final String defaultValue) {
		return new PceId(InetAddresses.forString(defaultValue).getAddress());
	}
}

Implement PCE ID union type builder

Implement PCE ID union type builder

Change-Id: I7e53b274101feb357dfef67bf3d71148be8f94a8
Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>


/*
 * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.snomed.reasoner.classification;

import java.util.Objects;

import org.eclipse.core.runtime.jobs.ISchedulingRule;

import com.b2international.snowowl.datastore.remotejobs.SerializableSchedulingRule;

/**
 * @since 7.0
 */
public final class ClassificationSchedulingRule implements SerializableSchedulingRule {

	private static int nextId = 0;

	private final int id;
	private final String repositoryId;
	private final String branch;

	public static ClassificationSchedulingRule create(final int concurrentClassifications, final String repositoryId, final String branch) {
		return new ClassificationSchedulingRule((++nextId % concurrentClassifications), repositoryId, branch);
	}

	private ClassificationSchedulingRule(final int id, final String repositoryId, final String branch) {
		this.id = id;
		this.repositoryId = repositoryId;
		this.branch = branch;
	}

	@Override
	public boolean contains(final ISchedulingRule rule) {
		return equals(rule);
	}

	@Override
	public boolean isConflicting(final ISchedulingRule rule) {
		if (getClass() != rule.getClass()) { return false; }
		final ClassificationSchedulingRule other = (ClassificationSchedulingRule) rule;

		// If the IDs are the same, the number of concurrent classifications limit has been reached
		if (id == other.id) { return true; }

		// Otherwise, both branch and repositoryId must match for a conflict
		if (!Objects.equals(branch, other.branch)) { return false; }
		if (!Objects.equals(repositoryId, other.repositoryId)) { return false; }

		return true;
	}

	@Override
	public int hashCode() {
		return Objects.hash(id, branch, repositoryId);
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) { return true; }
		if (obj == null) { return false; }
		if (getClass() != obj.getClass()) { return false; }

		final ClassificationSchedulingRule other = (ClassificationSchedulingRule) obj;
		if (id != other.id) { return false; }
		if (!Objects.equals(branch, other.branch)) { return false; }
		if (!Objects.equals(repositoryId, other.repositoryId)) { return false; }

		return true;
	}
}

[reasoner] Add scheduling rule implementation for classification jobs


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */
package org.geomajas.plugin.editing.jsapi.example.server.command;

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

import org.geomajas.command.Command;
import org.geomajas.geometry.Coordinate;
import org.geomajas.geometry.Geometry;
import org.geomajas.global.ExceptionCode;
import org.geomajas.global.GeomajasException;
import org.geomajas.plugin.editing.jsapi.example.dto.GetCentroidRequest;
import org.geomajas.plugin.editing.jsapi.example.dto.GetCentroidResponse;
import org.geomajas.service.DtoConverterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.vividsolutions.jts.geom.Point;

/**
 * <p>
 * This command calculates the centroid of the given geometries.
 * </p>
 *
 * @author Pieter De Graef
 */
@Component
public class GetCentroidCommand implements Command<GetCentroidRequest, GetCentroidResponse> {

	@Autowired
	private DtoConverterService converter;

	public GetCentroidResponse getEmptyCommandResponse() {
		return new GetCentroidResponse();
	}

	public void execute(GetCentroidRequest request, GetCentroidResponse response) throws Exception {
		if (request.getGeometries() == null || request.getGeometries().size() == 0) {
			throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "request");
		}

		Map<Geometry, Coordinate> centroids = new HashMap<Geometry, Coordinate>(request.getGeometries().size());
		for (Geometry geometry : request.getGeometries()) {
			com.vividsolutions.jts.geom.Geometry jtsGeom = converter.toInternal(geometry);
			Point centroid = jtsGeom.getCentroid();
			centroids.put(geometry, new Coordinate(centroid.getX(), centroid.getY()));
		}

		response.setCentroids(centroids);
	}
}

GEP-27: Create a showcase application that demonstrates the JavaScript API of the editing plugin.


/****************************************************************
 * 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.james.api.imap.message.request;

import org.apache.james.api.imap.ImapCommand;

public interface ImapRequest {

	/**
	 * Gets the IMAP command whose execution is requested by the client.
	 * @return ImapCommand, not null
	 */
	public abstract ImapCommand getCommand();

	/**
	 * Gets the prefix tag identifying this request.
	 * @return the tag identifying the client request, not null
	 */
	public abstract String getTag();

}

Move in other API elements.

Move in other API elements.

git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@546285 13f79535-47bb-0310-9956-ffa450edef68


package Reaction;

import Pair.Pair;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

import java.util.ArrayList;

public class ReactionDBWriterTest {

    Pair pair0 = createPair("UNIQUE-ID", "ANDELA-FELLOW");
    Pair pair1 = createPair("TYPES", "OMOTOSO");
    Pair pair2 = createPair("COMMON-NAME", "FEMALE");
    Pair pair3 = createPair("ATOM-MAPPINGS", "ANDELA");
    Pair pair4 = createPair("IN-PATHWAY", "10");

    ReactionDBWriter reactionDBWriter;
    Reaction reaction;

    public Pair<String, ArrayList<String>> createPair(String key, String value) {
        ArrayList<String> values = new ArrayList<>();
        values.add(value);
        return new Pair<>(key, values);
    }

    public void populatePairList(){
        reaction.add(pair0);
        reaction.add(pair1);
        reaction.add(pair2);
        reaction.add(pair3);
        reaction.add(pair4);
    }

    @Before
    public void setUp() throws Exception {
        reactionDBWriter = new ReactionDBWriter();
        reaction = new Reaction();
        populatePairList();
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testConnectToReactionDatabase() throws Exception {
        reactionDBWriter.connectToReactionDatabase();
        assertTrue(reactionDBWriter.isConnected());
    }

    @Test
    public void testCreateReactionTable() throws Exception {
        testConnectToReactionDatabase();
        reactionDBWriter.createReactionTable();
    }

    @Test
    public void testWriteReactionToDatabase() throws Exception {
        testConnectToReactionDatabase();
        testCreateReactionTable();
        reactionDBWriter.writeReactionToDatabase(reaction);
        reactionDBWriter.disconnect();
        assertFalse(reactionDBWriter.isConnected());
    }
}

Add Test to fail ReactionDBWriter class

Add Test to fail ReactionDBWriter class


package com.github.aureliano.verbum_domini.helper;

import com.github.aureliano.verbum_domini.core.bean.IBean;
import com.github.aureliano.verbum_domini.core.impl.dao.DaoFactory;

public final class ServiceHelper {

	private ServiceHelper() {
		super();
	}

	public static boolean exist(Class<? extends IBean> type, String id) {
		if (!id.matches("\\d+")) {
			return false;
		}

		return DaoFactory.createDao(type).exist(Integer.parseInt(id));
	}
}

Use fast method to verify entity existence.


package nl.next35.logic;

import nl.next35.domain.Post;
import nl.next35.domain.User;

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

/**
 * @author Lesley
 */
public final class ResolverChain {

    private final List<Resolver> resolvers = new ArrayList<>();

    public List<Post> resolve(User user) {
        List<Post> posts = new ArrayList<>();

        resolvers.stream().map(r -> r.getPosts(user)).forEach(posts::addAll);

        return posts;
    }

    public void add(Resolver resolver) {
        resolvers.add(resolver);
    }

    public void remove(Resolver resolver) {
        resolvers.remove(resolver);
    }

}

Add class that can take up multiple resolvers.