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

import io.github.robwin.markup.builder.asciidoc.AsciiDocBuilder;
import io.github.robwin.markup.builder.markdown.MarkdownBuilder;

/**
 * @author Robert Winkler
 */
public final class MarkupDocBuilders {

    private MarkupDocBuilders(){}

    public static MarkupDocBuilder documentBuilder(MarkupLanguage markupLanguage){
        switch(markupLanguage){
            case MARKDOWN: return new MarkdownBuilder();
            case ASCIIDOC: return new AsciiDocBuilder();
            default: return new AsciiDocBuilder();
        }
    }

}

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

import io.github.robwin.markup.builder.asciidoc.AsciiDocBuilder;
import io.github.robwin.markup.builder.markdown.MarkdownBuilder;

/**
 * @author Robert Winkler
 */
public final class MarkupDocBuilders {

    private MarkupDocBuilders(){}

    public static MarkupDocBuilder documentBuilder(MarkupLanguage markupLanguage){
        switch(markupLanguage){
            case MARKDOWN: return new MarkdownBuilder();
            case ASCIIDOC: return new AsciiDocBuilder();
            default: return new AsciiDocBuilder();
        }
    }

    /**
     * Instantiate a new builder copying {@code docBuilder} characteristics.
     * You can use it to build intermediate MarkupDocBuilder for composition purpose.
     */
    public static MarkupDocBuilder documentBuilder(MarkupDocBuilder docBuilder){
        if (docBuilder instanceof MarkdownBuilder)
            return new MarkdownBuilder();
        else if (docBuilder instanceof AsciiDocBuilder)
            return new AsciiDocBuilder();
        else
            return new AsciiDocBuilder();
    }

}

Create a builder instance from another builder instance, for easier composition


package edu.kit.ipd.sdq.vitruvius.framework.contracts.interfaces;

import edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes.Blackboard;

public interface ChangePreparing {
    void prepareAllChanges(Blackboard blackboard);
}

package edu.kit.ipd.sdq.vitruvius.framework.contracts.interfaces;

import edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes.ProcessableChange;
import edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes.RecordedChange;

public interface ChangePreparing {
    ProcessableChange prepareAllChanges(RecordedChange unpreparedChange);
}

Restructure change preparer to prepare recorded changes and return processable changes.


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.appoptics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.tck.MeterRegistryCompatibilityKit;

import java.time.Duration;

class AppOpticsMeterRegistryCompatibilityTest extends MeterRegistryCompatibilityKit {
    private final AppOpticsConfig config = new AppOpticsConfig() {
        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public boolean enabled() {
            return false;
        }
    };

    @Override
    public MeterRegistry registry() {
        return new AppOpticsMeterRegistry(config, new MockClock());
    }

    @Override
    public Duration step() {
        return config.step();
    }
}

/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.appoptics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.tck.MeterRegistryCompatibilityKit;

import java.time.Duration;

class AppOpticsMeterRegistryCompatibilityTest extends MeterRegistryCompatibilityKit {
    private final AppOpticsConfig config = new AppOpticsConfig() {
        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public boolean enabled() {
            return false;
        }

        @Override
        public String apiToken() {
            return "fake";
        }
    };

    @Override
    public MeterRegistry registry() {
        return new AppOpticsMeterRegistry(config, new MockClock());
    }

    @Override
    public Duration step() {
        return config.step();
    }
}

Use fake apiToken in AppOptics compatibility kit tests

The apiToken is required and constructing the AppOpticsMeterRegistry will fail fast without it now.


package com.gurkensalat.android.xingsync.api;

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

import com.googlecode.androidannotations.annotations.EBean;

@EBean
public class MeCall // implements XingApiCall
{
	private static final String TAG = "xingsync.MeCall";

	public JSONArray perform(final String... args)
	{
		// Hardcoded Mock for now

		StringBuffer sb = new StringBuffer(1024);

		sb.append("{");
		sb.append("  \"users\": [");
		sb.append("    {");
		sb.append("      \"id\": \"3382304_64b174\",");
		sb.append("      \"first_name\": \"Hakan\",");
		sb.append("      \"last_name\": \"Tandogan\",");
		sb.append("      \"display_name\": \"Hakan Tandogan\"");
		sb.append("    }");
		sb.append("  ]");
		sb.append("}");

		Log.i(TAG, sb.toString());

		JSONArray jsonArray = new JSONArray();
		try
		{
			jsonArray = new JSONArray(sb.toString());
			Log.i(TAG, jsonArray.toString());
		}
		catch (JSONException e)
		{
			Log.e(TAG, "while parsing answer string", e);
		}

		return jsonArray;
	}
}

package com.gurkensalat.android.xingsync.api;

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

import android.util.Log;

import com.googlecode.androidannotations.annotations.EBean;

@EBean
public class MeCall // implements XingApiCall
{
	private static final String TAG = "xingsync.MeCall";

	public JSONObject perform(final String... args)
	{
		// Hardcoded Mock for now

		StringBuffer sb = new StringBuffer(1024);

		sb.append("{");
		sb.append("  \"users\": [");
		sb.append("    {");
		sb.append("      \"id\": \"3382304_64b174\",");
		sb.append("      \"first_name\": \"Hakan\",");
		sb.append("      \"last_name\": \"Tandogan\",");
		sb.append("      \"display_name\": \"Hakan Tandogan\"");
		sb.append("    }");
		sb.append("  ]");
		sb.append("}");

		Log.i(TAG, sb.toString());

		JSONObject json = new JSONObject();
		try
		{
			json = new JSONObject(sb.toString());
			Log.i(TAG, json.toString());
		}
		catch (JSONException e)
		{
			Log.e(TAG, "while parsing answer string", e);
		}

		return json;
	}
}

Make the contract a JSONObject

Make the contract a JSONObject


package com.seatgeek.sixpack.android;

import com.seatgeek.sixpack.Alternative;
import com.seatgeek.sixpack.Experiment;
import com.seatgeek.sixpack.Sixpack;
import com.seatgeek.sixpack.SixpackBuilder;
import com.seatgeek.sixpack.log.LogLevel;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(
        injects = {
                SixpackActivity.class
        }
)
public class SixpackModule {
    public static final String BUTTON_COLOR = "button-color";
    public static final String BUTTON_COLOR_RED = "red";
    public static final String BUTTON_COLOR_BLUE = "blue";

    @Singleton @Provides Sixpack provideSixpack() {
        Sixpack sixpack = new SixpackBuilder()
                .setClientId(Sixpack.generateRandomClientId())
                .setSixpackUrl("http://10.0.3.2:5000/") // genymotion host
                .build();

        sixpack.setLogLevel(LogLevel.VERBOSE);

        return sixpack;
    }

    @Singleton @Provides @Named(BUTTON_COLOR) Experiment provideButtonColorExperiment(Sixpack sixpack) {
        return sixpack.experiment()
                .withName(BUTTON_COLOR)
                .withAlternatives(
                        new Alternative(BUTTON_COLOR_RED),
                        new Alternative(BUTTON_COLOR_BLUE)
                )
                .build();
    }
}

package com.seatgeek.sixpack.android;

import com.seatgeek.sixpack.Alternative;
import com.seatgeek.sixpack.Experiment;
import com.seatgeek.sixpack.Sixpack;
import com.seatgeek.sixpack.SixpackBuilder;
import com.seatgeek.sixpack.log.LogLevel;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.HttpUrl;

@Module(
        injects = {
                SixpackActivity.class
        }
)
public class SixpackModule {
    public static final String BUTTON_COLOR = "button-color";
    public static final String BUTTON_COLOR_RED = "red";
    public static final String BUTTON_COLOR_BLUE = "blue";

    @Singleton @Provides Sixpack provideSixpack() {
        Sixpack sixpack = new SixpackBuilder()
                .setClientId(Sixpack.generateRandomClientId())
                .setSixpackUrl(HttpUrl.parse("http://10.0.3.2:5000/")) // genymotion host
                .build();

        sixpack.setLogLevel(LogLevel.VERBOSE);

        return sixpack;
    }

    @Singleton @Provides @Named(BUTTON_COLOR) Experiment provideButtonColorExperiment(Sixpack sixpack) {
        return sixpack.experiment()
                .withName(BUTTON_COLOR)
                .withAlternatives(
                        new Alternative(BUTTON_COLOR_RED),
                        new Alternative(BUTTON_COLOR_BLUE)
                )
                .build();
    }
}

