/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2016 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 org.scijava.command.run;

import org.scijava.command.Command;
import org.scijava.command.CommandInfo;
import org.scijava.command.CommandService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginService;
import org.scijava.run.AbstractClassRunner;
import org.scijava.run.ClassRunner;

/**
 * Runs the given {@link Command} class.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ClassRunner.class)
public class CommandRunner extends AbstractClassRunner {

	@Parameter
	private PluginService pluginService;

	@Parameter
	private CommandService commandService;

	// -- ClassRunner methods --

	@Override
	public void run(final Class<?> c) {
		@SuppressWarnings("unchecked")
		final Class<? extends Command> commandClass =  (Class<? extends Command>) c;
		final Plugin annotation = c.getAnnotation(Plugin.class);
		final CommandInfo info = new CommandInfo(commandClass, annotation);
		pluginService.addPlugin(info);
		commandService.run(info, true);
	}

	// -- Typed methods --

	@Override
	public boolean supports(final Class<?> c) {
		return Command.class.isAssignableFrom(c);
	}

}

Add a ClassRunner for Command plugins

Add a ClassRunner for Command plugins

Migrated from the CommandJavaRunner of scijava/scripting-java.


/**
 *
 * Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
 *
 * 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.speedment.common.mutablestream.internal.source;

import com.speedment.common.mutablestream.HasNext;
import com.speedment.common.mutablestream.action.Action;
import com.speedment.common.mutablestream.terminate.Terminator;
import static java.util.Objects.requireNonNull;
import java.util.stream.BaseStream;

/**
 *
 * @param <T>  the streamed type (or wrapper)
 * @param <TS> the stream type
 *
 * @author Emil Forslund
 * @since  1.0.0
 */
public final class WrappedStream<T, TS extends BaseStream<T, TS>>
implements HasNext<T, TS> {

    private final TS wrapped;

    public WrappedStream(TS wrapped) {
        this.wrapped = requireNonNull(wrapped);
    }

    @Override
    public <Q, QS extends BaseStream<Q, QS>> HasNext<Q, QS>
    append(Action<T, TS, Q, QS> next) {
        return next;
    }

    @Override
    public <X> X execute(Terminator<T, TS, X> terminator) {
        return terminator.execute();
    }

    @Override
    public TS build(boolean parallel) {
        return parallel ? wrapped.parallel() : wrapped;
    }
}

mutablestream: Add source that wraps an existing stream


package com.orientechnologies.orient.core.sql.executor;

import com.orientechnologies.orient.core.db.*;
import com.orientechnologies.orient.core.metadata.security.OSecurityInternal;
import com.orientechnologies.orient.core.metadata.security.OSecurityPolicy;
import org.junit.*;

/**
 * @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com)
 */
public class OAlterSecurityPolicyStatementExecutionTest {
  static OrientDB orient;
  private ODatabaseSession db;

  @BeforeClass
  public static void beforeClass() {
    orient = new OrientDB("plocal:.", OrientDBConfig.defaultConfig());
  }

  @AfterClass
  public static void afterClass() {
    orient.close();
  }

  @Before
  public void before() {
    orient.create("test", ODatabaseType.MEMORY);
    this.db = orient.open("test", "admin", "admin");
  }

  @After
  public void after() {
    this.db.close();
    orient.drop("test");
    this.db = null;
  }

  @Test
  public void testPlain() {
    db.command("CREATE SECURITY POLICY foo").close();

    db.command("ALTER SECURITY POLICY foo SET READ = (name = 'foo')").close();

    OSecurityInternal security = ((ODatabaseInternal) db).getSharedContext().getSecurity();
    OSecurityPolicy policy = security.getSecurityPolicy((ODatabaseSession) db, "foo");
    Assert.assertNotNull(policy);
    Assert.assertNotNull("foo", policy.getName());
    Assert.assertEquals("name = 'foo'", policy.getReadRule().toString());
    Assert.assertNull(policy.getCreateRule());
    Assert.assertNull(policy.getBeforeUpdateRule());
    Assert.assertNull(policy.getAfterUpdateRule());
    Assert.assertNull(policy.getDeleteRule());
    Assert.assertNull(policy.getExecuteRule());

    db.command("ALTER SECURITY POLICY foo REMOVE READ").close();

    policy = security.getSecurityPolicy((ODatabaseSession) db, "foo");
    Assert.assertNotNull(policy);
    Assert.assertNull(policy.getReadRule());

  }

}

Add test case for ALTER SECURITY POLICY statement


package de.asw.courses.web2016.demo.backend.servlet.handoff;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/handoff/eingabe")
public class EingabeServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		System.out.printf("Running in %s%n", getClass().getSimpleName());

		Integer a = Integer.valueOf(req.getParameter("a"));
		Integer b = Integer.valueOf(req.getParameter("b"));

		req.setAttribute("a", a);
		req.setAttribute("b", b);

		RequestDispatcher rd = req.getRequestDispatcher("/handoff/verarbeitung");
		rd.forward(req, resp);
	}
}

Add bootstrap for handoff example

Add bootstrap for handoff example


/***
 *
 * Copyright 2014 Andrew Hall
 *
 * 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.statefulj.framework.tests.controllers;

import org.statefulj.framework.core.annotations.StatefulController;
import org.statefulj.framework.core.annotations.Transition;
import org.statefulj.framework.tests.model.User;
import static org.statefulj.framework.tests.model.User.*;

@StatefulController(
	value="overloadedMethodController",
	clazz=User.class,
	startState=ONE_STATE
)
public class OverloadedMethodController {

	@Transition(event="one")
	public String method(User user, String event) {
		return "method1";
	}

	@Transition(event="two")
	public String method(User user, String event, Object parm) {
		return "method2";
	}

}

Add test case for overloaded methods

Add test case for overloaded methods


/*
 *
 * 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.airavata.wsmg.commons;

import javax.xml.namespace.QName;

public class MsgBoxQNameConstants {

    public static final QName MSG_BOXID_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "MsgBoxId", "msgbox");
    public static final QName MSGBOX_STATUS_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "status", "msgbox");
    public static final QName MSGBOX_MESSAGE_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "messages", "msgbox");

    /*
     * Request
     */
    public static final QName STOREMSG_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "storeMessages", "msgbox");
    public static final QName DESTROYMSG_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "destroyMsgBox", "msgbox");
    public static final QName TAKEMSGS_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "takeMessages", "msgbox");
    public static final QName CREATEMSG_BOX = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/", "createMsgBox",
            "msgbox");

    /*
     * Response
     */
    public static final QName STOREMSG_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "storeMessagesResponse", "msgbox");
    public static final QName DESTROY_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "destroyMsgBoxResponse", "msgbox");
    public static final QName CREATE_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "createMsgBoxResponse", "msgbox");
    public static final QName TAKE_MSGBOX_RESP_QNAME = new QName("http://org.apache.airavata/ws-messenger/msgbox/2011/",
            "takeMessagesResponse", "msgbox");
}

Add missing class in previous commit

Add missing class in previous commit

git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1174524 13f79535-47bb-0310-9956-ffa450edef68


package org.jrebirth.af.core.wave;

/**
 * The class DefaultWaveListener is the default empty implementation.
 *
 * You can use it as base class to only override the method you need.
 *
 * @author Sébastien Bordes
 */
