/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.smoketest;

import org.elasticsearch.test.ESIntegTestCase;

public class PreventFailingBuildIT extends ESIntegTestCase {

    public void testSoThatTestsDoNotFail() {
        // Noop

        // This is required because if tests are not enable no
        // tests will be run in the entire project and all tests will fail.
    }
}

Add noop test to prevent test failures

Tests: Add noop test to prevent test failures

Relates elastic/x-pack-elasticsearch#2920

Original commit: elastic/x-pack-elasticsearch@c2fe9d985c601de96da46a55b98d022ce444d493


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.picketbox.plugins;

import org.jboss.security.AuthenticationManager;
import org.jboss.security.AuthorizationManager;
import org.jboss.security.ISecurityManagement;
import org.jboss.security.JSSESecurityDomain;
import org.jboss.security.audit.AuditManager;
import org.jboss.security.identitytrust.IdentityTrustManager;
import org.jboss.security.mapping.MappingManager;
import org.picketbox.factories.SecurityFactory;

/**
 * A {@link ISecurityManagement} implementation that delegates to the instance registered with the {@link SecurityFactory}.
 *
 * @author Darran Lofthouse
 */
public class SecurityFactorySecurityManagement implements ISecurityManagement {

    private static final long serialVersionUID = 4533649455497748886L;

    private transient ISecurityManagement delegate;

    private ISecurityManagement getDelegate() {
        return delegate != null ? delegate : (delegate = SecurityFactory.getSecurityManagement());
    }

    @Override
    public AuthenticationManager getAuthenticationManager(String securityDomain) {
        return getDelegate().getAuthenticationManager(securityDomain);
    }

    @Override
    public AuthorizationManager getAuthorizationManager(String securityDomain) {
        return getDelegate().getAuthorizationManager(securityDomain);
    }

    @Override
    public MappingManager getMappingManager(String securityDomain) {
        return getDelegate().getMappingManager(securityDomain);
    }

    @Override
    public AuditManager getAuditManager(String securityDomain) {
        return getDelegate().getAuditManager(securityDomain);
    }

    @Override
    public IdentityTrustManager getIdentityTrustManager(String securityDomain) {
        return getDelegate().getIdentityTrustManager(securityDomain);
    }

    @Override
    public JSSESecurityDomain getJSSE(String securityDomain) {
        return getDelegate().getJSSE(securityDomain);
    }

}

[SECURITY-902] Add an implementation of ISecurityManagement that can use the SecurityFactory to find a globally registered implementation to delegate to.


package com.levelup.java.collections;

import static org.junit.Assert.assertTrue;

import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Test;

import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

/**
 * This java example will demonstrate how to check if every
 * element in the collection satisfies a specified condition.
 *
 * @author Justin Musgrove
 * @see List contains all elements
 */
public class ListContainsAll {

	class Camera {

		String name;
		int focalLength;

		@Override
		public String toString() {
			return Objects.toStringHelper(this)
					.add("name", name)
					.add("focallength", focalLength)
					.toString();
		}

		public Camera(String name, int focalLength) {
			super();
			this.name = name;
			this.focalLength = focalLength;
		}
	}

	List<Camera> cameras;

	@Before
	public void setUp () {
		cameras = Lists.newArrayList();

		cameras.add(new Camera("Nikon", 80));
		cameras.add(new Camera("Cannon", 135));
		cameras.add(new Camera("Kodak", 300));
		cameras.add(new Camera("Olympus", 200));
		cameras.add(new Camera("Fujifilm", 600));
	}

	@Test
	public void list_contains_all_java () {

		boolean allCamerasOfMediumTelephoto = true;

		for (Camera camera : cameras) {
			if (camera.focalLength < 80) {
				allCamerasOfMediumTelephoto = false;
				break;
			}
		}

		assertTrue(allCamerasOfMediumTelephoto);
	}

	@Test
	public void list_contains_all_guava () {

		boolean allCamerasOfMediumTelephoto = Iterables.all(cameras, new Predicate<Camera>() {
			public boolean apply(Camera input) {
				return input.focalLength >= 80;
			}
		});

		assertTrue(allCamerasOfMediumTelephoto);
	}

	@Test
	public void list_contains_all_apache () {

		@SuppressWarnings("unchecked")
		Collection<Camera> mediumTelephotoCameras = CollectionUtils.select(cameras,
				new org.apache.commons.collections.Predicate() {
			public boolean evaluate(Object object) {
				Camera camera = (Camera) object;
				return camera.focalLength >= 80;
			}
		});

		assertTrue(mediumTelephotoCameras.size() == cameras.size());
	}

}

Add list contains all example

Add list contains all example


package wissolsoft.porada.webapp.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import wissolsoft.porada.webapp.model.Vote;

@Repository
public class VotesDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public void insertVote(final Vote vote) {
        final Session session = sessionFactory.getCurrentSession();
        final Transaction transaction = session.beginTransaction();
        session.save(vote);
        transaction.commit();
    }

}

Add basic DAO for votes

Add basic DAO for votes


/*
 * Copyright 2014 Codenvy, S.A.
 *
 * 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.codenvy.ide.ext.datasource.shared.exception;

/**
 * Exception for CSV export.
 *
 * @author "Mickaël Leduque"
 */
public class CSVExportException extends Exception {

    /** UID for serialization */
    private static final long serialVersionUID = 1L;

    public CSVExportException() {
    }

    public CSVExportException(final String message) {
        super(message);
    }

    public CSVExportException(final Throwable cause) {
        super(cause);
    }

    public CSVExportException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public CSVExportException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

}

Add an exception for CSV export errors

Add an exception  for CSV export errors


package com.asascience.ncsos.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class LogUtils {

    public static String exceptionAsString(Exception exception) {
        /**
         * Gets the exception stack trace as a string.
         * @param exception
         * @return
         */
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.print(" [ ");
            pw.print(exception.getClass().getName());
            pw.print(" ] ");
            pw.print(exception.getMessage());
            exception.printStackTrace(pw);
            return sw.toString();
        }
    }
}

Add a LogUtil to print consistent log message


/**
 * Created with IntelliJ IDEA.
 * User: jhasmanyquiroz
 * Date: 11/12/15
 * Time: 3:07 PM
 * To change this template use File | Settings | File Templates.
 */
package ui.pages;

import org.openqa.selenium.support.PageFactory;
import ui.BasePageObject;

public class CoursesPage extends BasePageObject {
    public CoursesPage() {
        PageFactory.initElements(driver, this);
        waitUntilPageObjectIsLoaded();
    }

    public void waitUntilPageObjectIsLoaded() {
    }
}

Implement the Page Factory Pattern and methods for search any course


package tests.net.sf.jabref.export.layout.format;

import net.sf.jabref.export.layout.format.AuthorLastFirstAbbreviator;
import junit.framework.Assert;
import junit.framework.TestCase;

/**
 * Test case  that verifies the functionalities of the
 * formater AuthorLastFirstAbbreviator.
 *
 * @author Carlos Silla
 */
public class AuthorLastFirstAbbreviatorTester extends TestCase {