Fix compile error in android example app.


/**
 * Copyright (C) 2010 openecho
 *
 * 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 kinetic.math.statistic;

import java.lang.reflect.Array;

/**
 * Standard Deviation Utility
 *
 * @author openecho
 * @version 1.0.1
 */
public class StandardDeviation {
    public static Double evaluate(Double[] data) {
        if(data==null) {
            throw new NullPointerException();
        }
        int length = Array.getLength(data);
        if(length < 2) {
            throw new RuntimeException("More than two values are required to calculate a standard deviation");
        }
        double mean = Mean.evaluate(data);
        double sumDifferenceSquared = 0;
        for(int i=0;i<length;i++) {
            sumDifferenceSquared += Math.pow(data[i]-mean,2);
        }
        return Math.sqrt(sumDifferenceSquared/(length-1));
    }
}

/**
 * Copyright (C) 2010 openecho
 *
 * 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 kinetic.math.statistic;

import java.lang.reflect.Array;

/**
 * Standard Deviation Utility
 *
 * @author openecho
 * @version 1.0.1
 */
public class StandardDeviation {

    public static Double evaluate(Double[] data) {
        return StandardDeviation.evaluate(data, true);
    }

    public static Double evaluate(Double[] data, boolean partialPopulation) {
        if(data==null) {
            throw new NullPointerException();
        }
        int length = Array.getLength(data);
        if(length < 2) {
            throw new RuntimeException("More than two values are required to calculate a standard deviation");
        }
        double mean = Mean.evaluate(data);
        double sumDifferenceSquared = 0;
        for(int i=0;i<length;i++) {
            sumDifferenceSquared += Math.pow(data[i]-mean,2);
        }
        return Math.sqrt(sumDifferenceSquared/((partialPopulation) ? (length-1) : (length)));
    }
}

Add population based divide option

Add population based divide option


package org.concord.framework.otrunk.view;

import java.util.Vector;

import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;

public interface OTLabbookManager
{
	public void add(OTObject otObject);

	public void add(OTObject otObject, OTObject container);

	public void addSnapshot(OTObject snapshot);

	public void addDataCollector(OTObject dataCollector);

	public void addDrawingTool(OTObject drawingTool);

	public void addText(OTObject text);

	public void remove(OTObject labbookEntry);

	public Vector getSnapshots();

	public Vector getGraphs();

	public Vector getDrawings();

	public Vector getText();

	public Vector getAllEntries();

	public boolean isEmpty();

	public void addLabbookListener(OTChangeListener listener);

	public void removeLabbookListener(OTChangeListener listener);

//	public void setOTObjectService(OTObjectService objectService);

}

package org.concord.framework.otrunk.view;

import java.util.Vector;

import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;

public interface OTLabbookManager
{
	/*
	 * This object will be added directly to an entry, so the original should be cloned, preferably
	 * using the copy method in the OTLabbookViewProvider for the object
	 */
	public void add(OTObject otObject);

	/*
	 * If a refence to the original object is included, it will be easier to tie the entry back
	 * to its origins.
	 */
	public void add(OTObject otObject, OTObject originalObject);

	/*
	 * A container, such as the section the object was in, should be included to allow the lab
	 * book to sort based on contaner.
	 */
	public void add(OTObject otObject, OTObject originalObject, OTObject container);

	public void addSnapshot(OTObject snapshot);

	public void addDataCollector(OTObject dataCollector);

	public void addDrawingTool(OTObject drawingTool);

	public void addText(OTObject text);

	public void remove(OTObject labbookEntry);

	public Vector getSnapshots();

	public Vector getGraphs();

	public Vector getDrawings();

	public Vector getText();

	public Vector getAllEntries();

	public boolean isEmpty();

	public void addLabbookListener(OTChangeListener listener);

	public void removeLabbookListener(OTChangeListener listener);

}

Update methods on interface to allow adding reference objects

git-svn-id: fdf63cc6b6871a635be2b727c8623e4c3a9a9ed7@15418 6e01202a-0783-4428-890a-84243c50cc2b


/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms.util;

import jssc.SerialPortEvent;
import org.junit.jupiter.api.*;

import java.util.Arrays;

/**
 * Test class for {@link EKGSerialPort}.
 *
 * @since December 14, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
class EKGSerialPortTest {

    private static long READ_DURATION = (long) 3e9;  // 3 seconds, expressed in nanoseconds

    private EKGSerialPort serialPort;

    @BeforeEach
    void setUp() {
        serialPort = new EKGSerialPort() {
            @Override
            public void serialEvent(SerialPortEvent serialPortEvent) {

            }
        };
        serialPort.openPort();
    }

    @AfterEach
    void tearDown() {
        serialPort.closePort();
    }

    @Test
    void testInTerminal() {
        int[] data;

        long startTime = System.nanoTime();
        do {
            data = serialPort.readIntArray();

            if (data != null && data.length > 0) {
                System.out.println(Arrays.toString(data));
            }
        } while (System.nanoTime() - startTime < READ_DURATION);
    }

}

/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms.util;

import org.junit.jupiter.api.*;

import java.util.Arrays;

/**
 * Test class for {@link EKGSerialPort}.
 *
 * @since December 14, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
class EKGSerialPortTest {

    private static long READ_DURATION = (long) 3e9;  // 3 seconds, expressed in nanoseconds

    private EKGSerialPort serialPort;

    @BeforeEach
    void setUp() {
        serialPort = new EKGSerialPort();
        serialPort.openPort();
    }

    @AfterEach
    void tearDown() {
        serialPort.closePort();
    }

    @Test
    void testInTerminal() {
        long startTime = System.nanoTime();

        serialPort.setEventListener(serialPortEvent -> {
            int[] data = serialPort.readIntArray();
            System.out.println(Arrays.toString(data));
        });

        while (System.nanoTime() - startTime < READ_DURATION);
    }

    @Test
    void testInFXChart() {

    }

}

Reimplement test method 'testInTerminal' to use serial port event listener


package fi.vincit.multiusertest.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.junit.runners.model.FrameworkMethod;

import fi.vincit.multiusertest.annotation.TestUsers;

public class TestMethodFilter {
    private UserIdentifier creatorIdentifier;
    private UserIdentifier userIdentifier;

    public TestMethodFilter(UserIdentifier creatorIdentifier, UserIdentifier userIdentifier) {
        Objects.requireNonNull(creatorIdentifier);
        Objects.requireNonNull(userIdentifier);

        this.creatorIdentifier = creatorIdentifier;
        this.userIdentifier = userIdentifier;
    }

    public boolean shouldRun(FrameworkMethod frameworkMethod) {
        TestConfiguration configuration =
                TestConfiguration.fromTestUsers(frameworkMethod.getAnnotation(TestUsers.class));
        Collection<UserIdentifier> creators = configuration.getCreatorIdentifiers();
        Collection<UserIdentifier> users = configuration.getUserIdentifiers();

        boolean shouldRun = true;
        if (!creators.isEmpty()) {
            shouldRun = creators.contains(creatorIdentifier);
        }
        if (!users.isEmpty()) {
            shouldRun = shouldRun && users.contains(userIdentifier);
        }

        return shouldRun;
    }

    public List<FrameworkMethod> filter(List<FrameworkMethod> methods) {
        List<FrameworkMethod> methodsToRun = new ArrayList<>();
        for (FrameworkMethod frameworkMethod : methods) {
            if (shouldRun(frameworkMethod)) {
                methodsToRun.add(frameworkMethod);
            }
        }
        return methodsToRun;
    }
}

package fi.vincit.multiusertest.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.junit.runners.model.FrameworkMethod;

import fi.vincit.multiusertest.annotation.TestUsers;

public class TestMethodFilter {
    private final UserIdentifier creatorIdentifier;
    private final UserIdentifier userIdentifier;

    public TestMethodFilter(UserIdentifier creatorIdentifier, UserIdentifier userIdentifier) {
        Objects.requireNonNull(creatorIdentifier);
        Objects.requireNonNull(userIdentifier);

        this.creatorIdentifier = creatorIdentifier;
        this.userIdentifier = userIdentifier;
    }

    public boolean shouldRun(FrameworkMethod frameworkMethod) {
        TestConfiguration configuration =
                TestConfiguration.fromTestUsers(frameworkMethod.getAnnotation(TestUsers.class));
        Collection<UserIdentifier> creators = configuration.getCreatorIdentifiers();
        Collection<UserIdentifier> users = configuration.getUserIdentifiers();

        boolean shouldRun = true;
        if (!creators.isEmpty()) {
            shouldRun = creators.contains(creatorIdentifier);
        }
        if (!users.isEmpty()) {
            shouldRun = shouldRun && users.contains(userIdentifier);
        }

        return shouldRun;
    }

    public List<FrameworkMethod> filter(List<FrameworkMethod> methods) {
        List<FrameworkMethod> methodsToRun = new ArrayList<>();
        for (FrameworkMethod frameworkMethod : methods) {
            if (shouldRun(frameworkMethod)) {
                methodsToRun.add(frameworkMethod);
            }
        }
        return methodsToRun;
    }
}

Add finals to TestMethidFilter properties


package com.stefanengineering;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner initRepository(UserRepository repository) {
        return (args) -> {
            /*
             * repository.save(new User("Stefan", "Eng")); repository.save(new
             * User("John", "Smith")); repository.save(new User("Alex",
             * "Johnson"));
             *
             * logger.info("Customers found with findAll():");
             * logger.info("-------------------------------"); for (User
             * customer : repository.findAll()) {
             * logger.info(customer.toString()); } logger.info("");
             */
        };
    }
}