public class DefaultWaveListener implements WaveListener {

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCreated(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveSent(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveProcessed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCancelled(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveConsumed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveFailed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveDestroyed(Wave wave) {
        // Nothing to do yet
    }

}

Add default implementation of wave listener


package de.lmu.ifi.dbs.elki.logging.statistics;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import de.lmu.ifi.dbs.elki.utilities.FormatUtil;

/**
 * Trivial double-valued statistic.
 *
 * @author Erich Schubert
 */
public class DoubleStatistic extends AbstractStatistic {
  /**
   * Statistic value.
   */
  double value;

  /**
   * Constructor.
   *
   * @param key Key
   */
  public DoubleStatistic(String key) {
    super(key);
  }

  /**
   * Constructor.
   *
   * @param key Key
   * @param value Value
   */
  public DoubleStatistic(String key, double value) {
    super(key);
    this.value = value;
  }

  /**
   * Set the statistics.
   *
   * @param value New value
   */
  public void setDouble(double value) {
    this.value = value;
  }

  @Override
  public String formatValue() {
    return FormatUtil.format(value, FormatUtil.NF8);
  }
}

Add class for double-valued statistics

Add class for double-valued statistics


package sc.iview.commands.edit;

import org.scijava.command.Command;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import sc.iview.SciView;

import static sc.iview.commands.MenuWeights.*;

/**
 * A command for interactively editing input controls.
 * @author Vladimir Ulman
 */
@Plugin(type = Command.class, menuRoot = "SciView",
        menu = { @Menu(label = "Edit", weight = EDIT), @Menu(label = "Inputs Bindings", weight = EDIT_SCIVIEW_SETTINGS+2) })
public class InputBindingsSettings implements Command
{
    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        sciView.publicGetInputHandler().openKeybindingsGuiEditor( "SciView's Key bindings editor" );
    }
}

ADD: Edit -> Inputs Bindings menu item that shows publicGetInputHandler().openKeybindingsGuiEditor()


package seedu.taskmanager.logic.commands;

import java.io.IOException;
import java.util.Optional;

import seedu.taskmanager.commons.core.Config;
import seedu.taskmanager.commons.exceptions.DataConversionException;
import seedu.taskmanager.commons.util.ConfigUtil;
import seedu.taskmanager.commons.util.StringUtil;
import seedu.taskmanager.logic.commands.exceptions.CommandException;

/**
 * @@author A0114269E
 * Move the directory of taskmanager.xml file to user-specified path to allow cloud service sync.
 * Overwrite the given file path if a file with same name exists. Old XML file is not deleted.
 * Path matching is case sensitive.
 */
public class MoveCommand extends Command {
    public static final String COMMAND_WORD = "mv";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Move the directory of the taskmanager."
            + "xml file to allow user to sync with cloud services. Overwrite will occur for same file name.\n"
            + "Parameters: PATH...\n"
            + "Example: " + COMMAND_WORD + " /User/admin/Documents/taskmanager.xml";

    public static final String MESSAGE_SUCCESS = "TaskManager directory moved to : ";
    public static final String MESSAGE_ERROR_BUILDCONFIG = "Failed to build new config";
    public static final String MESSAGE_ERROR_SAVECONFIG = "Failed to save config file : '%1$s'";

    private final String newPath;

    public MoveCommand(String path) {
        this.newPath = path;
    }

    @Override
    public CommandResult execute() throws CommandException {
        Config newConfig;
        String configFilePathUsed;

        configFilePathUsed = Config.DEFAULT_CONFIG_FILE;

        try {
            Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
            newConfig = configOptional.orElse(new Config());
        } catch (DataConversionException e) {
            throw new CommandException(MESSAGE_ERROR_BUILDCONFIG);
        }

        newConfig.setTaskManagerFilePath(this.newPath);
        storage.updateTaskManagerStorageDirectory(this.newPath, newConfig);

        try {
            ConfigUtil.saveConfig(newConfig, configFilePathUsed);
        } catch (IOException e) {
            throw new CommandException(MESSAGE_ERROR_SAVECONFIG + StringUtil.getDetails(e));
        }

        return new CommandResult(MESSAGE_SUCCESS + this.newPath);
    }
}

Add new move command, a variant of change directory that overwrites given file path


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem48;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class WordSearchTest {

  private WordSearch wordSearch;

  @Before public void setUp() {
    wordSearch = new WordSearch();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullWordSearch() {
    wordSearch.contains(null, "word");
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullWordsToSearchInTheMatrix() {
    wordSearch.contains(new char[0][0], null);
  }

  @Test public void shouldReturnFalseIfWordSearchIsEmpty() {
    char[][] matrix = {
        { 'a', 'a', 'c', 'd', 'e' }, { 'a', 'd', 'a', 'r', 'c' }, { 'a', 'd', 'a', 'c', 'c' },
        { 'b', 'a', 'c', 'o', 'o' }
    };

    boolean result = wordSearch.contains(matrix, "pedro");

    assertFalse(result);
  }

  @Test public void shouldReturnTrueIfWordToSearchIsInsideWordSearch() {
    char[][] matrix = {
        { 'a', 'a', 'c', 'd', 'e' }, { 'a', 'd', 'a', 'r', 'c' }, { 'a', 'd', 'a', 'c', 'c' },
        { 'b', 'a', 'c', 'o', 'o' }
    };

    boolean result = wordSearch.contains(matrix, "baco");

    assertTrue(result);
  }
}

Add some tests to problem 48

Add some tests to problem 48


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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
 *
 *     https://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.
 */

open /*test*/ module de.sormuras.bach /*extends main module descriptor*/ {
  exports de.sormuras.bach;

  requires java.compiler;
  requires java.net.http;

  uses java.util.spi.ToolProvider;

  provides java.util.spi.ToolProvider with
      de.sormuras.bach.BachToolProvider;

  requires org.junit.jupiter;
}

Add "white box" test module descriptor

Add "white box" test module descriptor


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2015 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 org.scijava.io;

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

/**
 * Tests {@link FileHandle}.
 *
 * @author Curtis Rueden
 */
public class FileHandleTest extends DataHandleTest {

	@Override
	public Class<? extends DataHandle<?>> getExpectedHandleType() {
		return FileHandle.class;
	}

	@Override
	public Location createLocation() throws IOException {
		// create and populate a temp file
		final File tmpFile = File.createTempFile("FileHandleTest", "test-file");
		tmpFile.deleteOnExit();
		populateData(new FileOutputStream(tmpFile));
		return new FileLocation(tmpFile);
	}

}

Add unit tests for FileHandle

Add unit tests for FileHandle


package org.mutabilitydetector.blogexamples;

public class MutableMischief extends Immutable {

    @Override
    public String getLabel() {
        return "Return value keeps changing: " + (System.currentTimeMillis() % 10);
    }

    public static void main(String args[]) throws Exception {
        MutableMischief mutObj = new MutableMischief();
        ImmutableClient immutClient = new ImmutableClient(mutObj);
        System.out.println(immutClient.printImmutableLabel());
        Thread.sleep(1000);
        System.out.println(immutClient.printImmutableLabel());
    }
}

class Immutable {
    private String label = "Original Label";

    public String getLabel() {
        return label;
    }
}

class ImmutableClient {

    Immutable immutObj;

    ImmutableClient(Immutable immut) {
        this.immutObj = immut;
    }

    public String printImmutableLabel() {
        return immutObj.getLabel();
    }

}

Add code snippets from blog discussion.

Add code snippets from blog discussion.

git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@648 c7a0535c-eda6-11de-83d8-6d5adf01d787


package fr.free.nrw.commons;

import static org.hamcrest.CoreMatchers.is;

import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.utils.LengthUtils;

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

public class LengthUtilsTest {
    @Test public void testZeroDistance() {
        LatLng pointA = new LatLng(0, 0);
        LatLng pointB = new LatLng(0, 0);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("0m"));
    }

    @Test public void testOneDegreeOnEquator() {
        LatLng pointA = new LatLng(0, 0);
        LatLng pointB = new LatLng(0, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("111.2km"));
    }

    @Test public void testOneDegreeFortyFiveDegrees() {
        LatLng pointA = new LatLng(45, 0);
        LatLng pointB = new LatLng(45, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("78.6km"));
    }

    @Test public void testOneDegreeSouthPole() {
        LatLng pointA = new LatLng(-90, 0);
        LatLng pointB = new LatLng(-90, 1);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("0m"));
    }

    @Test public void testPoleToPole() {
        LatLng pointA = new LatLng(90, 0);
        LatLng pointB = new LatLng(-90, 0);
        String distance = LengthUtils.formatDistanceBetween(pointA, pointB);
        Assert.assertThat(distance, is("20,015.1km"));
    }
}

Add some tests for the LengthUtils class

Currently the LengthUtils class has no tests. This commit
adds some basic tests for the distance computations.


class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; next = null;}
}