	/**
	 * Verifies the Abbreviation of one single author with a simple name.
	 *
	 * Ex: Lastname, Name
	 */
	public void testOneAuthorSimpleName() {
		String name = new String("Lastname, Name");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of one single author with a common name.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	public void testOneAuthorCommonName() {
		String name = new String("Lastname, Name Middlename");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.M.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of two single with a common name.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	public void testTwoAuthorsCommonName() {
		String name = new String("Lastname, Name Middlename and Sobrenome, Nome Nomedomeio");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.M. and Sobrenome, N.N.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of two authors in the incorrect format.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	//TODO: Verify how to tell this test that it should pass if fail.
/*	public void testTwoAuthorsBadFormating() {
		String name = new String("Lastname, Name Middlename and Nome Nomedomeio Sobrenome");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);
	}*/

}

Test dirs along with the first test case of jabref for the AuthorLastFirstAbbreviator formater.


package io.quarkus.smallrye.faulttolerance.runtime.graal;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.BooleanSupplier;

import org.graalvm.home.Version;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;

public class FaultToleranceSubstitutions {
}

@TargetClass(className = "io.smallrye.faulttolerance.DefaultMethodFallbackProvider", onlyWith = GraalVM20OrEarlier.class)
final class Target_io_smallrye_faulttolerance_DefaultMethodFallbackProvider {

    @TargetClass(className = "io.smallrye.faulttolerance.ExecutionContextWithInvocationContext")
    static final class Target_io_smallrye_faulttolerance_ExecutionContextWithInvocationContext {

    }

    @Substitute
    static Object getFallback(Method fallbackMethod,
            Target_io_smallrye_faulttolerance_ExecutionContextWithInvocationContext ctx)
            throws IllegalAccessException, InstantiationException, IllegalArgumentException, InvocationTargetException,
            Throwable {
        throw new RuntimeException("Not supported in native image when using GraalVM releases prior to 21.0.0");
    }

}

class GraalVM20OrEarlier implements BooleanSupplier {

    @Override
    public boolean getAsBoolean() {
        return Version.getCurrent().compareTo(21) < 0;
    }
}

Substitute DefaultMethodFallbackProvider in GraalVM < 21.0


package net.kencochrane.raven.jul;

import net.kencochrane.raven.Raven;
import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.LoggedEvent;
import net.kencochrane.raven.event.interfaces.ExceptionInterface;
import net.kencochrane.raven.event.interfaces.MessageInterface;
import net.kencochrane.raven.event.interfaces.StackTraceInterface;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class SentryHandler extends Handler {
    private final Raven raven;

    public SentryHandler() {
        this(new Raven());
    }

    public SentryHandler(Raven raven) {
        this.raven = raven;
    }

    private static LoggedEvent.Level getLevel(Level level) {
        if (level.intValue() >= Level.SEVERE.intValue())
            return LoggedEvent.Level.ERROR;
        else if (level.intValue() >= Level.WARNING.intValue())
            return LoggedEvent.Level.WARNING;
        else if (level.intValue() >= Level.INFO.intValue())
            return LoggedEvent.Level.INFO;
        else if (level.intValue() >= Level.ALL.intValue())
            return LoggedEvent.Level.DEBUG;
        else return null;
    }

    private static List<String> formatParameters(Object[] parameters) {
        List<String> formattedParameters = new ArrayList<String>(parameters.length);
        for (Object parameter : parameters)
            formattedParameters.add(parameter.toString());
        return formattedParameters;
    }

    @Override
    public void publish(LogRecord record) {
        if (!isLoggable(record)) {
            return;
        }

        EventBuilder eventBuilder = new EventBuilder()
                .setLevel(getLevel(record.getLevel()))
                .setTimestamp(new Date(record.getMillis()))
                .setLogger(record.getLoggerName())
                .setCulprit(record.getSourceClassName() + "." + record.getSourceMethodName() + "()");
        if (record.getThrown() != null) {
            eventBuilder.addSentryInterface(new ExceptionInterface(record.getThrown()))
                    .addSentryInterface(new StackTraceInterface(record.getThrown()));
        }

        if (record.getParameters() != null)
            eventBuilder.addSentryInterface(new MessageInterface(record.getMessage(), formatParameters(record.getParameters())));
        else
            eventBuilder.setMessage(record.getMessage());

        raven.sendEvent(eventBuilder);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
}

Create a JUL handler using Raven

Create a JUL handler using Raven


package org.realityforge.replicant.client;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;

/**
 * A basic EntityLocator implementation that allows explicit per-type registration
 */
public class AggregateEntityLocator
  implements EntityLocator
{
  private final ArrayList<EntityLocator> _entityLocators = new ArrayList<>();

  protected final <T> void registerEntityLocator( @Nonnull final EntityLocator entityLocator )
  {
    apiInvariant( () -> !_entityLocators.contains( entityLocator ),
                  () -> "Attempting to register entityLocator " + entityLocator + " when already present." );
    _entityLocators.add( entityLocator );
  }

  /**
   * {@inheritDoc}
   */
  @Nullable
  @Override
  public final <T> T findByID( @Nonnull final Class<T> type, @Nonnull final Object id )
  {
    for ( final EntityLocator entityLocator : _entityLocators )
    {
      final T entity = entityLocator.findByID( type, id );
      if ( null != entity )
      {
        return entity;
      }
    }
    return null;
  }

  /**
   * {@inheritDoc}
   */
  @Nonnull
  @Override
  public <T> List<T> findAll( @Nonnull final Class<T> type )
  {
    final ArrayList<T> results = new ArrayList<>();
    for ( final EntityLocator entityLocator : _entityLocators )
    {
      results.addAll( entityLocator.findAll( type ) );
    }
    return results;
  }
}

Add locator that will delegate to list of locators


public class Solution {

    public int strStr(String haystack, String needle) {

        for (int i = 0; i <= haystack.length() - needle.length(); i++) {

            int j = 0;
            for ( ; j < needle.length(); j++) {

                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }

            }

            if (j == needle.length()) {
                return i;
            }

        }

        return -1;

    }

}

Create : 28 Implement strStr()

Create : 28 Implement strStr()


package tld.testmod;

/*
    Licenses for assets can be found in ASSETS_LICENSE.txt. All other files are licensed under the terms below:

    The MIT License (MIT)

    Test Mod 3 - Copyright (c) 2015-2017 Choonster

    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.
 */
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Config(modid = Main.MODID)
@Config.LangKey("testmod.config.title")
public class ModConfig {

    @Config.Comment("This is an example boolean property.")
    public static boolean fooBar = false;

    public static final Client client = new Client();

    public static class Client {

        @Config.Comment("This is an example int property.")
        public int baz = -100;

        public final HUDPos chunkEnergyHUDPos = new HUDPos(0, 0);

        public static class HUDPos {
            public HUDPos(final int x, final int y) {
                this.x = x;
                this.y = y;
            }

            @Config.Comment("The x coordinate")
            public int x;

            @Config.Comment("The y coordinate")
            public int y;
        }
    }

    @Mod.EventBusSubscriber
    private static class EventHandler {

        /**
         * Inject the new values and save to the config file when the config has been changed from the GUI.
         *
         * @param event The event
         */
        @SubscribeEvent
        public static void onConfigChanged(final ConfigChangedEvent.OnConfigChangedEvent event) {
            if (event.getModID().equals(Main.MODID)) {
                ConfigManager.sync(Main.MODID, Config.Type.INSTANCE);
            }
        }
    }
}

Add a test config for the heck of it. Thank you Choonster for your TestMod3.


package leetcode;

/**
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
 */
public class Problem122 {
    public int maxProfit(int[] prices) {
        return 0;
    }

    public static void main(String[] args) {
        Problem122 prob = new Problem122();
        System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
        System.out.println(prob.maxProfit(new int[]{3, 2, 6, 5, 0, 3}));
    }
}

Create skeleton for problem 122

Create skeleton for problem 122


package problems;

public class ReverseNodesInGroups {

    public class ListNode {
        int val;
        ListNode next;

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

    public ListNode reverseKGroup(ListNode head, int k) {
        if (k < 2)
            return head;
        ListNode newHead = new ListNode(-1), p = newHead;
        newHead.next = head;
        while (p != null && p.next != null) {
            ListNode[] t = reverse(p.next, k);
            p.next = t[0];
            p = t[1];
        }
        return newHead.next;
    }

    // return the head and tail of the reversed group
    ListNode[] reverse(ListNode head, int k) {
        ListNode p = head, q = p.next, r = null;
        ListNode[] out = { head, null };
        for (int i = 1; i < k; i++) {
            if (p.next == null)
                return out;
            p = p.next;
        }
        p = head;
        for (int i = 1; i < k; i++) {
            r = q.next;
            q.next = p;
            p = q;
            q = r;
        }
        head.next = q;
        out[0] = p;
        out[1] = head;
        return out;
    }

    public static void main(String[] args) {
        ReverseNodesInGroups rn = new ReverseNodesInGroups();

        int[] A = { 1, 2, 3, 4, 5 };
        ListNode head = null, p = null;
        for (int i = 0; i < A.length; i++) {
            ListNode t = rn.new ListNode(A[i]);
            if (head == null)
                head = p = t;
            else {
                p.next = t;
                p = t;
            }
        }

        ListNode l = rn.reverseKGroup(head, 5);
        while (l != null) {
            System.out.print(l.val + ", ");
            l = l.next;
        }
    }
}

Add Reverse Nodes In K Groups

Add Reverse Nodes In K Groups


/* This file is part of VoltDB.
 * Copyright (C) 2008-2020 VoltDB Inc.
 *
 * 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 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 org.voltdb_testprocs.fullddlfeatures;

import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;

public class testCreateWriteProcFromClassProc extends VoltProcedure {
    public final SQLStmt write = new SQLStmt(
            "INSERT INTO T2 SELECT * FROM T2;"
    );

    public long run(long isbn, String title, String author)
    throws VoltAbortException {
        return 1;
    }
}

ENG-19936:
Add new class to support DIRECTED PROECEDURE FROM CLASS scenario added to FullDDL.


package org.openmhealth.shim.withings.domain;

/**
 * A body measure type included in responses from the Withings body measure endpoint, specifically in a 'meastype'
 * property.
 *
 * @author Chris Schaefbauer
 * @author Emerson Farrugia
 * @see {@link org.openmhealth.shim.withings.mapper.WithingsBodyMeasureDataPointMapper}
 * @see Body Measures API documentation
 */
public enum WithingsBodyMeasureType {

    BODY_WEIGHT(1),
    BODY_HEIGHT(4),
    // FAT_FREE_MASS(5), // TODO confirm what this means
    // FAT_RATIO(6), // TODO confirm what this means
    // FAT_MASS_WEIGHT(8), // TODO confirm what this means
    DIASTOLIC_BLOOD_PRESSURE(9),
    SYSTOLIC_BLOOD_PRESSURE(10),
    HEART_RATE(11),
    OXYGEN_SATURATION(54);

    private int magicNumber;

    WithingsBodyMeasureType(int magicNumber) {
        this.magicNumber = magicNumber;
    }

    /**
     * @return the magic number used to refer to this body measure type in responses
     */
    public int getMagicNumber() {
        return magicNumber;
    }
}

Add class missed in last commit

Add class missed in last commit


/*
    JSPWiki - a JSP-based WikiWiki clone.

    Copyright (C) 2001-2002 Janne Jalkanen (Janne.Jalkanen@iki.fi)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.ecyrd.jspwiki.tags;

import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

/**
 * ParamTag submits name-value pairs to the first enclosing
 * ParamHandler instance. Name and value are strings, and can
 * be given as tag attributes, or alternatively the value can be
 * given as the body contents of this tag.
 * <p>
 * The name-value pair is passed to the closest containing
 * ancestor tag that implements ParamHandler.
 */
public class ParamTag
    extends BodyTagSupport
{

    private String m_name;
    private String m_value;

    public void release()
    {
        m_name = m_value = null;
    }

    public void setName( String s )
    {
        m_name = s;
    }

    public void setValue( String s )
    {
        m_value = s;
    }

    public int doEndTag()
    {
        Tag t = null;
        while( (t = getParent()) != null && !(t instanceof ParamHandler) )
            ;
        if( t != null )
        {
            String val = m_value;
            if( val == null )
            {
                BodyContent bc = getBodyContent();
                if( bc != null )
                {
                    val = bc.getString();
                }
            }
            if( val != null )
            {
                ((ParamHandler)t).setContainedParameter( m_name, val );
            }
        }

        return EVAL_PAGE;
    }
}

Tag for providing name-value pairs to a parent tag

git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@625005 13f79535-47bb-0310-9956-ffa450edef68


package info.u_team.u_team_core.item;

import java.util.function.Supplier;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;

public class NoPlaceUBucketItem extends UBucketItem {

	public NoPlaceUBucketItem(String name, ItemGroup group, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, group, properties, fluid);
	}

	public NoPlaceUBucketItem(String name, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, properties, fluid);
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
		return new ActionResult<ItemStack>(ActionResultType.PASS, player.getHeldItem(hand));
	}

}

Add no placement u bucket item

Add no placement u bucket item


package gov.nih.nci.cananolab.service.admin;

import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.publication.PublicationService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.security.SecurityService;

import java.util.Set;

/**
 * Interface for transfer of ownership.
 */
public interface OwnershipTransferService {

	public void transferOwner(SampleService sampleService, SecurityService securityService, Set<String> sampleIds, String currentOwner,
			String newOwner) throws Exception ;

	public void transferOwner(PublicationService publicationService, SecurityService securityService, Set<String> publicationIds, String currentOwner,
			String newOwner) throws Exception ;

	public void transferOwner(ProtocolService protocolService, SecurityService securityService, Set<String> protocolIds, String currentOwner,
			String newOwner) throws Exception ;

	}

Refactor ownership transfer to service

Refactor ownership transfer to service

SVN-Revision: 19386


package uk.ac.ox.oucs.oauth.admin;

import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.cover.ComponentManager;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Filter users before displaying the oAuth administration page
 */
public class AdminFilter implements Filter {
    private static final String OAUTH_ADMIN_RIGHT = "oauth.admin";
    private SecurityService securityService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        FunctionManager functionManager = (FunctionManager) ComponentManager.get(FunctionManager.class);
        functionManager.registerFunction(OAUTH_ADMIN_RIGHT, false);
        securityService = (SecurityService) ComponentManager.get(SecurityService.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (securityService.unlock(OAUTH_ADMIN_RIGHT, "")) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    @Override
    public void destroy() {
    }
}

Create a filter to check if the user can access oAuth admin


package alien4cloud.ui;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WizardController {

@RequestMapping({ "/wizard", "/wizard/#"})
   public String index() {
       return "forward:/wizard/index.html";
   }
}

Add spring controller for wizard

Add spring controller for wizard


package org.hisp.dhis.android.testapp.datavalue;

import android.support.test.runner.AndroidJUnit4;

import org.hisp.dhis.android.core.datavalue.DataValue;
import org.hisp.dhis.android.testapp.arch.BasePublicAccessShould;
import org.junit.runner.RunWith;
import org.mockito.Mock;

@RunWith(AndroidJUnit4.class)
public class DataValuePublicAccessShould extends BasePublicAccessShould<DataValue> {

    @Mock
    private DataValue object;

    @Override
    public DataValue object() {
        return object;
    }

    @Override
    public void has_public_create_method() {
        DataValue.create(null);
    }

    @Override
    public void has_public_builder_method() {
        DataValue.builder();
    }

    @Override
    public void has_public_to_builder_method() {
        object().toBuilder();
    }
}

Add data value package tests

[ANDROSDK-637] Add data value package tests


package com.phsshp.config;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class CommandLineParserTest {

    @Test
    public void parseFileNameFromCommandLine() throws Exception {
        CommandLineOptions options = parse("filepath");

        assertThat(options.getSourcePath(), equalTo("filepath"));
    }

    private CommandLineOptions parse(String ...arguments) {
        return new CommandLineParser().parse(arguments);
    }
}

Add test for parsing file path from command line


package cl.fatman.capital.fund;

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

import org.hibernate.annotations.GenericGenerator;

import java.time.LocalDate;

@Entity
@Table( name = "Rate" )
public class Rate {

	private int id;
	private double value;
	private LocalDate date;

	public Rate(double value, LocalDate date) {
		super();
		this.value = value;
		this.date = date;
	}

	public Rate() {
		super();
	}

	@Id
	@GeneratedValue(generator="increment")
	@GenericGenerator(name="increment", strategy = "increment")
	@Column(name="ID")
	public int getId() {
		return id;
	}

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

	@Column(name = "VALUE")
	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	@Column(name = "DATE", unique = true)
	public LocalDate getDate() {
		return date;
	}

	public void setDate(LocalDate date) {
		this.date = date;
	}
}

Create the class rate to registry the value of a fund.


package leetcode.compare_version_numbers;

public class Solution {
    public int compareVersion(String version1, String version2) {
    	version1 = version1.replaceAll("(\\.0+)+$", "");
    	version2 = version2.replaceAll("(\\.0+)+$", "");
        String[] sp1 = version1.split("\\.");
        String[] sp2 = version2.split("\\.");
        int l1 = sp1.length;
        int l2 = sp2.length;
        int l = Math.min(l1, l2);
        for(int i = 0; i < l; i++){
        	String n1 = sp1[i].replaceAll("^0+", "");
        	String n2 = sp2[i].replaceAll("^0+", "");
        	if(n1.length() > n2.length()){
        		return 1;
        	}else if(n1.length() < n2.length()){
        		return -1;
        	}else{
        		int cmp = n1.compareTo(n2);
        		if(cmp > 0) return 1;
        		if(cmp < 0) return -1;
        	}
        }
        if(l1 > l2) return 1;
        if(l1 < l2) return -1;
        return 0;
    }
}

Add java solution for 165. Compare Version Numbers

165. Compare Version Numbers: https://leetcode.com/problems/compare-version-numbers/


/*
 *                      Nividic development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the microarray platform
 * of the cole Normale Suprieure and the individual authors.
 * These should be listed in @author doc comments.
 *
 * For more information on the Nividic project and its aims,
 * or to join the Nividic mailing list, visit the home page
 * at:
 *
 *      http://www.transcriptome.ens.fr/nividic
 *
 */

package fr.ens.transcriptome.nividic.om;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import fr.ens.transcriptome.nividic.om.io.GPRReader;
import fr.ens.transcriptome.nividic.om.io.NividicIOException;

import junit.framework.TestCase;

public class SerializationTest extends TestCase {

  public void testBioAssay1() throws FileNotFoundException, IOException,
      ClassNotFoundException {

    BioAssay b = BioAssayFactory.createBioAssay();

    File f = new File("/tmp/bioassaySerialized");

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
    oos.writeObject(b);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
    BioAssay copy = (BioAssay) ois.readObject();
    ois.close();

    assertEquals(b.getBiologicalId(), copy.getBiologicalId());

    f.delete();
  }

  public void testBioAssay2() throws FileNotFoundException, IOException,
      ClassNotFoundException, NividicIOException {

    InputStream is = this.getClass().getResourceAsStream("/files/testGPR3.gpr");
    GPRReader gprr = new GPRReader(is);
    BioAssay b = gprr.read();

    File f = new File("/tmp/bioassaySerialized");

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
    oos.writeObject(b);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
    BioAssay copy = (BioAssay) ois.readObject();
    ois.close();

    assertEquals(b.getBiologicalId(), copy.getBiologicalId());

    f.delete();
  }

}

Add a class to test serialization of objects

git-svn-id: 5d5bc0d97dbe9d074e4c1656445fd2f468e4e619@378 5a62d92b-e016-0410-9103-b89fe532bb34


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

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

/**
 * A type of Plugin builder that can be used to configure and create a plugin instance using a Java DSL instead of
 * through a configuration file. These builders are primarily useful for internal code and unit tests, but they can
 * technically be used as a verbose alternative to configuration files.
 *
 * <p>
 *     When creating plugin builders, it is customary to create the builder class as a public static inner class
 *     called {@code Builder}. For instance, the builder class for
 *     {@link org.apache.logging.log4j.core.layout.PatternLayout PatternLayout} would be
 *     {@code PatternLayout.Builder}.
 * </p>
 *
 * @param <T> the Plugin class this is a builder for.
 */
public interface ConfigurablePluginBuilder<T> {

    /**
     * Builds the plugin object after all configuration has been set. This will use default values for any
     * unspecified attributes for the plugin.
     *
     * @return the configured plugin instance.
     */
    T build();
}

Add interface for building plugins in Java instead of XML/JSON.

  - Part of LOG4J2-653.

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


package org.openregistry.core.domain.jpa;

import static org.junit.Assert.*;

import org.junit.Test;
import org.openregistry.core.domain.Address;
import org.openregistry.core.domain.Country;
import org.openregistry.core.domain.Region;
import org.openregistry.core.domain.jpa.sor.JpaSorAddressImpl;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(locations = {"classpath:base-integration-tests.xml"})

public class JpaSorAddressImplTests {

	@Test
	public void testSetValidRegion () {
		Address sorAddress = new JpaSorAddressImpl();
		Region validRegion = new JpaRegionImpl();

		assertNull("Region must be null before setting", sorAddress.getRegion());
		sorAddress.setRegion(validRegion);
		assertNotNull("Region must not be null after setting", sorAddress.getRegion());
	}

	@Test
	public void testSetNullRegion () {
		Address sorAddress = new JpaSorAddressImpl();
		Region validRegion = new JpaRegionImpl();
		sorAddress.setRegion(validRegion);

		assertNotNull("Region must not be null before setting it to null", sorAddress.getRegion());
		sorAddress.setRegion(null);
		assertNull("Region must be null after setting it to null", sorAddress.getRegion());
	}

    @Test(expected = IllegalArgumentException.class)
    public void testSetIncorrectRegionType() {

		Address sorAddress = new JpaSorAddressImpl();

    	// This implements Region but is not instance of JpaRegionImpl
    	Region invalidRegion = new Region() {
			public String getName() {
				return null;
			}
			public String getCode() {
				return null;
			}
			public Country getCountry() {
				return null;
			}
    	};
    	sorAddress.setRegion(invalidRegion);
    }
}

Test for OR-346: setting valid, invalid and null region (initial version)

git-svn-id: 996c6d7d570f9e8d676b69394667d4ecb3e4cdb3@25347 1580c273-15eb-1042-8a87-dc5d815c88a0


package com.example.playground.monadic.parser.combinators;

import org.junit.Test;

import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ZeroParserTest {
    @Test
    public void shouldAlwaysReturnEmptyList() {
        final Parser<Integer, Integer, IntStream> parser = Parsers.<Integer, Integer, IntStream>zero();
        final String input = "word";
        final List<ParserResult<Integer, Integer, IntStream>> actualParserResults = parser.parse(input.chars());

        assertThat(actualParserResults, is(equalTo(Collections.emptyList())));
    }
}

Add simple test for zero parser

Add simple test for zero parser


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.fudgemsg;

import java.util.List;

import org.testng.annotations.Test;

import com.google.common.collect.ImmutableList;
import com.opengamma.engine.function.config.FunctionConfigurationDefinition;
import com.opengamma.engine.function.config.ParameterizedFunctionConfiguration;
import com.opengamma.engine.function.config.StaticFunctionConfiguration;
import com.opengamma.util.test.AbstractFudgeBuilderTestCase;
import com.opengamma.util.test.TestGroup;

/**
 * Tests {@link FunctionConfigurationDefinitionFudgeBuilder}
 */
@Test(groups = TestGroup.UNIT)
public class FunctionConfigurationDefinitionBuilderTest extends AbstractFudgeBuilderTestCase {

  @Test
  public void functionConfigurationDefinition() {
    List<String> otherConfigs = ImmutableList.of("CF1", "CF2", "CF3");
    List<StaticFunctionConfiguration> staticFunctions = ImmutableList.of(new StaticFunctionConfiguration("SF1"),
        new StaticFunctionConfiguration("SF2"));
    List<ParameterizedFunctionConfiguration> parameterizedFunctions = ImmutableList.of(
        new ParameterizedFunctionConfiguration("PF1", ImmutableList.of("P11", "P12")),
        new ParameterizedFunctionConfiguration("PF2", ImmutableList.of("P21", "P22")));
    assertEncodeDecodeCycle(FunctionConfigurationDefinition.class, new FunctionConfigurationDefinition("FUNC_TEST", otherConfigs, staticFunctions, parameterizedFunctions));
  }

}

Add unit test for fudge builder

Add unit test for fudge builder


/*
 * Copyright 2016, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * 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
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.server;

/**
 * @author Dmytro Dashenkov
 */
public class SubscriptionServiceShould {

}

Create class for subscription service tests.


package net.tlahmann.gdg.creation.helper;

public class Tuple<X, Y> {
	public X x;
	public Y y;

	public Tuple(X x, Y y) {
		this.x = x;
		this.y = y;
	}
}

Add Tupel class to hold min and max value


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.daytron.revworks.ui.dashboard;

import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;

/**
 * The screen when a user tried to navigate to a view that does not exist.
 *
 * @author Ryan Gilera
 */
public class ErrorView extends VerticalLayout implements View {

    private final Label errorLabel;

    public ErrorView() {
        setMargin(true);
        setSpacing(true);

        Label headerErrorLabel = new Label("The view could not be found!");
        headerErrorLabel.addStyleName(Reindeer.LABEL_H1);

        addComponent(headerErrorLabel);

        this.errorLabel = new Label();
        addComponent(this.errorLabel);
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        String message = String.format(
                "You attempted to navigate to a view ('%s') "
                + "that does not exist.",
                event.getViewName());

        this.errorLabel.setValue(message);
    }

}

Add an errow view for navigator

Add an errow view for navigator


/*
 * Copyright 2020 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
 *
 *      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 org.springframework.cloud.vault.config;

import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import org.springframework.cloud.vault.util.TestRestTemplateFactory;
import org.springframework.vault.client.ClientHttpConnectorFactory;
import org.springframework.vault.core.ReactiveVaultTemplate;
import org.springframework.vault.support.ClientOptions;

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

/**
 * Integration tests for {@link VaultReactiveHealthIndicator}.
 *
 * @author Mark Paluch
 */
public class VaultReactiveHealthIndicatorIntegrationTests extends IntegrationTestSupport {

	@Test
	public void shouldReturnHealthState() {

		ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(
				TestRestTemplateFactory.TEST_VAULT_ENDPOINT, ClientHttpConnectorFactory
				.create(new ClientOptions(), Settings
						.createSslConfiguration()), () -> Mono.just(Settings.token()));

		VaultReactiveHealthIndicator healthIndicator = new VaultReactiveHealthIndicator(vaultTemplate);

		healthIndicator.doHealthCheck(Health.up()).as(StepVerifier::create)
				.consumeNextWith(actual -> {
					assertThat(actual.getStatus()).isEqualTo(Status.UP);
				}).verifyComplete();
	}
}

Add integration test for VaultReactiveHealthIndicator

Add test for the reactive health indicator.

See gh-397


/*
 * Transient.java June 2007
 *
 * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */

package simple.xml;

import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;

/**
 * The Transient annotation is an optional annotation
 * that can be used within an XML class schema to mark a method or
 * field as being transient, which indicates that it does not take
 * part in serialization or deserialization. This is used only as
 * a means to illustrate to the reader of your class that this has
 * not impact on the XML representation of the object. Fields or
 * methods annotated with this will be ignored, as will those that
 * contain no XML annotations.
 *
 * @author Niall Gallagher
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Transient {
}

Add the optional transient annotation

Add the optional transient annotation

git-svn-id: 4741f78aa2d3279ddd0a34c053c42ca3ce19451b@703 124fc276-1b20-0410-8d16-dc08e6bff5e9


/* @(#)MoveFitness.java
 */
/**
 *  Class containing all of the business logic regarding whether a
 *  move is considered good or not.
 *
 * @author Geoff Shannon
 */

package wall_follower;

public class MoveFitness {

    // TODO: fix these values!!! Set arbitrarily for right now
    private static final float MIN_GOOD_DISTANCE = 0.1f;
    private static final float MAX_GOOD_DISTANCE = 1.0f;

    private int goodMoves;
    private int badMoves;

    /**
     *  Overall, the way that we score moves is this: there is a
     *  predefined "good" range.  If the move caused us to stay in
     *  that range, then it was good.  If we were outside the range,
     *  then if the move put us closer to that range it was good.
     *  Otherwise, it was a bad move.
     */
    public void scoreMove(SensorReading before, SensorReading after) {

        if (inGoodRange(before.distance)) {
            if (inGoodRange(after.distance)) {
                goodMoves++;
            } else {
                badMoves++;
            }
        } else {
            // If deltaDistance is positive then we moved away from
            // the wall, if it is negative then we moved closer.
            float deltaDistance = after.distance - before.distance;

            // If we were too close, and got farther away: good
            if (before.distance < MIN_GOOD_DISTANCE &&
                deltaDistance > 0) {
                goodMoves++;
            // Or if we were too far and got closer: good
            } else if (before.distance > MAX_GOOD_DISTANCE &&
                       deltaDistance < 0) {
                goodMoves++;

            } else {
                badMoves++;
            }
        }
    }

    public float getFitness() {
        return goodMoves / badMoves;
    }

    private static boolean inGoodRange(float distance) {
        return (distance >= MIN_GOOD_DISTANCE) &&
            (distance <= MAX_GOOD_DISTANCE);
    }
}

Add a simplistic move fitness evaluation


/*
 * Copyright (c) 2011-2019, PCJ Library, Marek Nowicki
 * All rights reserved.
 *
 * Licensed under New BSD License (3-clause license).
 *
 * See the file "LICENSE" for the full license governing this code.
 */
package org.pcj.test;

import org.pcj.PCJ;
import org.pcj.RegisterStorage;
import org.pcj.StartPoint;
import org.pcj.Storage;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Marek Nowicki (faramir@mat.umk.pl)
 */
@RegisterStorage(AbortTest.Vars.class)
public class AbortTest implements StartPoint {
    @Storage(AbortTest.class)
    enum Vars {wait}

    private boolean wait;

    public static void main(String[] args) {
        Level level = Level.INFO;
//        Level level = Level.CONFIG;
        Logger logger = Logger.getLogger("");
        Arrays.stream(logger.getHandlers()).forEach(handler -> handler.setLevel(level));
        logger.setLevel(level);

        String[] nodes = {
                "localhost:8091",
                "localhost:8002",
                "localhost:8003",
                "localhost:8004",
                "localhost:8091",
                "localhost:8002",
                "localhost:8003",
                "localhost:8004",
        };

        PCJ.executionBuilder(AbortTest.class)
                .addNodes(nodes)
                .deploy();
    }

    @Override
    public void main() throws Throwable {
        if (PCJ.myId() == 2) {
            Thread.sleep(1_000);
            throw new RuntimeException("Thread-" + PCJ.myId() + ": Abort");
        }
        PCJ.at(0, () -> {
            try {
                Thread.sleep(2_000);
            } catch (Exception e) {
                System.err.println("Thread-" + PCJ.myId() + " exception: " + e);
            }
            PCJ.waitFor(Vars.wait);
        });
        try {
            Thread.sleep(2_000);
        } catch (Exception e) {
            System.err.println("Thread-" + PCJ.myId() + " exception: " + e);
        }
        PCJ.waitFor(Vars.wait);
    }
}

Stop PCJ threads on error/abort.

Stop PCJ threads on error/abort.


package javaAnagrams;

import java.util.Scanner;

public class Solution {

	   static boolean isAnagram(String A, String B) {
		   if( A.length() != B.length() )
			   return false;
		   int arrayLength = 256;
	       int[] arrayOne = new int[arrayLength],
	    		 arrayTwo = new int[arrayLength];
	       for(int i = 0; i < A.length(); ++i) {
	    	   arrayOne[(A.charAt(i) - '0' - 1)] += 1;
	    	   arrayTwo[(B.charAt(i) - '0' - 1)] += 1;
	       }
	       for(int i = 0; i < arrayLength; ++i) {
	    	   if(arrayOne[i] != arrayTwo[i])
	    		  return false;
	       }
		   return true;
	   }
	    public static void main(String[] args) {
	        Scanner scanner = new Scanner(System.in);
	        String wordOne = scanner.next();
	        String wordTwo = scanner.next();
	        boolean decision = isAnagram(wordOne.toLowerCase(), wordTwo.toLowerCase());
	        if(decision)
	        	System.out.println("Anagrams");
	        else
	        	System.out.println("Not Anagrams");
	        scanner.close();
	    }
	}

Add problem Java Anagrams, HackerRank/Java/Strings/Java String


package org.jsmpp.util;

import static org.testng.Assert.*;
import org.jsmpp.bean.DeliveryReceipt;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class DeliveryReceiptParserTest {
    private PDUDecomposer decomposer = new DefaultDecomposer();
    private static final String ORIGINAL_MESSAGE = "testing jsmpp bow";

    @Test
    public void parseTextWithLowerCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parsingTextWithUpperCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parseWithNoTextAttribute() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), null);
        } catch (InvalidDeliveryReceiptException e) {
            e.printStackTrace();
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }
}