package com.stefanengineering;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Remove commented out init code

Remove commented out init code


package hu.bme.mit.spaceship;

import java.util.Random;

/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {

  private int torpedos = 0;
  private Random generator = new Random();

  public TorpedoStore(int numberOfTorpedos){
    this.torpedos = numberOfTorpedos;
  }

  public boolean fire(int numberOfTorpedos){
    if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
      throw new IllegalArgumentException("numberOfTorpedos");
    }

    boolean success = false;

    //simulate random overheating of the launcher bay which prevents firing
    double r = generator.nextDouble();

    if (r > 0.01) {
      // successful firing
      this.torpedos -= numberOfTorpedos;
      success = true;
    } else {
      // failure
      success = false;
    }

    return success;
  }

  public boolean isEmpty(){
    return this.torpedos <= 0;
  }

  public int getNumberOfTorpedos() {
    return this.torpedos;
  }
}

package hu.bme.mit.spaceship;

import java.util.Random;

/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {

  private int torpedoCount = 0;
  private Random generator = new Random();

  public TorpedoStore(int numberOfTorpedos){
    this.torpedoCount = numberOfTorpedos;
  }

  public boolean fire(int numberOfTorpedos){
    if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
      throw new IllegalArgumentException("numberOfTorpedos");
    }

    boolean success = false;

    //simulate random overheating of the launcher bay which prevents firing
    double r = generator.nextDouble();

    if (r > 0.01) {
      // successful firing
      this.torpedoCount -= numberOfTorpedos;
      success = true;
    } else {
      // failure
      success = false;
    }

    return success;
  }

  public boolean isEmpty(){
    return this.torpedoCount <= 0;
  }

  public int getTorpedoCount() {
    return this.torpedoCount;
  }
}

Rename variable torpedos to torpedoCount


package at.ac.tuwien.inso.entity;

public enum SemesterType {

    WinterSemester("WS"),
    SummerSemester("SS");

    private final String name;

    SemesterType(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    /**
     * Reverse of toString
     */
    public static SemesterType fromString(String name) {
        for (SemesterType type : SemesterType.values()) {
            if (type.toString().equals(name)) {
                return type;
            }
        }

        throw new IllegalArgumentException("Type '" + name + "' is not a valid SemesterType");
    }
}

package at.ac.tuwien.inso.entity;

public enum SemesterType {

    WinterSemester("WS", 10, 1),
    SummerSemester("SS", 3, 1);

    /**
     * Name of the semester: WS or SS
     */
    private final String name;

    /**
     * Month the semester starts
     */
    private final int startMonth;

    /**
     * Day in month the semester starts
     */
    private final int startDay;

    SemesterType(String name, int startMonth, int startDay) {
        this.name = name;
        this.startMonth = startMonth;
        this.startDay = startDay;
    }

    public int getStartMonth() {
        return startMonth;
    }

    public int getStartDay() {
        return startDay;
    }

    @Override
    public String toString() {
        return name;
    }

    /**
     * Reverse of toString
     */
    public static SemesterType fromString(String name) {
        for (SemesterType type : SemesterType.values()) {
            if (type.toString().equals(name)) {
                return type;
            }
        }

        throw new IllegalArgumentException("Type '" + name + "' is not a valid SemesterType");
    }
}

Add start dates to Semester Types

Add start dates to Semester Types


/*******************************************************************************
 * Copyright © 2019 EMBL - European Bioinformatics Institute
 *

 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the
 * License.
 ******************************************************************************/

package org.mousephenotype.cda.db.repositories;

import org.mousephenotype.cda.db.pojo.Parameter;
import org.springframework.data.repository.CrudRepository;

public interface ParameterRepository extends CrudRepository<Parameter, Long> {

    Parameter getByStableId(String stableId);
}

/*******************************************************************************
 * Copyright © 2019 EMBL - European Bioinformatics Institute
 *

 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the
 * License.
 ******************************************************************************/

package org.mousephenotype.cda.db.repositories;

import org.mousephenotype.cda.db.pojo.Parameter;
import org.springframework.data.repository.CrudRepository;

public interface ParameterRepository extends CrudRepository<Parameter, Long> {

    Parameter getByStableId(String stableId);
    Parameter getFirstByStableId(String stableId);
}

Add method to find first by parameter stable id


package org.synyx.urlaubsverwaltung.security;

/**
 * Spring Security rules that can be used within {@link org.springframework.security.access.prepost.PreAuthorize}
 * annotations.
 */
public final class SecurityRules {

    public static final String IS_OFFICE = "hasAuthority('OFFICE')";
    public static final String IS_BOSS_OR_OFFICE = "hasAnyAuthority('BOSS', 'OFFICE')";
    public static final String IS_BOSS_OR_DEPARTMENT_HEAD = "hasAnyAuthority('BOSS', 'DEPARTMENT_HEAD')";
    public static final String IS_BOSS_OR_DEPARTMENT_HEAD_OR_SECOND_STAGE_AUTHORITY =
        "hasAnyAuthority('BOSS', 'DEPARTMENT_HEAD', 'SECOND_STAGE_AUTHORITY')";

    public static final String IS_PRIVILEGED_USER =
        "hasAnyAuthority('DEPARTMENT_HEAD', 'BOSS', 'OFFICE', 'SECOND_STAGE_AUTHORITY')";

    private SecurityRules() {

        // Hide constructor for util classes
    }
}

package org.synyx.urlaubsverwaltung.security;

/**
 * Spring Security rules that can be used within {@link org.springframework.security.access.prepost.PreAuthorize}
 * annotations.
 */
public final class SecurityRules {

    public static final String IS_OFFICE = "hasAuthority('OFFICE')";
    public static final String IS_BOSS_OR_OFFICE = "hasAnyAuthority('BOSS', 'OFFICE')";
    public static final String IS_BOSS_OR_DEPARTMENT_HEAD_OR_SECOND_STAGE_AUTHORITY =
        "hasAnyAuthority('BOSS', 'DEPARTMENT_HEAD', 'SECOND_STAGE_AUTHORITY')";

    public static final String IS_PRIVILEGED_USER =
        "hasAnyAuthority('DEPARTMENT_HEAD', 'BOSS', 'OFFICE', 'SECOND_STAGE_AUTHORITY')";

    private SecurityRules() {
        // Hide constructor for util classes
    }
}

Remove not needed security rule bossOrDH


package org.clafer.instance;

import org.clafer.ast.AstConcreteClafer;
import org.clafer.ast.AstModel;
import static org.clafer.ast.Asts.IntType;
import static org.clafer.ast.Asts.newModel;
import static org.junit.Assert.*;
import org.junit.Test;

/**
 *
 * @author jimmy
 */
public class InstanceModelTest {

    @Test
    public void testToString() {
        AstModel model = newModel();
        AstConcreteClafer feature = model.addChild("Feature").withCard(1, 1);
        AstConcreteClafer cost = feature.addChild("Cost").withCard(1, 1).refTo(IntType);

        InstanceClafer costInstance = new InstanceClafer(cost, 0, new InstanceRef(IntType, 3));
        InstanceClafer featureInstance = new InstanceClafer(feature, 0, null, costInstance);
        InstanceModel modelInstance = new InstanceModel(featureInstance);

        assertEquals("Feature$0\n    Cost$0 = 3\n", modelInstance.toString());
    }
}

Update test to match new instance syntax.


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

package com.google.gerrit.server.plugins;

import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;

class CleanupHandle {
  private final File tmpFile;
  private final JarFile jarFile;