public class RemoveNthFromEnd {
    /**
    * Given a linked list, remove the nth node from the end of list and return its head.
    */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode nPrev = head;
        ListNode current = head;
        // to keep track of node previous to nth from the end
        int count = n + 1;
        // if no elements in list
        if (head == null) return null;
        // if n == 0, no node needs to be deleted
        if (n == 0) return head;
        while (current != null) {
            current = current.next;
            if (count == 0) nPrev = nPrev.next;
            else count--;
        }
        if (count == 0) nPrev.next = nPrev.next.next;
        // if the node is the head
        if (count == 1) head = head.next;
        return head;
    }

    public ListNode append (ListNode head, int val) {
        if (head == null) return new ListNode (val);
        ListNode cur = head;
        while (cur.next != null) cur = cur.next;
        ListNode newNode = new ListNode (val);
        cur.next = newNode;
        return head;
    }

    public String printList (ListNode head) {
        StringBuilder result = new StringBuilder ();
        while (head != null) {
            result.append (head.val + " ");
            head = head.next;
        }
        return result.toString();
    }

    public static void main (String[] args) {
        RemoveNthFromEnd test = new RemoveNthFromEnd ();
        ListNode head1 = new ListNode (1);
//         test.append (head1, 2);
//         test.append (head1, 3);
//         test.append (head1, 4);
//         test.append (head1, 5);
        head1 = test.removeNthFromEnd (head1, 1);
        System.out.println(test.printList (head1));
    }
}

Remove nth node from end of list

Remove nth node from end of list


package db.migration;

import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by emma on 06/04/2016.
 *
 * @author emma
 *         <p>
 *         Copy OR and DESCRIPTION values to BETA_NUM, BETA_UNIT and BETA_DIRECTION in ASSOCIATION table
 */
public class V2_1_2_012__Migrate_or_to_beta_for_non_standard_unit_case_02 implements SpringJdbcMigration {

    // Query to find beta associations with a description that can be fit into a beta unit and direction
    private static final String SELECT_ASSOCIATIONS =
            "SELECT ID, OR_PER_COPY_NUM, DESCRIPTION FROM ASSOCIATION \n" +
                    "WHERE OR_TYPE = 0 \n" +
                    "AND DESCRIPTION IS NOT NULL  \n" +
                    "AND OR_PER_COPY_NUM IS NOT NULL \n" +
                    "AND (DESCRIPTION  LIKE 'increase' OR DESCRIPTION LIKE 'decrease')";

    private static final String UPDATE_ASSOCIATION =
            "UPDATE ASSOCIATION SET BETA_NUM = ?, BETA_UNIT = ? , BETA_DIRECTION= ? , OR_PER_COPY_NUM=?, DESCRIPTION=? WHERE ID = ?";

    @Override
    public void migrate(JdbcTemplate jdbcTemplate) throws Exception {

        jdbcTemplate.query(SELECT_ASSOCIATIONS, (resultSet, i) -> {
            Long id = resultSet.getLong(1);
            float betaNum = resultSet.getFloat(2);
            String direction = resultSet.getString(3).trim();

            // Run update
            jdbcTemplate.update(UPDATE_ASSOCIATION, betaNum, null, direction, null, null, id);
            return null;
        });
    }
}

Migrate associations with a description that just contains string increase or decrease


package com.orientechnologies.orient.distributed.impl.coordinator.network;

import com.orientechnologies.orient.distributed.impl.log.OLogId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class ONetworkConfirmTest {

  @Test
  public void testSerialize() throws IOException {
    OLogId oplogId = new OLogId(10, 20, 19);
    ONetworkConfirm ack = new ONetworkConfirm(oplogId);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    ack.write(out);
    byte[] serialized = baos.toByteArray();
    out.close();
    baos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    DataInputStream in = new DataInputStream(bais);

    ONetworkConfirm ack2 = new ONetworkConfirm();
    ack2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(ack.getCommand(), ack2.getCommand());
    Assert.assertEquals(ack.getId(), ack2.getId());
  }
}

Add serialization tests for ONetworkConfirm


package org.traccar.protocol;

import org.junit.Assert;
import org.junit.Test;
import org.traccar.ProtocolTest;

public class Gt06FrameDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        Gt06FrameDecoder decoder = new Gt06FrameDecoder();

        Assert.assertEquals(
                binary("78780d010352887071911998000479d00d0a"),
                decoder.decode(null, null, binary("78780d010352887071911998000479d00d0a")));

        Assert.assertEquals(
                binary("78782516000000000000c000000000000000000020000900fa0210ef00fb620006640301000468030d0a"),
                decoder.decode(null, null, binary("78782516000000000000c000000000000000000020000900fa0210ef00fb620006640301000468030d0a")));

    }

}

Add unit tests for GT06 frame decoder

Add unit tests for GT06 frame decoder


/*
 * 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.stratos.cloud.controller.functions;

import org.apache.stratos.cloud.controller.pojo.MemberContext;
import org.apache.stratos.kubernetes.client.model.Pod;
import com.google.common.base.Function;

/**
 * Is responsible for converting a {@link Pod} object to a
 * {@link MemberContext} Object.
 */
public class PodToMemberContext implements Function<Pod, MemberContext> {

    @Override
    public MemberContext apply(Pod pod) {

        if (pod == null) {
            return null;
        }
        MemberContext memberContext = new MemberContext();
        memberContext.setMemberId(pod.getId());
        memberContext.setPrivateIpAddress(pod.getCurrentState().getHostIP());
        memberContext.setPublicIpAddress(pod.getCurrentState().getHostIP());

        return memberContext;
    }

}

Convert a Pod object to a MemberContext

Convert a Pod object to a MemberContext


/*
 * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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.wso2.carbon.identity.oidc.session.cache;

import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.oidc.session.servlet.TestUtil;

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

/**
 * Unit test coverage for OIDCSessionDataCache class.
 */
public class OIDCSessionDataCacheTest {

    @Test
    public void testGetInstance() {

        assertNotNull(OIDCSessionDataCache.getInstance(), "OIDCSessionDataCache is null.");
    }

    @Test
    public void testAddToCache() {

        TestUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        OIDCSessionDataCacheKey key = mock(OIDCSessionDataCacheKey.class);
        OIDCSessionDataCacheEntry entry = mock(OIDCSessionDataCacheEntry.class);
        OIDCSessionDataCache.getInstance().addToCache(key, entry);
        assertNotNull(OIDCSessionDataCache.getInstance().getValueFromCache(key),
                "OIDCSessionDataCache is null.");
    }

    @Test
    public void testClearCacheEntry() {

        TestUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        OIDCSessionDataCacheKey key = mock(OIDCSessionDataCacheKey.class);
        OIDCSessionDataCache.getInstance().clearCacheEntry(key);
        assertNull(OIDCSessionDataCache.getInstance().getValueFromCache(key),
                "OIDCSessionDataCache is not null.");
    }
}

Add unit test for OIDCSessionDataCache

Add unit test for OIDCSessionDataCache


package com.samovich.cs6310;

/**
 * Filename StringSemantic
 * Created by Valery Samovich
 * Written on 1/15/17
 */
public class StringSemantic {

    public static void main(String[] args) {

        // variables
        String s = "foo";
        System.out.println(s);
        System.out.println("");

        System.out.println("1st example:");
        // 1st example
        if (s.equals("foo")){
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }
        System.out.println("");

        System.out.println("2nd example:");
        // 2nd example
        if ("foo".equals(s)){
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }

    }
}

Add example with semantic difference for string


package com.javarush.test.level05.lesson12.home03;

/* Создай классы Dog, Cat, Mouse
Создай классы Dog, Cat, Mouse. Добавь по три поля в каждый класс, на твой выбор. Создай объекты для героев мультика Том и Джерри. Так много, как только вспомнишь.
Пример:
Mouse jerryMouse = new Mouse(“Jerry”, 12 , 5), где 12 - высота в см, 5 - длина хвоста в см.
*/

public class Solution
{
    public static void main(String[] args)
    {
        Mouse jerryMouse = new Mouse("Jerry", 12 , 5);
        Cat catTom = new Cat("Tom", 15, 8);
        Dog dogBob = new Dog("Bob", 20, 4);

    }

    public static class Mouse
    {
        String name;
        int height;
        int tail;