Add delivery receipt test case

Add delivery receipt test case

git-svn-id: 8aef34885c21801cc977f98956a081c938212632@181 1678c8a9-8d33-0410-b0a4-d546c816ed44


/*
 * 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-30
 * Site       : https://www.acmicpc.net/problem/8958
 */

public class Boj8958 {

    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=0; i<n; i++){
            char[] inputs = br.readLine().toCharArray();
            int result = 0;
            for(int j=0; j<inputs.length; ) {
                int count = 0;
                while(inputs[j] == 'O') {
                    count++;
                    j++;
                    if(j==inputs.length){
                        break;
                    }
                }
                result += count*(count+1)/2;
                j++;
            }
            System.out.println(result);
        }
    }

}

Solve No.8958 from Baekjoon Online Judge


package com.grayben.riskExtractor;

import java.io.File;

import com.grayben.riskExtractor.htmlScorer.HtmlScorer;
import com.grayben.riskExtractor.htmlScorer.ArrayListScoredText;
import com.grayben.riskExtractor.htmlScorer.TreeHtmlScorer;

public class RiskExtractor {

	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		checkArgs(args);
		String fileName = args[0];
		File htmlFile = new File(fileName);
		String charsetName = args[1];
		HtmlScorer scorer = new TreeHtmlScorer();
		ArrayListScoredText scoredText = scorer.scoreHtml(htmlFile, charsetName);
		System.out.print(scoredText.toString());
		System.out.println();
		System.out.println("Program finished.");
		long endTime = System.currentTimeMillis();
		long secondsElapsed = (endTime - startTime)/1000;
		System.out.println("Time elapsed: " + secondsElapsed);

	}

	private static void checkArgs(String[] args){
		int argsLen = 2;
		if(args.length != argsLen){
			System.err.println("ERROR: must pass " + argsLen + " arguments.");
			System.exit(1);
		}
	}

}