  CleanupHandle(File tmpFile,
      JarFile jarFile) {
    this.tmpFile = tmpFile;
    this.jarFile = jarFile;
  }

  void cleanup() {
    try {
      jarFile.close();
    } catch (IOException err) {
    }
    if (!tmpFile.delete() && tmpFile.exists()) {
      PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
          + ", retrying to delete it on termination of the virtual machine");
      tmpFile.deleteOnExit();
    } else {
      PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
    }
  }
}

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

package com.google.gerrit.server.plugins;

import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;

class CleanupHandle {
  private final File tmpFile;
  private final JarFile jarFile;

  CleanupHandle(File tmpFile,
      JarFile jarFile) {
    this.tmpFile = tmpFile;
    this.jarFile = jarFile;
  }

  void cleanup() {
    try {
      jarFile.close();
    } catch (IOException err) {
      PluginLoader.log.error("Cannot close " + jarFile.getName(), err);
    }
    if (!tmpFile.delete() && tmpFile.exists()) {
      PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath()
          + ", retrying to delete it on termination of the virtual machine");
      tmpFile.deleteOnExit();
    } else {
      PluginLoader.log.info("Cleaned plugin " + tmpFile.getName());
    }
  }
}

Print error message to log when plugin loader fails to close JAR file

Change-Id: Ic113b7759e094bd18c8c68767d85a25044400cb4


package com.groupon.seleniumgridextras.utilities;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA. User: dima Date: 7/8/14 Time: 3:49 PM To change this template use
 * File | Settings | File Templates.
 */
public class StreamUtility {

  public static String inputStreamToString(InputStream is) throws IOException {
    StringBuilder result = new StringBuilder();
    int in;
    while ((in = is.read()) != -1) {
      result.append((char) in);
    }
    is.close();
    return result.toString();
  }

}

package com.groupon.seleniumgridextras.utilities;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

public class StreamUtility {

  public static String inputStreamToString(InputStream is) throws IOException {
    return IOUtils.toString(is, "UTF-8");
  }

}

Use apache utility instead of the home baged thing


package org.pwd.web.websites;

import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * @author bartosz.walacik
 */
@Controller
@RequestMapping("/serwisy")
class WebsitesController {

    private WebsiteRepository websiteRepository;

    @Autowired
    public WebsitesController(WebsiteRepository websiteRepository) {
        this.websiteRepository = websiteRepository;
    }

    @RequestMapping(method = GET)
    public String getWebsites(Model model,
                              @RequestParam(value = "query", required = false) String query) {

        model.addAttribute("query", query);

        List<Website> websites;
        if (StringUtils.isEmpty(query)) {
            websites = websiteRepository.search("XYZ"); //websiteRepository.findAll();
        } else {
            websites = websiteRepository.search(query);
        }
        model.addAttribute("websites", websites);
        model.addAttribute("websitesTotalCount", websiteRepository.count());
        model.addAttribute("websitesCount", websites.size());

        return "websites";
    }
}

package org.pwd.web.websites;

import org.pwd.domain.websites.Website;
import org.pwd.domain.websites.WebsiteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * @author bartosz.walacik
 */
@Controller
@RequestMapping("/serwisy")
class WebsitesController {

    private WebsiteRepository websiteRepository;

    @Autowired
    public WebsitesController(WebsiteRepository websiteRepository) {
        this.websiteRepository = websiteRepository;
    }

    @RequestMapping(method = GET)
    public String getWebsites(Model model,
                              @RequestParam(value = "query", required = false) String query) {

        model.addAttribute("query", query);

        List<Website> websites;
        if (StringUtils.isEmpty(query)) {
            websites = websiteRepository.findAll();
        } else {
            websites = websiteRepository.search(query);
        }
        model.addAttribute("websites", websites);
        model.addAttribute("websitesTotalCount", websiteRepository.count());
        model.addAttribute("websitesCount", websites.size());

        return "websites";
    }
}

Revert "Zastąpienie findAll generowaniem pustej listy"

This reverts commit b28c03003ff556dd56690ba848062505f951476d.


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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of user accounts.
 *
 * @author Emerson Farrugia
 */
public interface UserRepository extends Repository<User, String> {

    /**
     * @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
     */
    Optional<User> findOne(String username);

    /**
     * @see org.springframework.data.repository.CrudRepository#save(Object)
     */
    User save(User user);
}

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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of user accounts.
 *
 * @author Emerson Farrugia
 */
public interface UserRepository extends Repository<User, String> {

    /**
     * @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
     */
    Optional<User> findOne(String username);

    /**
     * @see org.springframework.data.repository.CrudRepository#save(Object)
     */
    User save(User user);

    /**
     * @see org.springframework.data.repository.CrudRepository#delete(java.io.Serializable)
     */
    void delete(String username);
}

Add a delete method to the user repository for testing purposes.


package protocolsupport.protocol.core.initial;

import io.netty.buffer.ByteBuf;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.utils.netty.ChannelUtils;

public class ProtocolUtils {

	protected static ProtocolVersion get16PingVersion(int protocolId) {
		switch (protocolId) {
			case 78: {
				return ProtocolVersion.MINECRAFT_1_6_4;
			}
			case 74: {
				return ProtocolVersion.MINECRAFT_1_6_2;
			}
			case 73: {
				return ProtocolVersion.MINECRAFT_1_6_1;
			}
			default: {
				return ProtocolVersion.MINECRAFT_1_6_4;
			}
		}
	}

	@SuppressWarnings("deprecation")
	protected static ProtocolVersion readOldHandshake(ByteBuf data) {
		ProtocolVersion version = ProtocolVersion.fromId(data.readUnsignedByte());
		return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_LEGACY;
	}

	@SuppressWarnings("deprecation")
	protected static ProtocolVersion readNettyHandshake(ByteBuf data) {
		if (ChannelUtils.readVarInt(data) == 0x00) {
			ProtocolVersion version = ProtocolVersion.fromId(ChannelUtils.readVarInt(data));
			return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_FUTURE;
		}
		return null;
	}

}

package protocolsupport.protocol.core.initial;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.utils.netty.ChannelUtils;

public class ProtocolUtils {

	protected static ProtocolVersion get16PingVersion(int protocolId) {
		switch (protocolId) {
			case 78: {
				return ProtocolVersion.MINECRAFT_1_6_4;
			}
			case 74: {
				return ProtocolVersion.MINECRAFT_1_6_2;
			}
			case 73: {
				return ProtocolVersion.MINECRAFT_1_6_1;
			}
			default: {
				return ProtocolVersion.MINECRAFT_1_6_4;
			}
		}
	}

	@SuppressWarnings("deprecation")
	protected static ProtocolVersion readOldHandshake(ByteBuf data) {
		ProtocolVersion version = ProtocolVersion.fromId(data.readUnsignedByte());
		return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_LEGACY;
	}

	@SuppressWarnings("deprecation")
	protected static ProtocolVersion readNettyHandshake(ByteBuf data) {
		int packetId = ChannelUtils.readVarInt(data);
		if (packetId == 0x00) {
			ProtocolVersion version = ProtocolVersion.fromId(ChannelUtils.readVarInt(data));
			return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_FUTURE;
		} else {
			throw new DecoderException(packetId + "is not a valid packet id");
		}
	}

}

Throw exception if packet id is wrong

Throw exception if packet id is wrong


/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

	public abstract void goTo(String url);

	public abstract void assertPresenceOf(Finder<WebElement, WebDriver> finder);

	public abstract void assertPresenceOf(
			Matcher<Integer> cardinalityConstraint,
			Finder<WebElement, WebDriver> finder);

	public abstract void type(String input, Finder<WebElement, WebDriver> finder);

	public abstract void clickOn(Finder<WebElement, WebDriver> finder);

	public abstract void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

	public abstract void quit();

}

/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

  void goTo(String url);

  void assertPresenceOf(Finder<WebElement, WebDriver> finder);

  void assertPresenceOf(Matcher<Integer> cardinalityConstraint,
      Finder<WebElement, WebDriver> finder);

  void type(String input, Finder<WebElement, WebDriver> finder);

  void clickOn(Finder<WebElement, WebDriver> finder);

  void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

  void quit();

}