        public Mouse(String name, int height, int tail)
        {
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

    public static class Cat{
        String name;
        int height;
        int tail;

        public Cat(String name, int height, int tail){
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

    public static class Dog{
        String name;
        int height;
        int tail;

        public Dog (String name, int height, int tail){
            this.name = name;
            this.height = height;
            this.tail = tail;
        }
    }

}

Use constructors and access levels

Use constructors and access levels


package leetcode;

/**
 * https://leetcode.com/problems/bitwise-and-of-numbers-range/
 */
public class Problem201 {
    public int rangeBitwiseAnd(int m, int n) {
        return 0;
    }

    public static void main(String[] args) {
        Problem201 prob = new Problem201();
        System.out.println(prob.rangeBitwiseAnd(5, 7)); // 4
    }
}

Create a skeleton for problem 201

Create a skeleton for problem 201


package leetcode;

/**
 * https://leetcode.com/problems/minimum-size-subarray-sum/
 */
public class Problem209 {
    public int minSubArrayLen(int s, int[] nums) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem209 prob = new Problem209();
    }
}

Add a skeleton for problem 209

Add a skeleton for problem 209


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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
 *
 *     https://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 test.base;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.lang.module.ModuleFinder;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;

/** Check code snippets used in {@code src/bach/bach-${NAME}.jsh} scripts. */
class JavaShellScriptTests {

  @Test
  void empty() {
    var module = ModuleFinder.of(Path.of(".bach/lib")).find("de.sormuras.bach");
    assertTrue(module.isEmpty());
  }
}

Add tests for snippets used in JShell-based scripts


package to.etc.domui.pages;

import java.text.*;
import java.util.*;

import javax.annotation.*;

import to.etc.domui.annotations.*;
import to.etc.domui.component.buttons.*;
import to.etc.domui.component.input.*;
import to.etc.domui.dom.html.*;

/**
 * Selenium test date input check page.
 *
 * @author Frits Jalvingh
 * Created on May 27, 2014
 */
public class DateInputTestPage extends UrlPage {
	private boolean m_withtime;

	@Nullable
	private Div m_result;

	@UIUrlParameter(name = "withtime")
	public boolean isWithtime() {
		return m_withtime;
	}

	public void setWithtime(boolean withtime) {
		m_withtime = withtime;
	}

	@Override
	public void createContent() throws Exception {
		final DateInput di = new DateInput(isWithtime());
		add(di);
		di.setTestID("datein");

		DefaultButton	button = new DefaultButton("Click", new IClicked<DefaultButton>() {
			@Override
			public void clicked(DefaultButton clickednode) throws Exception {
				Date dt = di.getValueSafe();
				Div result = m_result;
				if(null == result) {
					m_result = result = new Div();
					add(result);
					result.setTestID("result");
				}
				result.removeAllChildren();
				if(dt == null) {
					result.setText("error");
				} else {
					DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
					result.setText(df.format(dt));
				}
			}
		});
		button.setTestID("btn");
		add(button);

		DefaultButton clear = new DefaultButton("Click", new IClicked<DefaultButton>() {
			@Override
			public void clicked(DefaultButton clickednode) throws Exception {
				di.setValue(null);
				Div result = m_result;
				if(null != result) {
					result.remove();
					m_result = null;
				}
			}
		});
		clear.setTestID("clear");
		add(clear);

	}
}

Add Selenium testable page for testing DateInput.


/*
 * BitmapUtils.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.graphic;

import android.graphics.BitmapFactory;

import com.nkming.utils.Log;
import com.nkming.utils.Res;
import com.nkming.utils.type.Size;

public class BitmapUtils
{
	/**
	 * Return the size of a bitmap without loading the whole file
	 *
	 * @param path
	 * @return
	 */
    public static Size getSize(String path)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(path, options);
        if (options.outWidth == -1 || options.outHeight == -1)
        {
	        Log.e(LOG_TAG + ".getSize", "Failed while decodeFile");
            return null;
        }
        else
        {
            return new Size(options.outWidth, options.outHeight);
        }
    }

	private static final String LOG_TAG = Res.LOG_TAG + "."
			+ BitmapUtils.class.getSimpleName();
}

Add fn to get size of a bitmap without loading


package org.ggp.base.apps.validator;

import org.ggp.base.util.game.CloudGameRepository;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.game.GameRepository;
import org.ggp.base.validator.BasesInputsValidator;
import org.ggp.base.validator.SimulationValidator;
import org.ggp.base.validator.StaticValidator;
import org.ggp.base.validator.GameValidator;
import org.ggp.base.validator.ValidatorException;

/**
 * BatchValidator does game validation on all of the games in a given game repository.
 * This allows you to quickly determine which games need to be repaired, given a large
 * existing game repository with games of varying quality.
 *
 * @author schreib
 */
public final class BatchValidator
{
	public static void main(String[] args)
	{
		GameRepository repo = new CloudGameRepository("games.ggp.org/base");
		for (String gameKey : repo.getGameKeys()) {
			if (gameKey.contains("amazons") || gameKey.contains("quad") || gameKey.contains("blokbox") || gameKey.contains("othello"))
				continue;
			Game game = repo.getGame(gameKey);
			GameValidator[] theValidators = new GameValidator[] {
					new StaticValidator(),
					new BasesInputsValidator(3000),
					new SimulationValidator(300, 10)
			};
			System.out.print(gameKey + " ... ");
			System.out.flush();
			boolean isValid = true;
			for (GameValidator theValidator : theValidators) {
				try {
					theValidator.checkValidity(game);
				} catch (ValidatorException ve) {
					System.out.println("Failed: " + ve);
					isValid = false;
					break;
				}
			}
			if (isValid) {
				System.out.println("Passed!");
			}
		}
	}
}

Add a batch game validator, for cleaning up game repositories.

git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@655 716a755e-b13f-cedc-210d-596dafc6fb9b


import org.junit.Test;

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

public class TempFailingTest {

    @Test
    public void test() {
        fail("This test is failing to reproduce a misconfiguration of our travis ci");
    }

}

Add failing test to reproduce bug

Add failing test to reproduce bug


package fuzion24.device.vulnerability.util;

import android.os.Build;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by fuzion24 on 9/21/15.
 */
public class DeviceInfo {

    private final String kernelVersion;
    private final String buildManufacturer;
    private final String buildBrand;
    private final String buildModel;
    private final String buildRelease;
    private final String buildSDK;
    private final String buildFingerPrint;

    private DeviceInfo(String kVer,
                       String bManufacturer,
                       String bBrand,
                       String bModel,
                       String bRelease,
                       String bSDK,
                       String bFingerPrint){
        this.kernelVersion = kVer;
        this.buildManufacturer = bManufacturer;
        this.buildBrand = bBrand;
        this.buildModel = bModel;
        this.buildRelease = bRelease;
        this.buildSDK = bSDK;
        this.buildFingerPrint = bFingerPrint;
    }

    public static DeviceInfo getDeviceInfo() throws Exception {

        String kVer = readKernelVersion();
        String bManufac = Build.MANUFACTURER;
        String bBrand = Build.BRAND;
        String bModel = Build.MODEL;
        String bRelease = Build.VERSION.RELEASE;
        String bSdk = Build.VERSION.SDK;
        String bFingerPrint = Build.FINGERPRINT;

        return new DeviceInfo(kVer,
                bManufac,
                bBrand,
                bModel,
                bRelease,
                bSdk,
                bFingerPrint
                );
    }

    public static String readKernelVersion() throws Exception {
        final int BUFFER_SIZE = 4098;

        Process p = Runtime.getRuntime().exec("uname -a");
        InputStream is = null;
        if (p.waitFor() == 0) {
            is = p.getInputStream();
        } else {
            is = p.getErrorStream();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is),
                BUFFER_SIZE);
        String line = br.readLine();
        br.close();
        return line;
    }

    public String getKernelVersion() {
        return kernelVersion;
    }

    public String getBuildManufacturer() {
        return buildManufacturer;
    }

    public String getBuildBrand() {
        return buildBrand;
    }

    public String getBuildModel() {
        return buildModel;
    }

    public String getBuildRelease() {
        return buildRelease;
    }

    public String getBuildSDK() {
        return buildSDK;
    }

    public String getBuildFingerPrint() {
        return buildFingerPrint;
    }

}

Add helper class for getting device info


/**
 * 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.trevni;

import java.nio.ByteBuffer;
import java.util.zip.CRC32;

/** Implements CRC32 checksum. */
final class Crc32Checksum extends Checksum {
  private CRC32 crc32 = new CRC32();

  @Override public int size() { return 4; }

  @Override public ByteBuffer compute(ByteBuffer data) {
    crc32.reset();
    crc32.update(data.array(), data.position(), data.remaining());

    ByteBuffer result = ByteBuffer.allocate(size());
    result.putInt((int)crc32.getValue());
    result.flip();
    return result;
 }

}

Add crc32 checksum, checkum tests and a bugfix.


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-20
 * Site       : https://www.acmicpc.net/problem/2739
 */