Add driving class with main method

Add driving class with main method


package org.opencompare;

import org.junit.Assert;
import org.junit.Test;
import org.opencompare.api.java.PCMElement;
import org.opencompare.api.java.PCMFactory;
import org.opencompare.api.java.Value;
import org.opencompare.api.java.util.PCMVisitor;
import org.opencompare.api.java.value.BooleanValue;
import org.opencompare.model.impl.BooleanValueImpl;

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

/**
 * @author Moussa Lydia
 */
public class TraitementPcmTest {

    @Test
    public void testWhenFileExistsGetPcmIsNotNull() throws IOException {
        // si le fichier pcm exist
        final File file = new File("pcms/Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita_0.pcm");
        // et que je crée le TraitementPcm
        final TraitementPcm traitementPcm = new TraitementPcm(file);
        // alors getPcm ne doit pas être null
        Assert.assertNotNull(traitementPcm.getPcm());
        Assert.assertEquals("Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita", traitementPcm.getPcm().getName());
    }
}

Test TraitementPcm getPcm is not null

Test TraitementPcm getPcm is not null


package org.jsconf.core.test;

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

import org.jsconf.core.ConfigurationFactory;
import org.jsconf.core.sample.bean.ConfigBean;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

//Required to put ${java.io.tmpdir} on classpath
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class RealReloadingTest {
	private static final String TIC = "Tic";

	private static final String TAC = "Tac";

	private static File createTempFile;

	@Autowired
	private ConfigBean conf;

	@Autowired
	private ConfigurationFactory factory;

	@BeforeClass
	public static void init() throws IOException, InterruptedException {
		String prefix = Long.toString(System.nanoTime());
		createTempFile = File.createTempFile(prefix, "_app.conf");
		createTempFile.deleteOnExit();
		write(TIC);
	}

	@Test
	@Repeat
	public void test() throws IOException, InterruptedException {
		final Object ref = this.conf;
		Assert.assertNotNull(this.conf);
		Assert.assertEquals(TIC, this.conf.getUrl());

		write(TAC);

		Assert.assertTrue(ref == this.conf);
		Assert.assertEquals(TAC, this.conf.getUrl());
	}

	private static void write(String value) throws IOException, InterruptedException {
		createTempFile.delete();
		createTempFile.createNewFile();
		try (FileWriter fw = new FileWriter(createTempFile)) {
			fw.append("simpleConf : {  url : \"" + value + "\" }");
		}
		Thread.sleep(1000);
	}

	@Configuration
	static class ContextConfiguration {
		@Bean
		public ConfigurationFactory configurationFactory() {
			return new ConfigurationFactory().withResourceName(createTempFile.getName())//
					.withBean("simpleConf", ConfigBean.class, null, true);
		}
	}
}