JasonLeyba: Remove unnecessary modifiers and cleanup whitespace.

git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@12481 07704840-8298-11de-bf8c-fd130f914ac9


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

package org.conscrypt.ct;

import org.conscrypt.Internal;

@Internal
public class SerializationException extends Exception {
    public SerializationException() {
    }

    public SerializationException(String message) {
        super(message);
    }

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

    public SerializationException(Throwable cause) {
        super(cause);
    }
}

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

package org.conscrypt.ct;

import org.conscrypt.Internal;

@Internal
public class SerializationException extends Exception {
    private static final long serialVersionUID = -5317873136664833411L;

    public SerializationException() {
    }

    public SerializationException(String message) {
        super(message);
    }

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

    public SerializationException(Throwable cause) {
        super(cause);
    }
}

Add a serialization UID to exception

Add a serialization UID to exception

In case someone needs to serialize this CT exception.


package com.axellience.vuegwtdemo.client;

import com.axellience.vuegwt.client.Vue;
import com.axellience.vuegwt.client.VueGWT;
import com.axellience.vuegwt.client.gwtpanel.VueGwtPanel;
import com.axellience.vuegwtdemo.client.components.counter.CounterComponent;
import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad()
 */
public class VueGwtDemoApp implements EntryPoint
{
    /**
     * This is the entry point method.
     */
    public void onModuleLoad()
    {
        VueGWT.initWithVueLib();

        // Create a simple GWT panel containing a CounterWithTemplateComponent
        RootPanel
            .get("simpleCounterComponentContainer")
            .add(new VueGwtPanel<>(CounterComponent.class));

        Vue.attach("#todoListComponentContainer", TodoListComponent.class);
    }
}

package com.axellience.vuegwtdemo.client;

import com.axellience.vuegwt.client.Vue;
import com.axellience.vuegwt.client.VueGWT;
import com.axellience.vuegwt.client.gwtpanel.VueGwtPanel;
import com.axellience.vuegwtdemo.client.components.counter.CounterComponent;
import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad()
 */
public class VueGwtDemoApp implements EntryPoint
{
    /**
     * This is the entry point method.
     */
    public void onModuleLoad()
    {
        VueGWT.initWithVueLib();

        // Create a simple GWT panel containing a CounterComponent
        RootPanel
            .get("simpleCounterComponentContainer")
            .add(new VueGwtPanel<>(CounterComponent.class));

        Vue.attach("#todoListComponentContainer", TodoListComponent.class);
    }
}

Fix a typo in a Java comment

Fix a typo in a Java comment


package com.sandjelkovic.dispatchd.api.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

/**
 * Created by stefan on 21.1.17..
 */

@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class RelationDto {
	private Long id;
	private Integer order;

	public RelationDto id(final Long id) {
		this.id = id;
		return this;
	}

	public RelationDto order(final Integer order) {
		this.order = order;
		return this;
	}

}

package com.sandjelkovic.dispatchd.api.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

/**
 * Created by stefan on 21.1.17..
 */

@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class RelationDto {
	private Long targetId;
	private Long sourceId;
	private int order;

	public RelationDto id(final Long id) {
		this.targetId = id;
		return this;
	}

	public RelationDto order(final int order) {
		this.order = order;
		return this;
	}

	public RelationDto sourceId(final Long sourceId) {
		this.sourceId = sourceId;
		return this;
	}

}

Insert source id in Relation

Insert source id in Relation


package seedu.bulletjournal.logic.commands;

/**
 * Lists all tasks in the address book to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_SUCCESS = "Listed all tasks";

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowAll();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

package seedu.bulletjournal.logic.commands;

/**
 * Lists all tasks in the address book to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_SUCCESS = "Listed all tasks";

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowUndone();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

Update list command to only list undone tasks


package org.usfirst.frc.team236.robot.commands;

import org.usfirst.frc.team236.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class Shoot extends Command {

    public Shoot() {
        // Use requires() here to declare subsystem dependencies
    	requires(Robot.shooter);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.shooter.setSol(1);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.shooter.setSol(0);
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

package org.usfirst.frc.team236.robot.commands;

import org.usfirst.frc.team236.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class Shoot extends Command {

    public Shoot() {
        // Use requires() here to declare subsystem dependencies
    	requires(Robot.shooter);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.shooter.setSol(1);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.shooter.setSol(-1);
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Make sure solenoid fully retracts pin

Make sure solenoid fully retracts pin


package org.mcupdater.translate;

public enum Languages {
	en_US(new USEnglish());

	private TranslateProxy proxy;

	Languages(TranslateProxy proxy){
		this.proxy = proxy;
	}

	public TranslateProxy getProxy() {
		return this.proxy;
	}

	public static String getLocale() {
		return System.getProperty("user.language") + "_" + System.getProperty("user.country");
	}
}

package org.mcupdater.translate;

public enum Languages {
	en_US(new USEnglish()),
	en_GB(en_US.getProxy()),
	en_CA(en_US.getProxy()),
	en_AU(en_US.getProxy()),
	;

	private TranslateProxy proxy;

	Languages(TranslateProxy proxy){
		this.proxy = proxy;
	}

	public TranslateProxy getProxy() {
		return this.proxy;
	}

	public static String getLocale() {
		return System.getProperty("user.language") + "_" + System.getProperty("user.country");
	}
}

Add additional English locales to demonstrate translation inheritance.


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

// https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem
public class MinimumAbsoluteDifferenceInAnArray {

  private static final String SPACE = " ";

  private static long[] readArray() throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
      reader.readLine(); // Skip this line.
      String[] split = reader.readLine().split(SPACE);
      return Arrays.stream(split).mapToLong(Long::parseLong).toArray();
    }
  }

  private static long getMinAbsoluteDifference(long[] numbers) {
    Arrays.sort(numbers);
    long minDifference = Long.MAX_VALUE;
    for (int i = 0; i < numbers.length; i++) {
      int nextIndex = i + 1;
      if (nextIndex < numbers.length) {
        long currentNumber = numbers[i];
        long nextNumber = numbers[nextIndex];
        long difference = Math.abs(currentNumber - nextNumber);
        minDifference = (difference < minDifference) ? difference: minDifference;
      }
    }
    return minDifference;
  }

  public static void main(String[] args) throws IOException {
    long[] array = readArray();
    long minDifference = getMinAbsoluteDifference(array);
    System.out.println(minDifference);
  }
}

Add solution for Minimum absolute difference in an array problem.


package total;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Total {
    static final List<Pair<Integer, Integer>> pairs = Arrays.asList(
        Pair.of(6, 2),
        Pair.of(2, 6),
        Pair.of(2, 0),
        Pair.of(2, 8)
    );

    private static int percent(int a, int b) {
        return a * 100 / b;
    }

    private static int percent(Pair<Integer, Integer> pair) {
        return percent(pair.left, pair.right);
    }

    private static Optional<Integer> percentOptional(int a, int b) {
        if (b == 0) {
            return Optional.empty();
        } else {
            return Optional.of(a * 100 / b);
        }
    }

    private static Optional<Integer> percentOptional(Pair<Integer, Integer> pair) {
        return percentOptional(pair.left, pair.right);
    }

    private static int percentStrict(int a, NotZeroInt b) {
        return a * 100 / b.number;
    }

    private static int percentStrict(Pair<Integer, NotZeroInt> pair) {
        return percentStrict(pair.left, pair.right);
    }

    public static void main(String[] args) {
        pairs.stream()
            .map(pair -> {
                try {
                    return Optional.of(Total.percent(pair));
                } catch (ArithmeticException e) {
                    return Optional.empty();
                }
            })
            .forEach(System.out::println);

        pairs.stream()
            .map(Total::percentOptional)
            .forEach(System.out::println);

        pairs.stream()
            .map(pair -> pair.rightOptMap(NotZeroInt::of))
            .map(pairOpt -> pairOpt.map(Total::percentStrict))
            .forEach(System.out::println);

        pairs.stream()
            .map(pair -> pair.rightOptMap(NotZeroInt::of))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .map(Total::percentStrict)
            .forEach(System.out::println);
    }
}

Add sample usage of total functions

Add sample usage of total functions


package org.kodejava.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ArrayPrimitiveObjectConversionDemo {
    public static void main(String[] args) {
        int numbers[] = {1, 2, 3, 4, 5};
        boolean booleans[] = {true, false, false, true};
        float decimals[] = {10.1f, 3.14f, 2.17f};

        Integer numbersObjects[] = ArrayUtils.toObject(numbers);
        Boolean booleansObjects[] = ArrayUtils.toObject(booleans);
        Float decimalsObjects[] = ArrayUtils.toObject(decimals);

        numbers = ArrayUtils.toPrimitive(numbersObjects);
        booleans = ArrayUtils.toPrimitive(booleansObjects);
        decimals = ArrayUtils.toPrimitive(decimalsObjects);
    }
}

Add array conversion from primitives to objects.


public class Solution {

    public List<String> fizzBuzz(int n) {

        List<String> fizzbuzzList = new ArrayList<>();

        for (int i = 1; i <= n; i++) {

            if (i % 15 == 0) {
                fizzbuzzList.add("FizzBuzz");
            } else if (i % 3 == 0) {
                fizzbuzzList.add("Fizz");
            } else if (i % 5 == 0) {
                fizzbuzzList.add("Buzz");
            } else {
                fizzbuzzList.add(Integer.toString(i));
            }

        }

        return fizzbuzzList;

    }

}

Create : 412 Fizz Buzz

Create : 412 Fizz Buzz


package fr.treeptik.cloudunit.functions;

import fr.treeptik.cloudunit.dto.LogLine;

import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

/**
 * Created by nicolas on 18/01/2016.
 */