public class Boj2739 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int i=1; i<10; i++){
            System.out.println(n + " * " + i + " = " + (n*i));
        }
    }

}

Solve No.2739 from Baekjoon Online Judge


package test.unit.haushaltsbuch;

import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import haushaltsbuch.DeleteException;
import haushaltsbuch.Entry;
import haushaltsbuch.EntryRepository;
import haushaltsbuch.InsertException;
import haushaltsbuch.web.controllers.BaseController;
import haushaltsbuch.web.controllers.ListController;
import test.helpers.TestEntry;

public class ListControllerTest extends ListController
{
  private EntryRepository _repository;

  @Before
  public void setUp() throws Exception
  {
    _repository = mock(EntryRepository.class);

    ServletConfig servletConfig = mock(ServletConfig.class);
    ServletContext servletContext = mock(ServletContext.class);

    when(servletConfig.getServletContext()).thenReturn(servletContext);
    when(servletContext.getAttribute(BaseController.CTX_ATTR_NAME)).thenReturn(_repository);

    init(servletConfig);
  }

  @Test
  public void testEmpty() throws ServletException, IOException, DeleteException, InsertException
  {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    List<Entry> all = Collections.emptyList();
    when(_repository.getAll()).thenReturn(all);

    doGet(request, response);

    verify(request).setAttribute(eq("entries"), eq(all));
    verify(request).setAttribute(eq("title"), anyString());
    verify(request).setAttribute(eq("view"), eq("all.jsp"));
  }

  @Test
  public void testSome() throws ServletException, IOException, DeleteException, InsertException
  {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    List<Entry> all = asList(new TestEntry(), new TestEntry());
    when(_repository.getAll()).thenReturn(all);

    doGet(request, response);

    verify(request).setAttribute(eq("entries"), eq(all));
    verify(request).setAttribute(eq("title"), anyString());
    verify(request).setAttribute(eq("view"), eq("all.jsp"));
  }

  private List<Entry> asList(Entry... entries)
  {
    return Arrays.asList(entries);
  }
}

Add test for list controller

Add test for list controller


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/get-student-workspace")
public class GetStudentWorkspace extends HttpServlet {
  private FirebaseAuth authInstance;
  private DatastoreService datastore;
  private Gson gson;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
      gson = new Gson();
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    try {
      // Retrive class entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      String studentToken = request.getParameter("studentToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(studentToken);
      String studentID = decodedToken.getUid();

      EmbeddedEntity beingHelped = (EmbeddedEntity) classEntity.getProperty("beingHelped");
      EmbeddedEntity queueInfo = (EmbeddedEntity) beingHelped.getProperty(studentID);

      // if interaction ended
      if (queueInfo == null) {
        response.setContentType("application/json;");
        response.getWriter().print(gson.toJson("null"));

      } else {
        // Get workspace id
        String workspaceID = (String) queueInfo.getProperty("workspaceID");

        // Build workspace link
        String workspaceLink = "/workspace?workspaceID=" + workspaceID;

        response.setContentType("application/json;");
        response.getWriter().print(gson.toJson(workspaceLink));
      }

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet that will return workspace link


package co.vorobyev.exitsign;

/**
 * Constant class collecting exit status codes.
 *
 * @author Anton Vorobyev, <anton@vorobyev.co>
 */
public final class ExitStatus {

    /** Don't create instance of this class, it is constant class. */
    private ExitStatus() {
        throw new AssertionError();
    }

    /** Exit code returned when execution finishes successfully */
    public static final int OK = 0;

}

Add constant class collecting exit codes (now it is OK only)


package com.KOIFish.FishStock.beans;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Cacheable
@Entity
@Table(name="Fish_Companies")
public class FishStockCompany {

	@Id
	@Column(name="CompanyId", nullable=false)
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int companyId;

	@Column(name="Name", nullable=false, length=100)
	private String companyName;

	@Column(name="Symbol", nullable=true, length=10)
	private String symbol;

	@Column(name="TotalRating", nullable=true)
	private int totalRating;

	@Column(name="TotalUsersRated", nullable=true)
	private int totalUsersRated;

	public FishStockCompany(){
		super();
	}

	public FishStockCompany(String companyName, String symbol) {
		super();
		this.companyName = companyName;
		this.symbol = symbol;
	}

	public int getCompanyId() {
		return companyId;
	}
	public void setCompanyId(int companyId) {
		this.companyId = companyId;
	}
	public String getCompanyName() {
		return companyName;
	}
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	public String getSymbol() {
		return symbol;
	}
	public void setSymbol(String symbol) {
		this.symbol = symbol;
	}
	public int getTotalRating() {
		return totalRating;
	}
	public void setTotalRating(int totalRating) {
		this.totalRating = totalRating;
	}
	public int getTotalUsersRated() {
		return totalUsersRated;
	}
	public void setTotalUsersRating(int totalUsersRated) {
		this.totalUsersRated = totalUsersRated;
	}

	@Override
	public String toString() {
		return "FishStockCompany [companyId=" + companyId + ", companyName=" + companyName + ", symbol=" + symbol
				+ ", totalRating=" + totalRating + ", totalUsersRated=" + totalUsersRated + "]";
	}

}

Create bean that maps to Company table in database


package net.openhft.chronicle.core.pool;

import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.Nullable;

import java.util.function.Function;
import java.util.stream.Stream;

/**
 * Created by peter on 29/02/16.
 */
public class ParsingCache<E> {
    protected final ParsedData<E>[] interner;
    protected final int mask, shift;
    private final Function<String, E> eFunction;
    protected boolean toggle = false;

    public ParsingCache(int capacity, Function<String, E> eFunction) throws IllegalArgumentException {
        this.eFunction = eFunction;
        int n = Maths.nextPower2(capacity, 128);
        shift = Maths.intLog2(n);
        interner = new ParsedData[n];
        mask = n - 1;
    }

    @Nullable
    public E intern(@Nullable CharSequence cs) {
        if (cs == null)
            return null;
        int hash = Maths.hash32(cs);
        int h = hash & mask;
        ParsedData<E> s = interner[h];
        if (StringUtils.isEqual(s.string, cs))
            return s.e;
        int h2 = (hash >> shift) & mask;
        ParsedData<E> s2 = interner[h2];
        if (StringUtils.isEqual(s2.string, cs))
            return s2.e;
        String string = cs.toString();
        ParsedData<E> s3 = new ParsedData<>(string, eFunction.apply(string));
        interner[s == null || (s2 != null && toggle()) ? h : h2] = s3;

        return s3.e;
    }

    protected boolean toggle() {
        return toggle = !toggle;
    }

    public int valueCount() {
        return (int) Stream.of(interner).filter(s -> s != null).count();
    }

    static class ParsedData<E> {
        final String string;
        final E e;

        ParsedData(String string, E e) {
            this.string = string;
            this.e = e;
        }
    }
}

Add the ability to cache the results parsed from a CharSequence.


import com.serial.*;

import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class fletcher_test {
    @Test
    public void testHelloWorldInt(){
        byte[] data = "Hello World!".getBytes();
        int sum = Serial.fletcher16(data);

        assertEquals(0x5941, sum);
    }

    @Test
    public void testRobotMessageInt(){
        byte[] data = "Robot Message".getBytes();
        int sum = Serial.fletcher16(data);

        assertEquals(0xf9ef, sum);
    }

    @Test
    public void emptyInt(){
        byte[] data = new byte[0];
        int sum = Serial.fletcher16(data);

        assertEquals(0xffff, sum);
    }

    @Test
    public void oneByteInt(){
        byte[] data = new byte[]{ 0x01 };
        int sum = Serial.fletcher16(data);

        assertEquals(0x0101, sum);
    }

    @Test
    public void zerosInt(){
        byte[] data = new byte[]{ 0x01, 0x00, 0x00, 0x00 };
        int sum = Serial.fletcher16(data);

        assertEquals(0x0401, sum);
    }

    @Test
    public void testHelloWorldBytes(){
        byte[] data = "Hello World!".getBytes();
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x59, (byte)0x41}, sum);
    }

    @Test
    public void testRobotMessageBytes(){
        byte[] data = "Robot Message".getBytes();
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0xf9, (byte)0xef}, sum);
    }

    @Test
    public void emptyBytes(){
        byte[] data = new byte[0];
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0xff, (byte)0xff}, sum);
    }

    @Test
    public void oneByteBytes(){
        byte[] data = new byte[]{ 0x01 };
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x01, (byte)0x01}, sum);
    }

    @Test
    public void zerosBytes(){
        byte[] data = new byte[]{ 0x01, 0x00, 0x00, 0x00 };
        byte[] sum = Serial.fletcher16bytes(data);

        assertArrayEquals(new byte[]{(byte)0x04, (byte)0x01}, sum);
    }
}