Add new true reloading test

Add new true reloading test


package eme;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import eme.generator.EObjectGeneratorTest;
import eme.generator.EcoreMetamodelGeneratorTest;

@RunWith(Suite.class)

@SuiteClasses({
    EcoreMetamodelGeneratorTest.class,
    EObjectGeneratorTest.class
})

public class AllHeadlessTests {
}

ADD: Test suite for test that will be run as a normal JUnit test.


package SecureElection.Common;

/**
 * Created by kalas on 2015-11-20.
 */
public class Settings {
    public static final int CLA_PORT = 8988;
    public static final int CTF_PORT = 8989;
    public static final String KEYLOCATION = "./assets/";
}

Add settings class to common package

Add settings class to common package


package leetcode.symmetric_tree;

import common.TreeNode;

public class Solution {
	public boolean isSymmetric(TreeNode root) {
		if(root == null) return true;
		return isSymmetric(root.left, root.right);
	}
	private static boolean isSymmetric(TreeNode left, TreeNode right) {
		if(left == null && right == null) return true;
		if(left != null && right == null) return false;
		if(left == null && right != null) return false;
		if(left.val != right.val) return false;
		return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
	}

}

Add java solution for 101. Symmetric Tree

101. Symmetric Tree: https://leetcode.com/problems/symmetric-tree/


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.shell.command;