public class LogsFilter {

    public static BiFunction<String, List<LogLine>, List<LogLine>> bySource =
            (source, messages) -> messages.stream()
                    .filter(m -> source.equals(m.getSource()))
                    .collect(Collectors.toList());

    public static BiFunction<String, List<LogLine>, List<LogLine>> byMessage =
            (pattern, messages) -> messages.stream()
                    .filter(m -> m.getMessage().toLowerCase().contains(pattern.toLowerCase()))
                    .collect(Collectors.toList());

}

Remove infinite testCase + introduce new log pattern inherited from Docker 1.9


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

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

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

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

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

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

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

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

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

Test case for account state detection in AD


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsSqsTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsSqsTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Camel-AWS: Create single Karaf feature tests for single components, aws-sqs test


package br.com.delogic.asd.exception;

import org.springframework.util.Assert;

import br.com.delogic.jfunk.Has;

/**
 * Exception que será lançada caso alguma processamento precise ser interrompido
 * porém não é uma regra de negócio.
 *
 * @author Célio
 *
 */
@SuppressWarnings("serial")
public class ProcessException extends AsdException {

    private ProcessException parent;

    public ProcessException(String message) {
        super(message);
    }

    public ProcessException() {
        super(null);
    }

    public static ProcessException of(String message) {
        return new ProcessException(message);
    }

    /**
     * Retorna uma exception que faz equals com o tipo principal, permitindo
     * comparação com uma única instância.
     *
     * @param message
     * @param params
     * @return
     */
    private ProcessException withMessage(String message, Object... params) {
        ProcessException ex = new ProcessException(Has.content(params) ? String.format(message, params) : message) {
            @Override
            public boolean equals(Object obj) {
                return ProcessException.this == obj;
            }
        };
        ex.parent = this;
        return ex;
    }

    public ProcessException thrownIf(boolean condition) throws ProcessException {
        Assert.hasText(getMessage());
        if (condition) {
            throw this;
        }
        return this;
    }

    public ProcessException thrownIf(boolean condition, String message, Object... params) throws ProcessException {
        Assert.hasText(message);
        if (condition) {
            throw withMessage(message, params);
        }
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof ProcessException)) {
            return false;
        }
        ProcessException that = (ProcessException) obj;
        return this == that || this == that.parent;
    }

    public boolean is(ProcessException ex) {
        return equals(ex);
    }

}

Add exception for interrupted processing


package apps.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.security.MessageDigest;