Add test of fletcher checksum functions

Add test of fletcher checksum functions


package com.google.instrumentation.common;

import java.io.Closeable;

/**
 * An {@link Closeable} which cannot throw a checked exception.
 */
public interface NonThrowingCloseable extends Closeable {
  @Override
  void close();
}

Add an interface that extends Closeable which cannot throw a checked exception.


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

import com.fluxchess.jcpi.commands.ProtocolInitializeAnswerCommand;
import org.junit.Test;

import java.io.*;

public class IOProtocolHandlerTest {

  @Test(expected = NoProtocolException.class)
  public void testSend() {
    String[] commands = {""};
    IOProtocolHandler handler = createIOProtocolHandler(commands);

    handler.send(new ProtocolInitializeAnswerCommand("Engine 1.0", "Author"));
  }

  private IOProtocolHandler createIOProtocolHandler(String[] commands) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try (PrintStream stream = new PrintStream(buffer)) {
      for (String command : commands) {
        stream.println(command);
      }
    }

    return new IOProtocolHandler(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()))), new PrintStream(new ByteArrayOutputStream()));
  }

}

Add unit test for IOProtocolHandler

Add unit test for IOProtocolHandler


package com.somerledsolutions.pa11y.client;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

public class ApplicationTest {

    @InjectMocks
    private Application testee;

    @Mock
    private Pa11yRestClient client;

    @Before
    public void setUp() {
        testee = new Application();
        initMocks(this);
    }

    @Test
    public void shouldCallCreateTaskOnClientWithCorrectArguments() throws Exception {

        testee.run("-c", "-n", "name of task", "-h", "http://0.0.0.0:3000", "-s", "WCAG2AAA");
        verify(client, times(1)).createTask("name of task", "http://0.0.0.0:3000", "WCAG2AAA");
    }

}

Test cases for -c and --create switches.


public class CountingSort {
	public static int[] countingSort(int[] unsorted) {
		int maxValue = max(unsorted);

		// Count occurrences of each value in unsorted
		int[] counts = new int[maxValue + 1];

		for(int value : unsorted)
			counts[value]++;

		for(int i = 1; i < counts.length; i++)
			counts[i] += counts[i - 1];

		// Reorder values in unsorted
		int[] sorted = new int[unsorted.length];
		for(int value : unsorted) {
			counts[value] -= 1;
			int index = counts[value];
			sorted[index] = value;
		}

		return sorted;
	}

	private static int max(int[] array) {
		int max = Integer.MIN_VALUE;

		for(int value : array) {
			if(value > max) max = value;
		}

		return max;
	}

	public static void main(String[] args) {
		int[] unsorted = {5, 5, 5, 4, 3, 2, 1, 0};
		int[] sorted = countingSort(unsorted);
		for(int value : sorted)
			System.out.println(value);
	}
}

Implement counting sort for non-negative numbers


/*
 * The MIT License (MIT)
 * Copyright (c) 2018 Microsoft Corporation
 *
 * 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.microsoft.azure.cosmosdb.internal;

import java.time.format.DateTimeFormatter;
import java.util.Locale;

import org.testng.annotations.Test;

public class UtilsTest {
    @Test(groups = { "internal" })
    public void localeUS() {
    	Locale.setDefault(Locale.ITALIAN);
    	DateTimeFormatter RFC_1123_DATE_TIME =
    			DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.US);
    	String time=Utils.nowAsRFC1123();
    	Locale.setDefault(Locale.US);
    	RFC_1123_DATE_TIME.parse(time);
    }
}

Add unit test for PR 52

Add unit test for PR 52


package tachyon.perf.tools;

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

import tachyon.perf.basic.PerfTaskContext;
import tachyon.perf.basic.PerfTotalReport;
import tachyon.perf.basic.TaskType;
import tachyon.perf.conf.PerfConf;

/**
 * Generate a total report for the specified test.
 */
public class TachyonPerfCollector {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.err.println("Wrong program arguments. Should be <TaskType> <reports dir>");
      System.exit(-1);
    }

    try {
      PerfTotalReport summaryReport = TaskType.get().getTotalReportClass(args[0]);
      summaryReport.initialSet(args[0]);
      File contextsDir = new File(args[1]);
      File[] contextFiles = contextsDir.listFiles();
      if (contextFiles == null || contextFiles.length == 0) {
        throw new IOException("No task context files exists under " + args[1]);
      }
      PerfTaskContext[] taskContexts = new PerfTaskContext[contextFiles.length];
      for (int i = 0; i < contextFiles.length; i ++) {
        taskContexts[i] = TaskType.get().getTaskContextClass(args[0]);
        taskContexts[i].loadFromFile(contextFiles[i]);
      }
      summaryReport.initialFromTaskContexts(taskContexts);
      String outputFileName = PerfConf.get().OUT_FOLDER + "/TachyonPerfReport-" + args[0];
      summaryReport.writeToFile(new File(outputFileName));
      System.out.println("Report generated at " + outputFileName);
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Failed to generate Tachyon-Perf-Report");
      System.exit(-1);
    }
  }
}

Add tool to generate total report

Add tool to generate total report


package org.commonmark.test;

import org.commonmark.html.HtmlRenderer;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UsageExampleTest {

    @Test
    public void one() {
        Parser parser = Parser.builder().build();
        Node document = parser.parse("This is *Sparta*");
        HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
        assertEquals("
This is Sparta
\n", renderer.render(document));
    }

}

Add test for usage example

Add test for usage example


package com.blazeloader.api.api.general;

import com.blazeloader.api.main.BLMain;

import java.io.File;

/**
 * General API functions
 */
public class ApiGeneral {
    /**
     * Location of Minecraft's working directory (.minecraft).
     */
    public static File mainDir = new File("./");

    /**
     * Location of the working directory for mods.  Mods should load and save configurations, resources, etc. here.
     */
    public static File modDir = new File("./BL/mods/");

    /**
     * Location of the storage directory for mod Configs.  Mods do not have to obey this, but should if possible.
     */
    public static File configDir = new File("./BL/config/");

    /**
     * Shuts down the game with a specified error code.  Use 0 for normal shutdown.
     *
     * @param code The error code to return to the system after shutdown.
     */
    public static void shutdown(String message, int code) {
        BLMain.instance().shutdown(message, code);
    }
}

package com.blazeloader.api.api.general;

import com.blazeloader.api.main.BLMain;

import java.io.File;

/**
 * General API functions
 */
public class ApiGeneral {
    /**
     * Location of Minecraft's working directory (.minecraft).
     */
    public static File mainDir = new File("./");

    /**
     * Shuts down the game with a specified error code.  Use 0 for normal shutdown.
     *
     * @param code The error code to return to the system after shutdown.
     */
    public static void shutdown(String message, int code) {
        BLMain.instance().shutdown(message, code);
    }
}

Remove unneeded fields from APIGeneral

Remove unneeded fields from APIGeneral


package org.jpos.qi.minigl;

import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.data.ValueContext;
import com.vaadin.shared.ui.ErrorLevel;
import org.jpos.ee.DB;
import org.jpos.gl.Account;
import org.jpos.qi.QI;

public class AccountValidator implements Validator<Account> {
    private QI app;
    private Class clazz;

    public AccountValidator (QI app, Class clazz) {
        super();
        this.app = app;
        this.clazz = clazz;
    }

    @Override
    public ValidationResult apply (Account value, ValueContext context) {
        Account acct = null;
        if (!context.getHasValue().isPresent())
            return ValidationResult.ok();
        boolean isReadOnly = context.getHasValue().get().isReadOnly();
        if (isReadOnly)
            return ValidationResult.ok();
        if (value != null) {
            try {
                acct = DB.exec(db -> db.session().get(Account.class, value.getId()));
            } catch (Exception e) {
                app.getLog().createError(e.getMessage());
            }
        }
        if (acct == null)
            return ValidationResult.create(app.getMessage("errorMessage.willCreateAccountAndReceivables"),
                    ErrorLevel.INFO);
        else if (clazz.isInstance(value))
            return ValidationResult.create(app.getMessage("errorMessage.accountExists"), ErrorLevel.INFO);
        return ValidationResult.ok();

    }
}

Move Account validator to separate class to allow reusing it


package io.sigpipe.sing.stat;

import java.util.List;

import org.apache.commons.math3.util.FastMath;

import io.sigpipe.sing.dataset.feature.Feature;

public class SquaredError {

    private RunningStatistics sqErrs = new RunningStatistics();
    private RunningStatistics actualStats = new RunningStatistics();
    private RunningStatistics predictedStats = new RunningStatistics();

    public SquaredError(List<Feature> actual, List<Feature> predicted) {
        if (actual.size() != predicted.size()) {
            throw new IllegalArgumentException(
                    "List sizes must be equal");
        }

        for (int i = 0; i < actual.size(); ++i) {
            Feature a = actual.get(i);
            Feature b = predicted.get(i);
            Feature err = a.subtract(b);
            double p = Math.pow(err.getDouble(), 2.0);

            sqErrs.put(p);
            actualStats.put(a.getDouble());
            predictedStats.put(b.getDouble());
        }
    }
}

Add class to manage squared errors between collections


package beaform.utilities;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import beaform.entities.FormulaTag;

/**
 * Test for the formula tag.
 * @author Steven Post
 *
 */
public class TagComparatorTest {

	@Test
	public void testDifferentTags() {

		final TagComparator tagComp = new TagComparator();

		final FormulaTag tag1 = new FormulaTag("testa");
		final FormulaTag tag2 = new FormulaTag("testb");

		assertTrue("The tags are expected to have another ordering", tagComp.compare(tag1, tag2) < 0);
		assertTrue("The tags are expected to have another ordering", tagComp.compare(tag2, tag1) > 0);
	}

	@Test
	public void testSameTags() {

		final TagComparator tagComp = new TagComparator();

		final FormulaTag tag1 = new FormulaTag("test");
		final FormulaTag tag2 = new FormulaTag("test");

		assertTrue("The tags are expected to have the same ordering", tagComp.compare(tag1, tag2) == 0);
		assertTrue("The tags are expected to have the same ordering", tagComp.compare(tag2, tag1) == 0);
	}

}

Add tests for the Tagcomparator

Add tests for the Tagcomparator


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

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.plugins.providers.multipart.InputPart;

@Provider
public class InputPartFilter implements ContainerRequestFilter {

	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
		requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, "UTF-8");
	}
}