import alluxio.AlluxioURI;
import alluxio.client.block.AlluxioBlockStore;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.exception.AlluxioException;

import org.apache.commons.cli.CommandLine;

import java.io.IOException;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Displays the path's info.
 * If path is a directory it displays the directory's info.
 * If path is a file, it displays the file's all blocks info.
 */
@ThreadSafe
public final class StatCommand extends WithWildCardPathCommand {
  /**
   * @param fs the filesystem of Alluxio
   */
  public StatCommand(FileSystem fs) {
    super(fs);
  }

  @Override
  public String getCommandName() {
    return "stat";
  }

  @Override
  protected void runCommand(AlluxioURI path, CommandLine cl) throws AlluxioException, IOException {
    URIStatus status = mFileSystem.getStatus(path);
    if (status.isFolder()) {
      System.out.println(path + " is a directory path.");
      System.out.println(status);
    } else {
      System.out.println(path + " is a file path.");
      System.out.println(status);
      System.out.println("Containing the following blocks: ");
      AlluxioBlockStore blockStore = AlluxioBlockStore.create();
      for (long blockId : status.getBlockIds()) {
        System.out.println(blockStore.getInfo(blockId));
      }
    }
  }

  @Override
  public String getUsage() {
    return "stat <path>";
  }

  @Override
  public String getDescription() {
    return "Displays info for the specified path both file and directory.";
  }
}

Add stat command class file

Add stat command class file


package org.hisp.dhis.android.core.datavalue;

import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;

import org.hisp.dhis.android.core.common.State;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import org.hisp.dhis.android.core.utils.StoreUtils;

import java.util.ArrayList;
import java.util.Collection;

public class DataValueSetStore {

    private static final String QUERY_WITH_STATE = "SELECT " +
            DataValueModel.Columns.DATA_ELEMENT + "," +
            DataValueModel.Columns.PERIOD + "," +
            DataValueModel.Columns.ORGANISATION_UNIT + "," +
            DataValueModel.Columns.VALUE +
            " FROM " +
            DataValueModel.TABLE +
            " WHERE " +
            DataValueModel.Columns.STATE +
            " = ':state'";

    private static final String UPDATE_STATE = "UPDATE "
            + DataValueModel.TABLE +
            " SET " +
            DataValueModel.Columns.STATE + " = ? " +
            " WHERE " +
            DataValueModel.Columns.DATA_ELEMENT + " = ?;";

    private final DatabaseAdapter databaseAdapter;
    private final SQLiteStatement updateStateStatement;

    public DataValueSetStore(DatabaseAdapter databaseAdapter) {

        this.databaseAdapter = databaseAdapter;
        this.updateStateStatement = databaseAdapter.compileStatement(UPDATE_STATE);
    }

    public Collection<DataValue> getDataValuesWithState(State state) {
        return queryDataValuesWithState(state);
    }

    private Collection<DataValue> queryDataValuesWithState(State state) {

        String query = QUERY_WITH_STATE.replace(":state", state.name());

        Cursor cursor = databaseAdapter.query(query);

        return map(cursor);
    }

    private Collection<DataValue> map(Cursor cursor) {

        Collection<DataValue> dataValues = new ArrayList<>();

        cursor.moveToFirst();

        if (cursor.getCount() > 0) {

            do {

                DataValue dataValue = DataValue.create(
                        cursor.getString(0),
                        cursor.getString(1),
                        cursor.getString(2),
                        null,
                        null,
                        cursor.getString(3),
                        null,
                        null,
                        null,
                        null,
                        null,
                        null
                );

                dataValues.add(dataValue);

            } while(cursor.moveToNext());
        }

        return dataValues;
    }

    /**
     * @param dataElementUid UID from the DataElement related to the DataValue you want to set
     * @param newState The new state to be set for the DataValue
     *
     * @return True if any DataValue has been updated
     */
    @SuppressWarnings("PMD.UselessParentheses")
    public boolean setState(String dataElementUid, State newState) {

        StoreUtils.sqLiteBind(updateStateStatement, 1, newState.name());
        StoreUtils.sqLiteBind(updateStateStatement, 2, dataElementUid);

        int updatedRows = databaseAdapter.executeUpdateDelete(DataValueModel.TABLE, updateStateStatement);
        updateStateStatement.clearBindings();

        return (updatedRows > 0);
    }
}

Add DB store for DataValueSets

Add DB store for DataValueSets


/**
 * The MIT License
 * Copyright (c) 2014 Ilkka Seppälä
 *
 * 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.iluwatar.hexagonal.domain;

/**
 *
 * Provides notifications for lottery events.
 *
 */
public interface LotteryNotifications {

  void notifyTicketSubmitted(PlayerDetails details);
  void notifyNoWin(PlayerDetails details);
  void notifyPrize(PlayerDetails details);

}

Add interface for lottery event notifications


package learn_to_code.java_api.io_and_nio.nio;