// TODO(schreib): Remove this file... just checking it in so that I can pick it up
// on another machine when I'm on vacation.
public class TestTool {
    // Private helper methods that handle common HTTP tasks.
    private static String readMessageContent(Socket s) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null){
            sb.append(line + "\n");
        }
        return sb.toString();
    }

    public static void writeClientRequest(Socket socket, InetAddress theAddress) throws IOException
    {
        PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
        socketOut.print("GET / HTTP/1.0\n");
        socketOut.print("Host: " + theAddress.getHostName() + "\n");
        socketOut.print("Accept: */* \n\n");
        socketOut.flush();
    }

    public static void main(String[] args) {
        Socket s;
        try {
            InetAddress theAddress = InetAddress.getByName("ggp-webkiosk.appspot.com");
            System.out.println(theAddress.getHostName());
            System.out.println(theAddress.getHostAddress());
            s = new Socket(theAddress.getHostAddress(), 80);
            writeClientRequest(s, theAddress);
            String theMessage = readMessageContent(s);
            System.out.println("-------------------");
            System.out.println(theMessage);
            System.out.println("-------------------");
            System.out.println(String.valueOf(MessageDigest.getInstance("MD5").digest(theMessage.getBytes())));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Add a test file that will go away soon; please ignore.

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


package server.dto;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigurationProperties {

	private static Properties properties;

	static
	{
		loadProperties();
	}

	public static void loadProperties() {
		Properties prop = new Properties();
		InputStream input = ConfigurationProperties.class.getClassLoader().getResourceAsStream("config.properties");;

		try {
			// load a properties file
			prop.load(input);

			// get the property value and print it out
			//System.out.println(prop.toString());

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

		properties = prop;
	}

	public static String dbHost()
	{
		return properties.getProperty("db_host");
	}

	public static String dbPort()
	{
		return properties.getProperty("db_port");
	}

	public static String dbSchema()
	{
		return properties.getProperty("db_schema");
	}

	public static String dbUser()
	{
		return properties.getProperty("db_user");
	}

	public static String dbPassword()
	{
		return properties.getProperty("db_password");
	}

	public static String rmiBasePath()
	{
		return properties.getProperty("rmi_basepath");
	}

	public static String rmiPort()
	{
		return properties.getProperty("rmi_port");
	}

	public static String rmiRegistry()
	{
		return properties.getProperty("rmi_registry");
	}

	public static String rmiFilePolicy()
	{
		return properties.getProperty("rmi_file_policy");
	}

	public static String rmiFileKeystore()
	{
		return properties.getProperty("rmi_file_keystore");
	}

	public static String rmiPasswordKeystore()
	{
		return properties.getProperty("rmi_file_keystore_password");
	}

}

Introduce new static class to read config parameters


package guitests;

import static org.junit.Assert.assertTrue;
import static seedu.ezdo.logic.commands.DoneCommand.MESSAGE_DONE_TASK_SUCCESS;

import org.junit.Test;

import seedu.ezdo.testutil.TestTask;
import seedu.ezdo.testutil.TestUtil;

public class DoneCommandTest extends EzDoGuiTest {

    @Test
    public void done_success() {

        //delete the first in the list
        TestTask[] currentList = td.getTypicalTasks();
        TestTask[] doneList = td.getTypicalDoneTasks();
        int targetIndex = 1;
        TestTask toDone = currentList[targetIndex - 1];
        assertDoneSuccess(targetIndex, currentList, doneList);

        //delete the last in the list
        currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
        doneList = TestUtil.addTasksToList(doneList, toDone);
        targetIndex = currentList.length;
        assertDoneSuccess(targetIndex, currentList, doneList);

        //invalid index
        currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
        doneList = TestUtil.addTasksToList(doneList, toDone);
        commandBox.runCommand("done " + currentList.length + 1);
        assertResultMessage("The task index provided is invalid");
    }

    private void assertDoneSuccess(int targetIndexOneIndexed, final TestTask[] currentList, final TestTask[] doneList) {

        TestTask taskToDone = currentList[targetIndexOneIndexed - 1]; // -1 as array uses zero indexing
        TestTask[] expectedRemainder = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed);
        TestTask[] expectedDone = TestUtil.addTasksToList(doneList, taskToDone);

        commandBox.runCommand("done " + targetIndexOneIndexed);

        //confirm the list now contains all done tasks including the one just marked as done
        assertTrue(taskListPanel.isListMatching(expectedDone));

        //confirm the result message is correct
        assertResultMessage(String.format(MESSAGE_DONE_TASK_SUCCESS, taskToDone));

        //confirm the undone list does not contain the task just marked as done
        commandBox.runCommand("list");
        assertTrue(taskListPanel.isListMatching(expectedRemainder));
    }

}

Add preliminary test cases for DoneCommand


package leetcode.word_break_ii;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Solution {
	public boolean wordBreak(boolean[] impossible, ArrayList<String> ans, char[] chars, int start, int end, Set<String> dict, String prefix, StringBuilder sb) {
		int len = end - start;
		if(len == 0){
			ans.add(sb.toString());
			return true;
		}
		boolean ret = false;
		for(int i = len; i >= 0; i--){
			String w = new String(chars, start, i);
			if(dict.contains(w) && (i == len || !impossible[start + i])){
				int prevLength = sb.length();
				sb.append(prefix);
				sb.append(w);
				if(wordBreak(impossible, ans, chars, start + i, end, dict, " ", sb)){
					ret = true;
				}else{
					impossible[start + i] = true;
				}
				sb.setLength(prevLength);
			}
		}
		return ret;
	}

	public ArrayList<String> wordBreak(String s, Set<String> dict) {
		ArrayList<String> ans = new ArrayList<String>();
		if(dict.size() == 0) return ans;
		wordBreak(new boolean[s.length()], ans, s.toCharArray(), 0, s.length(), dict, "", new StringBuilder());
		return ans;
	}

	public static void main(String[] args){
		Set<String> input = new HashSet<String>(Arrays.asList(new String[]{"a","aa"}));

		System.err.println(new Solution().wordBreak("aaaaa", input));
	}
}

Add java solution for 140. Word Break II

140. Word Break II: https://leetcode.com/problems/word-break-ii/


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

import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitRequest;
import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQuerySubmitRequest;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQuerySubmitResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.transaction.OSessionOperationId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class ONetworkSubmitResponseTest {

  @Test
  public void testSerialize() throws IOException {

    String db = "testDb";
    OSessionOperationId opId = new OSessionOperationId("foo");
    ODDLQuerySubmitResponse res = new ODDLQuerySubmitResponse();
    ONetworkSubmitResponse response = new ONetworkSubmitResponse(db, opId, res);

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

    ONetworkSubmitResponse response2 = new ONetworkSubmitResponse();
    response2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(response.getCommand(), response2.getCommand());
    Assert.assertEquals(response.getDatabase(), response2.getDatabase());
    Assert.assertEquals(response.getOperationId(), response2.getOperationId());
    OSubmitResponse res2 = response2.getResponse();
    Assert.assertEquals(res.getResponseType(), res2.getResponseType());
    Assert.assertEquals(res.getClass(), res2.getClass());

  }
}

Add serialization tests for ONetworkSubmitResponse


package main.java.engine;

import java.awt.geom.Point2D;
import java.util.List;
import main.java.engine.objects.monster.Monster;

/**
 *
 * Use EnvironmentKnowledge to abstract the passing of limited information into Tower and/or Monster
 * behavior method calls.
 *
 * Goal is to give access to information about the environment of objects,
 * and change their state with controlled methods,
 * but not the ability nor access to directly modify the environmental objects themselves.
 *
 * Contains helper methods to return info which relies on knowledge unknown to individual objects
 * (typically aggregate info about the entire field of towers and monsters)
 * and methods to change state of environmental objects in a controlled manner.
 *
 * @author Austin
 *
 */
public class EnvironmentKnowledge {

    List<Monster> allMonsters;
    Player currentPlayer;

    /**
     * Add necessary state info.
     *
     * @param allMonsters
     */
    public EnvironmentKnowledge (List<Monster> allMonsters, Player currentPlayer) {

        // add more parameters as necessary

        this.allMonsters = allMonsters;
        this.currentPlayer = currentPlayer;

    }

    /**
     * Returns the coordinate of the monster nearest to the coordinate passed in
     *
     * @param x tower x-coor
     * @param y tower y-coor
     * @return coordinates of the nearest monster in the form of a Point2D object
     */
    public Point2D getNearestMonsterCoordinate (double x, double y) {

        double minDistance = Double.MAX_VALUE;
        Point2D closestMonsterCoor = null;
        Point2D towerCoor = new Point2D.Double(x, y);

        for (Monster m : allMonsters) {
            if (m.getCurrentCoor().distance(towerCoor) < minDistance) {
                minDistance = m.getCurrentCoor().distance(towerCoor);
                closestMonsterCoor = centerCoordinate(m);
            }
        }

        return closestMonsterCoor;
    }

    /**
     * Returns the center of the object for targeting
     *
     * @param m object coordinate
     * @return the center of the objects image according to the imageBBox
     */
    private Point2D centerCoordinate (Monster m) {
        return new Point2D.Double(m.getCurrentCoor().getX() + m.getImageBBoxConst().width / 2,
                                  m.getCurrentCoor().getY() + m.getImageBBoxConst().height / 2);
    }

    /**
     * Give the current player a specified amount of money.
     *
     * @param grantedMoney money to be given to player
     */
    public void grantPlayerMoney (int grantedMoney) {
        currentPlayer.addMoney(grantedMoney);
    }

}

Add a EnvironmentKwowledge object for Model to delegate more easily


package it;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class SanityTests {

  private static final String BACH = "src/bach/Bach.java";

  private static final List<String> EXPECTED_NORMAL_OUTPUT_LINES =
      List.of(">> INITIALIZATION >>", "  home='' -> " + Path.of("").toUri(), "  work='bin'");

  @Test
  @DisplayName("jshell Bach.jsh")
  void openAndRunInJShellReturnsZero() throws Exception {
    var builder = new ProcessBuilder("jshell");
    builder.command().add("--execution=local");
    builder.command().add("-J-ea");
    builder.command().add("-"); // Standard input, without interactive I/O.
    var process = builder.start();
    var source =
        List.of(
            "/open " + BACH,
            "var code = 0",
            "try {",
            "  Bach.of().main(List.of(\"info\"));",
            "} catch (Throwable throwable) {",
            "  throwable.printStackTrace();",
            "  code = 1;",
            "}",
            "");
    process.getOutputStream().write(String.join("\n", source).getBytes());
    process.getOutputStream().write("/exit code\n".getBytes());
    process.getOutputStream().flush();
    process.waitFor(19, TimeUnit.SECONDS);
    assertStreams(List.of(), process);
    assertEquals(0, process.exitValue(), process.toString());
  }

  @Test
  @DisplayName("java Bach.java")
  void compileAndRunWithJavaReturnsZero() throws Exception {
    var builder = new ProcessBuilder("java");
    builder.command().add("-ea");
    builder.command().add(BACH);
    builder.command().add("info");
    var process = builder.start();
    process.waitFor(19, TimeUnit.SECONDS);
    assertStreams(List.of(), process);
    assertEquals(0, process.exitValue(), process.toString());
  }

  static void assertStreams(List<String> expectedErrorStreamLines, Process process) {
    var out = lines(process.getInputStream());
    var err = lines(process.getErrorStream());
    try {
      assertLinesMatch(EXPECTED_NORMAL_OUTPUT_LINES, out);
      assertLinesMatch(expectedErrorStreamLines, err);
    } catch (AssertionError e) {
      var msg = String.join("\n", err) + String.join("\n", out);
      System.err.println(msg);
      throw e;
    }
  }

  static List<String> lines(InputStream stream) {
    try (var reader = new BufferedReader(new InputStreamReader(stream))) {
      return reader.lines().collect(Collectors.toList());
    } catch (IOException e) {
      throw new UncheckedIOException("Reading from stream failed!", e);
    }
  }
}

Add sanity tests ensuring generated Bach.java is compile- and executable


package in.webplay.poker;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

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

public class HandTest {
    Hand hand;

    @Before
    public void before() {
        hand = new Hand(null);
    }

    @Test
    public void shouldBeAbleToBuildAHandFromAString() {
        String cardStr = "As Ac Kd Kh 7c";
        Hand hand = Hand.fromString(cardStr);
        assertEquals(cardStr, hand.toString());
    }

    @Test
	public void shouldIdentifyThreeSameSuits() throws Exception {
		Hand threeFlush = Hand.fromString("2c 5d 8c Ac 7h");
		assertThat(threeFlush.numSameSuits(), is(3));
	}

    @Test
	public void flushShouldHaveFiveSameSuits() {
		Hand flush = Hand.fromString("2c 5c 8c Ac 7c");
		assertThat(flush.numSameSuits(), is(5));
	}
}

//describe('POKER.Hand.numSameSuits()', function () {
//    it('trip aces should have two same suits', function () {
//        tripAces.numSameSuits().should.equal(2);
//    });
//
//    it('flush should have five same suits', function () {
//        flush.numSameSuits().should.equal(5);
//    });
//
//});

Add tests for Hand class

Add tests for Hand class


package leetcode.peeking_iterator;

import java.util.Iterator;

class PeekingIterator implements Iterator<Integer> {

    private Iterator<Integer> mIterator;
    private Integer mNext;
    private boolean mHasNext;

    private final void nextInternal(){
        mHasNext = mIterator.hasNext();
        if(mHasNext){
            mNext = mIterator.next();
        }
    }

    public PeekingIterator(Iterator<Integer> iterator) {
        mIterator = iterator;
        nextInternal();
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return mNext;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if(mHasNext){
            Integer ret = mNext;
            nextInternal();
            return ret;
        }else{
            return null; // don't know how to handle
        }
    }

    @Override
    public boolean hasNext() {
        return mHasNext;
    }

    @Override
    public void remove() {

    }
}

Add solution for 284. Peeking Iterator

Add solution for 284. Peeking Iterator

284. Peeking Iterator: https://leetcode.com/problems/peeking-iterator/


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

package org.bson.diagnostics;

import java.util.logging.Logger;

/**
 * This class is not part of the public API.
 *
 * @since 3.0
 */
public final class Loggers {
    /**
     * The prefix for all logger names.
     */
    public static final String PREFIX = "org.bson";

    /**
     * Gets a logger with the given suffix appended on to {@code PREFIX}, separated by a '.'.
     *
     * @param suffix the suffix for the logger.
     * @return the logger
     * @see Loggers#PREFIX
     */
    public static Logger getLogger(final String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("suffix can not be null");
        }
        if (suffix.startsWith(".") || suffix.endsWith(".")) {
            throw new IllegalArgumentException("The suffix can not start or end with a '.'");
        }
        return Logger.getLogger(PREFIX + ":" + suffix);
    }

    private Loggers() {
    }
}

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

package org.bson.diagnostics;

import java.util.logging.Logger;

/**
 * This class is not part of the public API.
 *
 * @since 3.0
 */
public final class Loggers {
    /**
     * The prefix for all logger names.
     */
    public static final String PREFIX = "org.bson";

    /**
     * Gets a logger with the given suffix appended on to {@code PREFIX}, separated by a '.'.
     *
     * @param suffix the suffix for the logger.
     * @return the logger
     * @see Loggers#PREFIX
     */
    public static Logger getLogger(final String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("suffix can not be null");
        }
        if (suffix.startsWith(".") || suffix.endsWith(".")) {
            throw new IllegalArgumentException("The suffix can not start or end with a '.'");
        }
        return Logger.getLogger(PREFIX + "." + suffix);
    }

    private Loggers() {
    }
}