Fix file name encoding issue

Fix file name encoding issue

Files with accents in names, when uploaded with some binary widgets
doesn't save file name properly.

Fixes RM-5500


package com.cricketcraft.ctmlib;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;

public interface ISubmapManager
{
    IIcon getIcon(int paramInt1, int paramInt2);

    IIcon getIcon(IBlockAccess paramIBlockAccess, int paramInt1, int paramInt2, int paramInt3, int paramInt4);

    @SideOnly(Side.CLIENT)
    void registerIcons(String paramString, Block paramBlock, IIconRegister paramIIconRegister);

    @SideOnly(Side.CLIENT)
    RenderBlocks createRenderContext(RenderBlocks paramRenderBlocks, Block paramBlock, IBlockAccess paramIBlockAccess);

    @SideOnly(Side.CLIENT)
    void preRenderSide(RenderBlocks paramRenderBlocks, IBlockAccess paramIBlockAccess, int paramInt1, int paramInt2, int paramInt3, ForgeDirection paramForgeDirection);

    @SideOnly(Side.CLIENT)
    void postRenderSide(RenderBlocks paramRenderBlocks, IBlockAccess paramIBlockAccess, int paramInt1, int paramInt2, int paramInt3, ForgeDirection paramForgeDirection);
}

Work around CTMLib missing from Chisel api and deobf jars.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2016 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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 net.imagej.ops;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.ExecutionException;

import org.junit.Test;
import org.scijava.ItemIO;
import org.scijava.command.Command;
import org.scijava.command.CommandModule;
import org.scijava.command.CommandService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * Tests that {@link Op}s can be executed directly as {@link Command}s.
 *
 * @author Curtis Rueden
 */
public class RunningOpAsCommandTest extends AbstractOpTest {

	@Test
	public void testRunCommand() throws InterruptedException, ExecutionException {
		final CommandService cs = context.service(CommandService.class);
		final CommandModule module = cs.run(Fibonacci.class, true, "n", 7).get();
		final int result = (Integer) module.getOutput("result");
		assertEquals(13, result);
	}

	// -- Helper classes --

	@Plugin(type = Op.class)
	public static class Fibonacci extends AbstractOp {

		@Parameter
		private int n;

		@Parameter(type = ItemIO.OUTPUT)
		private int result;

		@Override
		public void run() {
			result = fibonacci(n);
		}

		private int fibonacci(final int k) {
			if (k == 1 || k == 2) return 1;
			// NB: Gratuitous use of math.add ensures the OpEnvironment is non-null!
			return ops().math().add(fibonacci(k - 1), fibonacci(k - 2));
		}
	}

}

Add test verifying that ops can be run as commands


package com.example.asadkhan.sunshine;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * A {@link PreferenceActivity} that presents a set of application settings.
 *

 * See
 * Android Design: Settings for design guidelines and the Settings
 * API Guide for more information on developing a Settings UI.
 */
public class SettingsActivity extends PreferenceActivity
        implements Preference.OnPreferenceChangeListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add 'general' preferences, defined in the XML file
        addPreferencesFromResource(R.xml.pref_general);

        // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
        // updated when the preference changes.
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
    }

    /**
     * Attaches a listener so the summary is always updated with the preference value.
     * Also fires the listener once, to initialize the summary (so it shows up before the value
     * is changed.)
     */
    private void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(this);

        // Trigger the listener immediately with the preference's
        // current value.
        onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list (since they have separate labels/values).
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]);
            }
        } else {
            // For other preferences, set the summary to the value's simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public Intent getParentActivityIntent() {
        try{
            Intent intento = super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if (intento != null) {
                return intento;
            } else {
                Log.e("HAHAHA Intento is null!", "Huh??");
            }
        } catch (NullPointerException npe){
            Log.e("HAHAHA Null pointer!!!", npe.getMessage());
        }
        return super.getParentActivityIntent();
    }

}

Add custom activity for settings page

Add custom activity for settings page


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

import io.kubernetes.client.ApiException;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodBuilder;
import io.kubernetes.client.models.V1Service;
import io.kubernetes.client.models.V1ServiceBuilder;
import io.kubernetes.client.util.Yaml;
import java.io.IOException;
import java.util.HashMap;

/**
 * A simple example of how to parse a Kubernetes object.
 *
 *
Easiest way to run this: mvn exec:java
 * -Dexec.mainClass="io.kubernetes.client.examples.YamlExample"
 *
 *
From inside $REPO_DIR/examples
 */
public class YamlExample {
  public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException {
    V1Pod pod =
        new V1PodBuilder()
            .withNewMetadata()
            .withName("apod")
            .endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("www")
            .withImage("nginx")
            .withNewResources()
            .withLimits(new HashMap<>())
            .endResources()
            .endContainer()
            .endSpec()
            .build();
    System.out.println(Yaml.dump(pod));

    V1Service svc =
        new V1ServiceBuilder()
            .withNewMetadata()
            .withName("aservice")
            .endMetadata()
            .withNewSpec()
            .withSessionAffinity("ClientIP")
            .withType("NodePort")
            .addNewPort()
            .withProtocol("TCP")
            .withName("client")
            .withPort(8008)
            .withNodePort(8080)
            .withTargetPort(new IntOrString(8080))
            .endPort()
            .endSpec()
            .build();
    System.out.println(Yaml.dump(svc));
  }
}

Add an example of using YAML

Add an example of using YAML


package com.codacy.play.tomcatcp.pool;

import com.codacy.play.tomcatcp.metrics.MetricsTrackerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;

import java.sql.SQLException;

public class TomcatCPDataSource extends DataSource {

    private MetricsTrackerFactory metricsTrackerFactory;
    private MetricRegistry metricRegistry;
    private HealthCheckRegistry healthCheckRegistry;
    private TomcatCPPool TCPool;

    public TomcatCPDataSource() {
        super();
    }

    public TomcatCPDataSource(PoolConfiguration poolProperties) {
        super(poolProperties);
    }