import learn_to_code.java_api.io_and_nio.io.FilesCreatorIO;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

        /* This 2 calls will create directories for both nio and io files.
        * We will try to filter out only directory with 'nio' as part of the name*/
        FilesCreatorNIO.createFiles();
        FilesCreatorIO.createFiles();

        Path startPath = Paths.get(FilesCreatorNIO.getDirNIOFiles()).getParent();

        /* Only accept directories which contain NIO. DirectoryStream can be worked with using foreach cycle */
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(startPath,
                e -> e.toString().toLowerCase().contains("nio"))) {
            for (Path path: ds) {
                System.out.println(path.toAbsolutePath());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Add DirectoryStream example with filter

Add DirectoryStream example with filter


package com.deepak.Strings;

/**
 *
Problem Statement

 *
 Given a string of characters consisting of 0 or more spaces,
 * remove all the spaces from this given string.
 * Separation of spaces from other characters should be done in-place(without using extra space).
 * Expected time and space complexity is O(n).
 * For example, if the input string is "  Hi, How are you?  "
 * then the output returned should be "Hi,Howareyou?"

 *
 * @author Deepak
 */
public class RemoveSpaces {

	/**
	 * Method to start the flow of the program
	 * @param args
	 */
	public static void main(String[] args) {
		String strWithSpaces = "  Hey, How are you doing?? ";
		String strWithOutSpaces = removeSpaces(strWithSpaces);
		System.out.println("Actual String => " + strWithSpaces);
		System.out.println("String after removing spaces => " + strWithOutSpaces);
	}

	/**
	 * Method to remove spaces with O(n^2) complexity [Not recommended]
	 *
 Algorithm :
	 * 1. Convert the entire string to char Array
	 * 2. Loop through it and search for white space
	 * 3. If found, loop through the array on right side
	 * 4. Shift each element to left and decrease the array size by 1
	 * 5. Repeat step 2-4 until all the white spaces are removed

	 *
	 * @param strWithSpaces
	 * @return {@link String}
	 */
	private static String removeSpaces(String strWithSpaces) {
		char[] strToCharArray = strWithSpaces.toCharArray();
		int charArraySize = strToCharArray.length;
		for (int i = 0; i < charArraySize; i++) {
			if (strToCharArray[i] == ' ') {
				for (int j = i; j < charArraySize - 1; j++) {
					strToCharArray[j] = strToCharArray[j+1];
				}
				charArraySize--;
			}
		}
		return new String(strToCharArray);
	}

}

Remove Spaces - O(n^2) complexity [Not recommended]


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

/**
 * Thrown when a command execution fails.
 *
 * @version $Rev$ $Date$
 */
public class CommandExecutionFailied
    extends Exception
{
    public CommandExecutionFailied(final Throwable cause) {
        super(cause);
    }
}

Add new exception type when commands fail

git-svn-id: cd28ba526fba5b39766c0a4e72305690b33c2c6e@662168 13f79535-47bb-0310-9956-ffa450edef68


package com.jshoresdevelopment.conversioncalculator;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AllUnitListItem {
    private String value;
    private String unit;

    public AllUnitListItem(String value, String unit) {
        this.value = value;
        this.unit = unit;
    }
}

Add convert all list item class.

Add convert all list item class.


package leetcode.permutations;

import java.util.ArrayList;

public class Solution {
	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, int[] num, int depth, boolean visit[]){
		if(depth == num.length){
			ans.add(new ArrayList<Integer>(cur));
		}else{
			for(int i = 0; i < num.length; i++){
				if(!visit[i]){
					visit[i] = true;
					cur.add(num[i]);
					dfs(ans, cur, num, depth + 1, visit);
					visit[i] = false;
					cur.remove(depth);
				}
			}
		}
	}
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        if(num == null || num.length == 0) return ans;
        boolean[] visit = new boolean[num.length];
        dfs(ans, new ArrayList<Integer>(), num, 0, visit);
        return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> ary : new Solution().permute(new int[]{2,3,4,5,6})){
    		for(int x : ary){
    			System.err.print(x + ", ");
    		}
    		System.err.println("");;
    	}
    }
}

Add java solution for 46. Permutations

Add java solution for 46. Permutations

46. Permutations: https://leetcode.com/problems/permutations/


package com.elmakers.mine.bukkit.world.block.builtin;

import java.util.Deque;
import java.util.Random;
import javax.annotation.Nonnull;

import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;

import com.elmakers.mine.bukkit.api.automata.Automaton;
import com.elmakers.mine.bukkit.utility.RandomUtils;
import com.elmakers.mine.bukkit.utility.WeightedPair;
import com.elmakers.mine.bukkit.world.BlockResult;
import com.elmakers.mine.bukkit.world.block.BlockRule;

public class AutomatonRule extends BlockRule {
    private Deque<WeightedPair<String>> automatonProbability;
    private ConfigurationSection parameters;

    @Override
    public boolean onLoad(ConfigurationSection parameters) {
        RandomUtils.populateStringProbabilityMap(automatonProbability, parameters, "automaton");
        this.parameters = parameters.getConfigurationSection("automaton_parameters");
        return !automatonProbability.isEmpty();
    }

    @Override
    @Nonnull
    public BlockResult onHandle(Block block, Random random, Player cause) {
        String automatonKey = RandomUtils.weightedRandom(automatonProbability);

        if (automatonKey.equalsIgnoreCase("none")) {
            return BlockResult.SKIP;
        }
        try {
            BlockResult result = BlockResult.valueOf(automatonKey.toUpperCase());
            return result;
        } catch (Exception ignore) {
        }

        Location location = block.getLocation();
        Automaton automaton = controller.addAutomaton(location, automatonKey, null, null, parameters);
        return automaton == null ? BlockResult.SKIP : BlockResult.REMOVE_DROPS;
    }
}

Add Automaton block replace rule

Add Automaton block replace rule


package io.quarkus.gradle;

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

import java.io.File;

import org.junit.jupiter.api.Test;

public class JandexMultiModuleTest extends QuarkusGradleWrapperTestBase {

    @Test
    public void testBasicMultiModuleBuild() throws Exception {

        final File projectDir = getProjectDir("jandex-basic-multi-module-project");

        BuildResult build = runGradleWrapper(projectDir, "clean", ":application:quarkusBuild");
        assertThat(build.getTasks().get(":common:jandex")).isEqualTo(BuildResult.SUCCESS_OUTCOME);
        assertThat(build.getTasks().get(":application:quarkusBuild")).isEqualTo(BuildResult.SUCCESS_OUTCOME);
    }

}

Test that jandex plugin is ran on quarkusBuild task


package ru.stqa.pft.sandbox;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by Alexander Gorny on 1/25/2017.
 */
public class DistanceTest {

  @Test
  public void testDistance(){

    Point p1 = new Point(0, 0);
    Point p2 = new Point(60, 80);

    Assert.assertEquals(p1.distance(p2), 100.0);

    p2.x = 30;
    p2.y = 40;
    Assert.assertEquals(p1.distance(p2), 50.0);

    p1.x = -2.3;
    p1.y = 4;
    p2.x = 8.5;
    p2.y = 0.7;
    Assert.assertEquals(p1.distance(p2), 11.292918134831227);

    p1.x = -25;
    p1.y = -1;
    p2.x = -25;
    p2.y = -1;
    Assert.assertEquals(p1.distance(p2), 0.0);

    p1.x = -25;
    p1.y = -1;
    p2.x = -25;
    p2.y = -1;
    Assert.assertEquals(p1.distance(p2), 0.0);

    p1.x = 67;
    p1.y = 13;
    p2.x = 67;
    p2.y = 1313;
    Assert.assertEquals(p1.distance(p2), 1300.0);

  }

}

Add tests for CalculateDistance class

Add tests for CalculateDistance class


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static com.google.common.truth.Truth.assertThat;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormAttributeEntityTest {

    @Test
    public void shouldSetFormAttributeEntityTest() {
        FormAttributeEntity formAttributeEntity = TestEntityFixtures.getFormAttributeEntity();
        assertThat(formAttributeEntity).isNotNull();
        assertThat(formAttributeEntity.getKey()).isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getFormId())
                .isEqualTo(1l);
        assertThat(formAttributeEntity.getKey())
                .isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getLabel())
                .isEqualTo("Test varchar");
        assertThat(formAttributeEntity.getRequired())
                .isFalse();
        assertThat(formAttributeEntity.getPriority())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getCardinality())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getOptions()).isNull();
    }
}

Add test for form attribute

Add test for form attribute


package com.novoda.downloadmanager;

import android.os.StatFs;

import java.io.File;

public final class ByteBasedStorageRequirementRule implements StorageRequirementRule {

    private final StorageCapacityReader storageCapacityReader;
    private final long bytesRemainingAfterDownload;

    public static ByteBasedStorageRequirementRule withPercentageOfStorageRemaining(long bytesRemainingAfterDownload) {
        return new ByteBasedStorageRequirementRule(new StorageCapacityReader(), bytesRemainingAfterDownload);
    }

    private ByteBasedStorageRequirementRule(StorageCapacityReader storageCapacityReader, long bytesRemainingAfterDownload) {
        this.storageCapacityReader = storageCapacityReader;
        this.bytesRemainingAfterDownload = bytesRemainingAfterDownload;
    }