Replace : with . in logger names.

JAVA-1185: Replace : with . in logger names.


// Copyright 2019 Google LLC
//
// 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 com.google.sps.data;

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

/**
 * Keeps track of a student's information, which includes their name, email, topics they
 * are learning, and tutoring sessions they have scheduled.
 * Student connects to the overarching database as a list of Students inside the database.
 */
public final class Student {

    private String name;
    private String email;
    private String[] learning;
    private TutorSession[] scheduledSessions;

    public Student(String name, String email, String[] learning, TutorSession[] scheduledSessions) {
        this.name = name;
        this.email = email;
        this.learning = learning;
        this.scheduledSessions = scheduledSessions;
    }

    public String getName() {
        return this.name;
    }

    public String getEmail() {
        return this.email;
    }

    public String[] getLearning() {
        return this.learning;
    }

    public TutorSession[] getScheduledSessions() {
        return this.scheduledSessions;
    }

    /** Adds the given Tutor Session to the scheduledSessions array. */
    public void addToScheduledSessions(TutorSession tutoringSession) {
        List<TutorSession> scheduledSessionsList = new LinkedList<TutorSession>(Arrays.asList(this.scheduledSessions));
        scheduledSessionsList.add(tutoringSession);
        this.scheduledSessions = scheduledSessionsList.toArray(new TutorSession[0]);
    }

}

Create the student object class.

Create the student object class.


package eic.beike.projectx.network.projectXServer;

import android.util.Log;
import com.google.gson.Gson;
import eic.beike.projectx.network.RetrieveReader;
import eic.beike.projectx.util.Constants;
import eic.beike.projectx.util.ScoreEntry;

import java.io.BufferedReader;

/**
 * Used to interact with our database.
 * Created by alex on 10/1/15.
 */
public class Database implements IDatabase {

    /**
     * Register a name for the given id.
     *
     * @return True if registration succeded, false if it failed.
     */
    @Override
    public boolean register(String id, String name) {
        BufferedReader in = RetrieveReader.get(
                Constants.SERVER_URL+"Register.php?id="+ id + "&name=" + name
        );
        if (in != null) {
            Gson gson = new Gson();
            InsertResponse response = gson.fromJson(in, InsertResponse.class);
            Log.d(this.getClass().getSimpleName(),"Got answer from server, message:" + response.getMessage());
            return (response.getSuccess() == 1);
        }
        Log.w(this.getClass().getSimpleName(),"Failed to contact the database.");
        return false;
    }

    /**
     * @param playerId The id, not the name, of the player
     * @param bus
     * @return True if score was recorded correctly, false if it failed.
     */
    @Override
    public boolean recordScore(String playerId, int score, long time, String bus) {
        return false;
    }

    /**
     * @return The best ten scores for all players on all buses.
     */
    @Override
    public ScoreEntry[] getTopTen() {
        return new ScoreEntry[0];
    }

    /**
     * @param playerId
     * @return The best ten scores for the given player.
     */
    @Override
    public ScoreEntry[] getPlayerTopTen(String playerId) {
        return new ScoreEntry[0];
    }
}

Add database implementation of register method.


package ai.vespa.util.http.hc5;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.util.Timeout;

import javax.net.ssl.SSLContext;
import java.time.Duration;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Like {@link VespaHttpClientBuilder}, but with standard TLS based on provided SSL context.
 *
 * @author jonmv
 */
public class DefaultHttpClientBuilder {

    public static final Duration connectTimeout = Duration.ofSeconds(5);
    public static final Duration socketTimeout = Duration.ofSeconds(5);

    private DefaultHttpClientBuilder() { }

    public static HttpClientBuilder create(SSLContext sslContext, String userAgent) {
        return create(() -> sslContext, userAgent);
    }

    /** Creates an HTTP client builder with the given SSL context, and using the provided timeouts for requests where config is not overridden. */
    public static HttpClientBuilder create(Supplier<SSLContext> sslContext, String userAgent) {
        return HttpClientBuilder.create()
                                .setConnectionManager(PoolingHttpClientConnectionManagerBuilder
                                                              .create()
                                                              .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder
                                                                                .create()
                                                                                .setSslContext(sslContext.get())
                                                                                .build())
                                                              .build())
                                .setUserAgent(userAgent)
                                .disableCookieManagement()
                                .disableAutomaticRetries()
                                .disableAuthCaching();
    }

}

Add DefaultHttpClientBuidler for easy SSLContext


package problems;

public class PopulatingNextRightPointers2 {

    // Definition for binary tree with next pointer.
    public class TreeLinkNode {
        int val;
        TreeLinkNode left, right, next;

        TreeLinkNode(int x) {
            val = x;
        }
    }

    public void connect(TreeLinkNode root) {
        TreeLinkNode cur = root, subRow = null, subp = null;
        while (cur != null) {
            if (cur.left != null) {
                if (subRow == null) {
                    subRow = cur.left;
                    subp = subRow;
                } else {
                    subp.next = cur.left;
                    subp = subp.next;
                }
            }
            if (cur.right != null) {
                if (subRow == null) {
                    subRow = cur.right;
                    subp = subRow;
                } else {
                    subp.next = cur.right;
                    subp = subp.next;
                }
            }
            if (cur.next != null)
                cur = cur.next;
            else {
                cur = subRow;
                subRow = null;
            }
        }
    }
}

Add Populating Next Right Pointer 2

Add Populating Next Right Pointer 2