    @Override
    public ConnectionPool createPool() throws SQLException {
        if (pool != null) {
            return pool;
        } else {
            TCPool = new TomcatCPPool(poolProperties);
            pool = TCPool;
            return pool;
        }
    }

    public MetricRegistry getMetricRegistry() {
        return metricRegistry;
    }

    public void setMetricRegistry(MetricRegistry metricRegistry) {
        if (metricsTrackerFactory != null) {
            throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together");
        }

        boolean isAlreadySet = getMetricRegistry() != null;

        if (pool != null) {
            if (isAlreadySet) {
                throw new IllegalStateException("MetricRegistry can only be set one time");
            } else {
                TCPool.setMetricRegistry(metricRegistry);
            }
        }
    }

    public MetricsTrackerFactory getMetricsTrackerFactory() {
        return metricsTrackerFactory;
    }

    public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) {
        if (metricRegistry != null) {
            throw new IllegalStateException("cannot use setMetricsTrackerFactory() and setMetricRegistry() together");
        }

        boolean isAlreadySet = getMetricsTrackerFactory() != null;

        if (pool != null) {
            if (isAlreadySet) {
                throw new IllegalStateException("MetricsTrackerFactory can only be set one time");
            } else {
                TCPool.setMetricsTrackerFactory(metricsTrackerFactory);
            }
        }
    }

    public HealthCheckRegistry getHealthCheckRegistry() {
        return healthCheckRegistry;
    }

    public void setHealthCheckRegistry(HealthCheckRegistry healthCheckRegistry) {
        boolean isAlreadySet = getHealthCheckRegistry() != null;

        if (pool != null) {
            if (isAlreadySet) {
                throw new IllegalStateException("HealthCheckRegistry can only be set one time");
            } else {
                TCPool.setHealthCheckRegistry(healthCheckRegistry);
            }
        }
    }

}

Add a wrapper class for DataSource

Add a wrapper class for DataSource


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.wdm.ChromeDriverManager;
import io.github.bonigarcia.wdm.FirefoxDriverManager;

/**
 * Test with Chrome and Firefox browsers.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class ChromeAndFirefoxTest {

	protected WebDriver chrome;
	protected WebDriver firefox;

	@BeforeClass
	public static void setupClass() {
		ChromeDriverManager.getInstance().setup();
		FirefoxDriverManager.getInstance().setup();
	}

	@Before
	public void setupTest() {
		chrome = new ChromeDriver();
		firefox = new FirefoxDriver();
	}

	@After
	public void teardown() {
		if (chrome != null) {
			chrome.quit();
		}
		if (firefox != null) {
			firefox.quit();
		}
	}

	@Test
	public void test() {
		// Test data
		int timeout = 30;
		String sutUrl = "https://en.wikipedia.org/wiki/Main_Page";

		// Implicit timeout
		chrome.manage().timeouts().implicitlyWait(timeout, SECONDS);
		firefox.manage().timeouts().implicitlyWait(timeout, SECONDS);

		// Open page in different browsers
		chrome.get(sutUrl);
		firefox.get(sutUrl);

		// Assertion
		assertEquals(chrome.getTitle(), firefox.getTitle());
	}

}

Include example with two browsers (Chrome and Firefox)


package com.abhi.fyberdemo.fragments;

import android.support.v4.app.Fragment;
import android.view.View;

import com.abhi.fyberdemo.BuildConfig;
import com.abhi.fyberdemo.MainActivity;
import com.abhi.fyberdemo.R;
import com.abhi.fyberdemo.models.OfferResponse;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/**
 * Created by abhi on 28/10/16.
 */

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23)
public class OffersFragmentTest {
    private MainActivity mMainActivity;
    private OffersFragment mOffersFragment;

    @Before
    public void setUp() throws Exception {
        OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        mMainActivity = Robolectric.setupActivity(MainActivity.class);
        mOffersFragment = OffersFragment.newInstance(mMainActivity, _offerResponse);
        startFragment(mOffersFragment);
    }

    private void startFragment(Fragment fragment) {
        mMainActivity.getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frag_container, fragment)
                .commit();
    }

    @Test
    public void newInstance() throws Exception {
        /*OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        MainActivity _mainActivity = Mockito.mock(MainActivity.class);
        OffersFragment _offersFragment = OffersFragment.newInstance(_mainActivity,_offerResponse);*/
        Assert.assertNotNull(mOffersFragment);
        Assert.assertNotNull(mMainActivity);
    }

    @Test
    public void setupUI() throws Exception {

    }

    @Test
    public void loadOffers() throws Exception {
        OfferResponse _offerResponse = mOffersFragment.getOfferResponse();
        Mockito.when(_offerResponse.containsOffers()).thenReturn(false);
        mOffersFragment.loadOffers(_offerResponse);
        Assert.assertEquals("No Offers Test is not displayed when there are no offers", mOffersFragment.mNoOffersTextView.getVisibility(), View.VISIBLE);
        Assert.assertEquals("RecyclerView is displayed when there are no offers", mOffersFragment.mOffersRecyclerView.getVisibility(), View.GONE);

        Mockito.when(_offerResponse.containsOffers()).thenReturn(true);
        mOffersFragment.loadOffers(_offerResponse);
        Assert.assertEquals("No Offers Test is displayed when there are offers", mOffersFragment.mNoOffersTextView.getVisibility(), View.GONE);
        Assert.assertEquals("RecyclerView is not displayed when there are offers", mOffersFragment.mOffersRecyclerView.getVisibility(), View.VISIBLE);
    }

    @Test
    public void getLayoutId() throws Exception {
        int layoutId = mOffersFragment.getLayoutId();
        Assert.assertTrue("Layout Id can not be 0 ", layoutId != 0);
        Assert.assertTrue("Layout Id can not be negative ", layoutId > 0);
    }
}

Add Unit test for OffersFragment using Roboelectric


/*
 * 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.pwcgarage.ibeaconref.restclients;

/**
 * @author asksven
 */
public class Constants
{
	protected static final String EVENTHUB_URL = "<your-url-here>";
	protected static final String EVENTHUB_SA_SIG = "<your-sa-signature-here>";
}

Connect strings and keys constants

Connect strings and keys constants


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

package com.google.gwtexpui.user.client;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.DialogBox;

/** A DialogBox that automatically re-centers itself if the window changes */
public class AutoCenterDialogBox extends DialogBox {
  private WindowResizeListener recenter;

  public AutoCenterDialogBox() {
  }

  public AutoCenterDialogBox(final boolean autoHide) {
    super(autoHide);
  }

  public AutoCenterDialogBox(final boolean autoHide, final boolean modal) {
    super(autoHide, modal);
  }

  @Override
  public void show() {
    if (recenter == null) {
      recenter = new WindowResizeListener() {
        public void onWindowResized(final int width, final int height) {
          onResize(width, height);
        }
      };
      Window.addWindowResizeListener(recenter);
    }
    super.show();
  }

  @Override
  protected void onUnload() {
    if (recenter != null) {
      Window.removeWindowResizeListener(recenter);
      recenter = null;
    }
    super.onUnload();
  }

  /**
   * Invoked when the outer browser window resizes.
   * <p>
   * Subclasses may override (but should ensure they still call super.onResize)
   * to implement custom logic when a window resize occurs.
   *
   * @param width new browser window width
   * @param height new browser window height
   */
  protected void onResize(final int width, final int height) {
    if (isAttached()) {
      center();
    }
  }
}

Add a simple dialog box that automatically centers itself

Blatantly stolen from Gerrit Code Review, this is a simple dialog
that registers a window listener to recenter itself whenever the
main browser window resizes.

Signed-off-by: Shawn O. Pearce <f3ea74d906fa9fe97c1fef6bad9cb871485c7045@google.com>


package monitoring.impl;

import monitoring.intf.Monitor;
import structure.impl.Verdict;
import structure.intf.QEA;

/**
 * A small-step monitor for a simple QEA with no quantified variables
 *
 * @author Helena Cuenca
 * @author Giles Reger
 */
public class SmallStepQEANoQVMonitor extends Monitor {

	private int currentState;

	private QEA qea;

	public SmallStepQEANoQVMonitor(QEA qea) {
		this.qea = qea;
	}

	@Override
	public Verdict step(int eventName, Object[] args) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Verdict step(int eventName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Verdict end() {
		// TODO Auto-generated method stub
		return null;
	}

}

Monitor for QEA with no quantified variables added