    @Override
    public boolean hasViolatedRule(File storageDirectory,
                                   FileSize downloadFileSize) {
        StatFs statFs = new StatFs(storageDirectory.getPath());
        long storageCapacityInBytes = storageCapacityReader.storageCapacityInBytes(statFs);
        long usableStorageInBytes = storageDirectory.getUsableSpace();
        long remainingStorageAfterDownloadInBytes = usableStorageInBytes - downloadFileSize.totalSize();

        Logger.v("Storage capacity in bytes: ", storageCapacityInBytes);
        Logger.v("Usable storage in bytes: ", usableStorageInBytes);
        Logger.v("Minimum required storage in bytes: ", bytesRemainingAfterDownload);
        return remainingStorageAfterDownloadInBytes < bytesRemainingAfterDownload;
    }

}

Create a byte based storage requirement rule.


package me.haosdent.cgroup.subsystem;

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

public class TestFreezer {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testSetState() {}

  @Test
  public void testGetState() {}
}

Add freezer subsystem test class.

Add freezer subsystem test class.


/*
 * Licensed to the University of California, Berkeley 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 tachyon.examples.keyvalue;

import tachyon.TachyonURI;
import tachyon.Version;
import tachyon.client.keyvalue.KeyValueStoreReader;
import tachyon.client.keyvalue.KeyValueStoreWriter;
import tachyon.client.keyvalue.KeyValueStores;

/**
 * A quick start tutorial for creating a key-value store, putting and getting some key-value pairs.
 */
public class KeyValueStoreQuickStart {
  /**
   * The main program.
   *
   * @param args one argument which is the path of the new key-value store
   * @throws Exception if any exception happens
   */
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.out.println("java -cp " + Version.TACHYON_JAR + " "
          + KeyValueStoreQuickStart.class.getName() + " <key-value store URI>");
      System.exit(-1);
    }

    TachyonURI storeUri = new TachyonURI(args[0]);
    KeyValueStores kvStore = KeyValueStores.Factory.create();

    // Creates a store.
    KeyValueStoreWriter writer = kvStore.create(storeUri);

    // Puts a key-value pair ("key", "value").
    String key = "key";
    String value = "value";
    writer.put(key.getBytes(), value.getBytes());
    System.out.println(String.format("(%s, %s) is put into the key-value store", key, value));

    // Completes the store.
    writer.close();

    // Opens a store.
    KeyValueStoreReader reader = kvStore.open(storeUri);

    // Gets the value for "key".
    System.out.println(String.format("Value for key '%s' got from the store is '%s'", key,
        new String(reader.get(key.getBytes()))));

    // Closes the reader.
    reader.close();
  }
}

Add a quickstart example for key-value store


package org.ngrinder.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.ngrinder.infra.annotation.TestOnlyComponent;

@TestOnlyComponent("pluggablePreAuthFilter")
public class MockPluggablePreAuthFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
					throws IOException,
					ServletException {
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}

[NGRINDER-209] Fix unit test errors and improve test coverage


package leetcode.largest_number;

import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    public String largestNumber(int[] num) {
        if(num == null || num.length == 0) return "";
        int length = num.length;
        String[] num_str = new String[length];
        for(int i = 0; i < length; i++){
            num_str[i] = String.valueOf(num[i]);
        }
        Arrays.sort(num_str, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return -(o1 + o2).compareTo(o2 + o1);
            }
        });
        StringBuilder ret = new StringBuilder();
        for(String str : num_str){
            ret.append(str);
        }
        String r = ret.toString().replaceAll("^0+", "");
        if(r.length() == 0){
            return "0";
        }else{
            return r;
        }
    }

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

Add java solution for 179. Largest Number

179. Largest Number: https://leetcode.com/problems/largest-number/


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public boolean isSameTree(TreeNode p, TreeNode q) {

        if (p == null || q == null) {
            return p == q;
        }

        if (p.val == q.val) {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        } else {
            return false;
        }

    }

}

Create : 100 Same Tree

Create : 100 Same Tree


/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.sig;

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

import com.adobe.pdfjt.core.exceptions.PDFIOException;
import com.adobe.pdfjt.core.exceptions.PDFInvalidDocumentException;
import com.adobe.pdfjt.core.exceptions.PDFSecurityException;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.services.digsig.SignatureFieldInterface;
import com.adobe.pdfjt.services.digsig.SignatureManager;

import com.datalogics.pdf.samples.SampleTest;

import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.util.Iterator;

/**
 * Tests the DocSigning Sample.
 */
public class DocSigningTest extends SampleTest {
    static final String FILE_NAME = "SignedField1.pdf";
    static final String QUALIFIED_SIGNATURE_FIELD_NAME = "SB1_Sig1";

    @Test
    public void testMain() throws Exception {
        final File file = newOutputFile(FILE_NAME);
        if (file.exists()) {
            Files.delete(file.toPath());
        }
        // The complete file name will be set in the DocSigning class.
        final String path = file.getCanonicalPath().replaceAll("1.pdf", "");

        DocSigning.main(path);
        // Make sure the Output file exists.
        assertTrue(file.getPath() + " must exist after run", file.exists());

        final PDFDocument doc = openPdfDocument(file.getCanonicalPath());

        try {
            // Make sure that Signature field is signed.
            final SignatureFieldInterface sigField = getSignedSignatureField(doc);
            assertTrue(sigField.isSigned());
            assertTrue(sigField.isVisible());
            assertEquals(QUALIFIED_SIGNATURE_FIELD_NAME, sigField.getQualifiedName());

        } finally {
            doc.close();
        }
    }

    private static SignatureFieldInterface getSignedSignatureField(final PDFDocument doc)
                    throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
        // Set up a signature service and get the first signature field.
        final SignatureManager sigService = SignatureManager.newInstance(doc);
        if (sigService.hasSignedSignatureFields()) {
            final Iterator<SignatureFieldInterface> iter = sigService.getDocSignatureFieldIterator();
            if (iter.hasNext()) {
                return iter.next();
            }
        }
        return null;
    }
}

Add Unit test for DocSigning Sample.

Add Unit test for DocSigning Sample.


package tests;

import static org.junit.Assert.*;

import org.junit.Test;
import logic.Score;

public class ScoreTests {

	@Test
	public void test_initScore() {
		Score score = new Score(2, 1);

		assertEquals("Score for Player 1 is not 2", 2, score.p1());
		assertEquals("Score for Player 2 is not 1", 1, score.p2());
	}

	@Test
	public void test_toString() {
		Score score = new Score(2, 1);

		assertEquals("toString is not correct", "Score for Player 1: 2 - Score for Player 2: 1", score.toString());
	}

}

Test cases for Score class

Test cases for Score class


package starpunk;

import com.badlogic.gdx.Game;

final class StarPunkGame
  extends Game
{
  public static final int WIDTH = 1280;
  public static final int HEIGHT = 900;

  StarPunkGame()
  {
  }

  @Override
  public void create()
  {
    setScreen( new GameScreen( this ) );
  }
}

Add in minimalistic game class

Add in minimalistic game class


/*
 * 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-10-01
 * Site       : https://www.acmicpc.net/problem/1157
 */

public class Boj1157 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputs = br.readLine().toLowerCase();
        int[] atoz = new int[26];
        for(int i=0; i<inputs.length(); i++){
            atoz[(int) inputs.charAt(i) - 97]++;
        }
        int max = -1;
        int maxi = 0;
        for(int i=0; i<atoz.length; i++){
            if(max < atoz[i]){
                max = atoz[i];
                maxi = i;
            }else if(max == atoz[i]){
                maxi = -2;
            }
        }
        System.out.println((char)(maxi+65));
    }

}

Solve No.1157 from Baekjoon Online Judge


package net.imagej.ops.viewOp;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendRandom;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ExtendRandom.class, name = ViewOps.ExtendRandom.NAME)
public class DefaultExtendRandom<T extends RealType<T>, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendRandom<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Parameter(type = ItemIO.INPUT)
	private double min;

	@Parameter(type = ItemIO.INPUT)
	private double max;

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendRandom(input, min, max);
	}
}

Add default implementation of ExtendRandom interface.


/*
 * Copyright 2014 Rackspace
 *
 *    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.rackspacecloud.blueflood.utils;

import com.rackspacecloud.blueflood.outputs.serializers.BasicRollupsOutputSerializer;
import com.rackspacecloud.blueflood.outputs.utils.PlotRequestParser;
import junit.framework.Assert;
import org.junit.Test;

import java.util.*;

public class PlotRequestParserTest {

    @Test
    public void testSelectParams() {
        List<String> stats = new ArrayList<String>();
        stats.add("average");
        stats.add("min");
        stats.add("max");
        Set<BasicRollupsOutputSerializer.MetricStat> filters = PlotRequestParser.getStatsToFilter(stats);

        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.AVERAGE));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MIN));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MAX));

        // Alternate comma delimited notation
        stats = new ArrayList<String>();
        stats.add("average,min,max");
        filters = PlotRequestParser.getStatsToFilter(stats);
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.AVERAGE));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MIN));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MAX));
    }
}

Add test cases for parsing filters in plot requests