package vooga.request.forwarder;

/**
 * An exception encapsulating when a receiver address could not be resolved
 * to a receiver
 */
public class ReceiverNotFoundException extends Exception {

    private static final long serialVersionUID = 2016239501767275842L;

    private String myAddress;

    /**
     * Create a new receiver not found exception
     *
     * @param address The address that could not be resolved
     */
    public ReceiverNotFoundException(String address){
        super(address + " could not be found");
        myAddress = address;
    }

    /**
     * Get the address
     * @return The address that could not be resolved
     */
    public String address(){
        return myAddress;
    }
}

Remove spacing between static and non static variables


import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class TestaInsercao {

  public static void main(String[] args) throws SQLException {
    Connection connection = Database.getConnection();
    Statement statement = connection.createStatement();
    boolean resultado = statement.execute("insert into Produto (nome, descricao) values('Notebook', 'Notebook i5'", Statement.RETURN_GENERATE_KEYS);
    System.out.println(resultado);

    ResultSet resultSet = statement.getGeneratedKeys();
    while(resultSet.next()) {
      String id = resultSet.getString("id");
      System.out.println(id + " gerado");
    }

    statement.close();
    connection.close();
  }

}

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class TestaInsercao {

  public static void main(String[] args) throws SQLException {
    String nome = "Notebook";
    String descricao = "  Notebook i5";

    Connection connection = Database.getConnection();

    String sql = "insert into Produto (nome, descricao) values(?, ?)";
    PreparedStatement statement = connection.prepareStatement(sql,
        Statement.RETURN_GENERATE_KEYS);
    statement.setString(1, nome);
    statement.setString(2, descricao);

    boolean resultado = statement.execute();
    System.out.println(resultado);

    ResultSet resultSet = statement.getGeneratedKeys();
    while(resultSet.next()) {
      String id = resultSet.getString("id");
      System.out.println(id + " gerado");
    }

    resultSet.close();
    statement.close();
    connection.close();
  }

}

Insert new files, Alura, JDBC e banco de dados em Java, Aula 3


package com.wonderkiln.camerakit;

import android.graphics.Rect;

import java.nio.ByteBuffer;

public class JpegTransformer {

    private ByteBuffer mHandler;

    public JpegTransformer(byte[] jpeg) {
        mHandler = jniStoreJpeg(jpeg, jpeg.length);
    }

    public byte[] getJpeg() {
        return jniCommit(mHandler);
    }

    public int getWidth() {
        return jniGetWidth(mHandler);
    }

    public int getHeight() {
        return jniGetHeight(mHandler);
    }

    public void rotate(int degrees) {
        jniRotate(mHandler, degrees);
    }

    public void flipHorizontal() {
        jniFlipHorizontal(mHandler);
    }

    public void flipVertical() {
        jniFlipVertical(mHandler);
    }

    public void crop(Rect crop) {
        jniCrop(mHandler, crop.left, crop.top, crop.width(), crop.height());
    }

    static {
        System.loadLibrary("jpegTransformer");
    }

    private native ByteBuffer jniStoreJpeg(byte[] jpeg, int size);

    private native byte[] jniCommit(ByteBuffer handler);

    private native int jniGetWidth(ByteBuffer handler);

    private native int jniGetHeight(ByteBuffer handler);

    private native void jniRotate(ByteBuffer handler, int degrees);

    private native void jniFlipHorizontal(ByteBuffer handler);

    private native void jniFlipVertical(ByteBuffer handler);

    private native void jniCrop(ByteBuffer handler, int left, int top, int width, int height);

}

package com.wonderkiln.camerakit;

import android.graphics.Rect;

import java.nio.ByteBuffer;

public class JpegTransformer {

    private ByteBuffer mHandler;

    public JpegTransformer(byte[] jpeg) {
        mHandler = jniStoreJpeg(jpeg, jpeg.length);
    }

    public byte[] getJpeg() {
        return jniCommit(mHandler);
    }

    public int getWidth() {
        return jniGetWidth(mHandler);
    }

    public int getHeight() {
        return jniGetHeight(mHandler);
    }

    public void rotate(int degrees) {
        jniRotate(mHandler, degrees);
    }

    public void flipHorizontal() {
        jniFlipHorizontal(mHandler);
    }

    public void flipVertical() {
        jniFlipVertical(mHandler);
    }

    public void crop(Rect crop) {
        jniCrop(mHandler, crop.left, crop.top, crop.width(), crop.height());
    }

    static {
        System.loadLibrary("yuvOperator");
        System.loadLibrary("jpegTransformer");
    }

    private native ByteBuffer jniStoreJpeg(byte[] jpeg, int size);

    private native byte[] jniCommit(ByteBuffer handler);

    private native int jniGetWidth(ByteBuffer handler);

    private native int jniGetHeight(ByteBuffer handler);

    private native void jniRotate(ByteBuffer handler, int degrees);

    private native void jniFlipHorizontal(ByteBuffer handler);

    private native void jniFlipVertical(ByteBuffer handler);

    private native void jniCrop(ByteBuffer handler, int left, int top, int width, int height);

}

Fix loading error on API level 16 and 17


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

import java.util.function.Predicate;

import io.joynr.qos.QualityOfService;
import io.joynr.qos.TimeComparisonCompatibility;

public abstract class QoSTimeComparisonCompatibility implements Predicate<TimeComparisonCompatibility> {

    protected final QualityOfService qos;

    public QoSTimeComparisonCompatibility(QualityOfService qos) {
        this.qos = qos;
    }

    @Override
    public boolean test(TimeComparisonCompatibility input) {
        Long ttl = getQoSTimeInMillis();
        long currentTime = System.currentTimeMillis();
        long delta = currentTime - input.getTimeInMilliSec();
        return condition(ttl, delta);
    }

    protected abstract boolean condition(long delta, long qosTimeConstraint);

    protected abstract Long getQoSTimeInMillis();
}

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

import java.util.function.Predicate;

import io.joynr.qos.QualityOfService;
import io.joynr.qos.TimeComparisonCompatibility;

public abstract class QoSTimeComparisonCompatibility implements Predicate<TimeComparisonCompatibility> {

    protected final QualityOfService qos;

    protected QoSTimeComparisonCompatibility(QualityOfService qos) {
        this.qos = qos;
    }

    @Override
    public boolean test(TimeComparisonCompatibility input) {
        Long ttl = getQoSTimeInMillis();
        long currentTime = System.currentTimeMillis();
        long delta = currentTime - input.getTimeInMilliSec();
        return condition(ttl, delta);
    }

    protected abstract boolean condition(long delta, long qosTimeConstraint);

    protected abstract Long getQoSTimeInMillis();
}

[Java] Change constructor to protected in abstract class

Having a public constructor in an abstract class is misleading as you
are not allowed to create objects from the abstract class.

Change-Id: I5334c4f686bd95d4929dc1c34bbf1c61441e005b


package com.github.blindpirate.gogradle.core.dependency.lock;

import com.github.blindpirate.gogradle.core.dependency.GolangDependency;
import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet;

import java.util.Collection;

public interface LockedDependencyManager {
    GolangDependencySet getLockedDependencies();

    void lock(Collection<? extends GolangDependency> flatDependencies);
}

package com.github.blindpirate.gogradle.core.dependency.lock;

import com.github.blindpirate.gogradle.build.Configuration;
import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet;
import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency;

import java.util.Collection;

public interface LockedDependencyManager {
    GolangDependencySet getLockedDependencies(Configuration configuration);

    void lock(Collection<? extends ResolvedDependency> flatBuildDependencies,
              Collection<? extends ResolvedDependency> flatTestDependencies);
}

Add support for test dependencies

Add support for test dependencies


package im.actor.core.js.entity;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;

import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportClosure;
import org.timepedia.exporter.client.Exportable;

@Export
@ExportClosure
public interface JsMessagesBindClosure extends Exportable {
    void onBind(JsArray<JsMessage> array,
                JsArray<JavaScriptObject> overlays,
                boolean isLoaded,
                Double receiveDate,
                Double readDate);
}

package im.actor.core.js.entity;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;

import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportClosure;
import org.timepedia.exporter.client.Exportable;

@Export
@ExportClosure
public interface JsMessagesBindClosure extends Exportable {
    void onBind(JsArray<JsMessage> array,
                JsArray<JavaScriptObject> overlays,
                boolean isLoaded,
                double receiveDate,
                double readDate);
}

Fix messages binding date boxing

fix(js): Fix messages binding date boxing


package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import scala.Tuple2;

import java.io.File;

/*
 * Recalibrate the base quality scores inorder to get more accurate scores.
 *
 * See:
 * https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_bqsr_BaseRecalibrator.php
 *
 * For more information.
 *
 */
public class BQSRTargetGenerator extends BaseGATKProgram implements Function<File, Tuple2<File, File>> {

    public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs, String coresPerNode) {
        super("BaseRecalibrator", extraArgs);
        setReference(pathToReference);
        addArgument("-knownSites", knownSites);
        setThreads(coresPerNode);
    }

    public Tuple2<File, File> call(File file) throws Exception {
        setInputFile(file.getPath());
        String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
        File outputTable = new File(outputTableFilename);

        setOutputFile(outputTable.getPath());

        executeProgram();
        return new Tuple2<File, File>(file, outputTable);
    }
}

package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;

import java.io.File;

/*
 * Recalibrate the base quality scores inorder to get more accurate scores.
 *
 * See:
 * https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_bqsr_BaseRecalibrator.php
 *
 * For more information.
 *
 */
public class BQSRTargetGenerator extends BaseGATKProgram {

    public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs, String coresPerNode) {
        super("BaseRecalibrator", extraArgs);
        setReference(pathToReference);
        addArgument("-knownSites", knownSites);
        setThreads(coresPerNode);
    }

    public File generateTargets(File file) throws Exception {
        setInputFile(file.getPath());
        String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
        File outputTable = new File(outputTableFilename);

        setOutputFile(outputTable.getPath());

        executeProgram();
        return outputTable;
    }
}

[Genomics]: Create BQSR targets on a single, merged file, as it is not
scatter-gatherable, and is pretty quick on large files anyways.


package com.github.arteam.simplejsonrpc.client.generator;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Date: 1/12/15
 * Time: 11:17 PM
 * Abstract generator of secure random identifiers
 */
abstract class SecureRandomIdGenerator<T> implements IdGenerator<T> {

    private static final String SHA_1_PRNG = "SHA1PRNG";

    protected final SecureRandom secureRandom;

    protected SecureRandomIdGenerator() {
        secureRandom = initSecureRandom();
    }

    private static SecureRandom initSecureRandom() {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(SHA_1_PRNG);
            secureRandom.nextBytes(new byte[]{}); // Important to seed immediately after creation
            return secureRandom;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}

package com.github.arteam.simplejsonrpc.client.generator;

import java.security.SecureRandom;

/**
 * Date: 1/12/15
 * Time: 11:17 PM
 * Abstract generator of secure random identifiers
 */
abstract class SecureRandomIdGenerator<T> implements IdGenerator<T> {

    protected final SecureRandom secureRandom;

    protected SecureRandomIdGenerator() {
        this(new SecureRandom());
    }

    protected SecureRandomIdGenerator(SecureRandom secureRandom) {
        this.secureRandom = secureRandom;
    }
}

Use Native secure random generator by default

SHA1PRNG is a relic of the old Java 6 times.


package io.quarkus.micrometer.runtime.binder;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;

public class JVMInfoBinder implements MeterBinder {

    @Override
    public void bindTo(MeterRegistry registry) {
        Counter.builder("jvm_info")
                .description("JVM version info")
                .tags("version", System.getProperty("java.runtime.version", "unknown"),
                        "vendor", System.getProperty("java.vm.vendor", "unknown"),
                        "runtime", System.getProperty("java.runtime.name", "unknown"))
                .register(registry)
                .increment();
    }
}

package io.quarkus.micrometer.runtime.binder;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;

public class JVMInfoBinder implements MeterBinder {

    @Override
    public void bindTo(MeterRegistry registry) {
        Counter.builder("jvm.info")
                .description("JVM version info")
                .tags("version", System.getProperty("java.runtime.version", "unknown"),
                        "vendor", System.getProperty("java.vm.vendor", "unknown"),
                        "runtime", System.getProperty("java.runtime.name", "unknown"))
                .register(registry)
                .increment();
    }
}

Fix jvm.info metric naming to match micrometer convention

This patch brings the jvm.info metric in line with other jvm metric names and in line
with general micrometer naming conventions which define "." as the separator.
This will later automatically convert to "_" through a prometheus naming convention if prometheus
export is used. Even in a pure prometheus use-case the difference is relevantas metric mappers
and filters see the original name.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package keygamep3;

/**
 *
 * @author rubenvde
 */
public class Dimensie {
    private int x;
    private int y;

    public Dimensie(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    public void setX(int x){
        this.x = x;
    }

    public void setY(int y){
        this.y = y;
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package keygamep3;

/**
 *
 * @author rubenvde
 */
public class Dimensie {
    private int x;
    private int y;

    public Dimensie(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    public void setX(int x){
        this.x = x;
    }

    public void setY(int y){
        this.y = y;
    }

    public void setDimensieReset(){
        this.x = 0;
        this.y = 0;
    }
}

Reset methode toegevoegd voor de resetKnop


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

/**
 * Internal utility classes for the Log4j 2 API.
 */
package org.apache.logging.log4j.util;

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

/**
 * Internal utility classes for the Log4j 2 API. Note that the use of any classes in this package is not supported.
 * There are no guarantees for binary or logical compatibility in this package.
 */
package org.apache.logging.log4j.util;

Add more info regarding internal classes.


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

public interface URLs {
  public static final String FILE_BUG_URL =
      "https://github.com/google/agi/issues/new?template=standard-bug-report-for-gapid.md";
  // TODO(b/148700785): Create the device compatibility doc and update here
  public static final String DEVICE_COMPATIBILITY_URL =
      "https://github.com/google/agi";
}

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

public interface URLs {
  public static final String FILE_BUG_URL =
      "https://github.com/google/agi/issues/new?template=standard-bug-report-for-gapid.md";
  public static final String DEVICE_COMPATIBILITY_URL = "https://gpuinspector.dev/validation";
}

Fix the validation URL in the UI.

Fix the validation URL in the UI.


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import javax.swing.JComponent;

/**
 * Are scroll bar buttons to be placed together or apart?
 */
public class ScrollBarButtonsTogetherState extends State {
    public ScrollBarButtonsTogetherState() {
        super("ButtonsTogether");
    }

    public boolean isInState(JComponent c) {
        if (false) {
            return true;
        }
        return false;
    }
}

/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import javax.swing.JComponent;
import javax.swing.UIManager;

/**
 * Are scroll bar buttons to be placed together or apart?
 */
public class ScrollBarButtonsTogetherState extends State {
    public ScrollBarButtonsTogetherState() {
        super("ButtonsTogether");
    }

    public boolean isInState(JComponent c) {
        Object clientProperty = c.getClientProperty("SeaGlass.Override.ScrollBarButtonsTogether");
        if (clientProperty != null && clientProperty instanceof Boolean) {
            return (Boolean) clientProperty;
        }

        return UIManager.getBoolean("SeaGlass.ScrollBarButtonsTogether");
    }
}

Set "buttons together" state from client property for override, otherwise from global UI property.


package com.growingwiththeweb.algorithms.interviewquestions.givenrandomfiveimplementrandomseven;

import java.util.Random;

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

    public static int random5() {
        return new Random().nextInt(5) + 1;
    }

    public static int random7() {
        int val = (random5() - 1) * 5 + random5();
        return val > 21 ? random7() : val % 7 + 1;
    }
}

package com.growingwiththeweb.algorithms.interviewquestions.givenrandomfiveimplementrandomseven;

import java.util.Random;

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

    public static int random5() {
        return new Random().nextInt(5) + 1;
    }

    public static int random7() {
        // If 1-21, return the result modulo 7 (12% chance for 1-7), otherwise call
        // recursively (16% chance)
        int val = (random5() - 1) * 5 + random5();
        // If 1-21, return the result modulo 7 (12% chance for 1-7), otherwise call
        // recursively (16% chance)
        return val > 21 ? random7() : val % 7 + 1;
    }
}

Add comment to random7 from random5

Add comment to random7 from random5


package org.coner.core.hibernate.dao;

import io.dropwizard.testing.junit.DAOTestRule;

abstract class AbstractDaoTest {
    DAOTestRule.Builder daoTestRuleBuilder;

    AbstractDaoTest() {
        daoTestRuleBuilder = DAOTestRule.newBuilder()
                .setDriver(org.hsqldb.jdbc.JDBCDriver.class)
                .setUrl("jdbc:hsqldb:mem:coner-" + getClass().getSimpleName())
                .setShowSql(true)
                .useSqlComments(true);
    }

    DAOTestRule.Builder getDaoTestRuleBuilder() {
        return daoTestRuleBuilder;
    }
}

package org.coner.core.hibernate.dao;

import io.dropwizard.testing.junit.DAOTestRule;

abstract class AbstractDaoTest {
    DAOTestRule.Builder daoTestRuleBuilder;

    AbstractDaoTest() {
        daoTestRuleBuilder = DAOTestRule.newBuilder()
                .setDriver(org.hsqldb.jdbc.JDBCDriver.class)
                .setUrl("jdbc:hsqldb:mem:coner-" + getClass().getSimpleName())
                .setShowSql(false)
                .useSqlComments(true);
    }

    DAOTestRule.Builder getDaoTestRuleBuilder() {
        return daoTestRuleBuilder;
    }
}

Disable SQL logging from DAO tests

Disable SQL logging from DAO tests

Was polluting the Travis CI logs


import org.bukkit.plugin.JavaPlugin;

public class @pluginName@ extends JavaPlugin {
    @Override
    public void onEnable() {
    }
}

import org.bukkit.plugin.java.JavaPlugin;

public class @pluginName@ extends JavaPlugin {
    @Override
    public void onEnable() {
    }
}

Use correct import for JavaPlugin

Use correct import for JavaPlugin

Signed-off-by: Ian Macalinao <57a33a5496950fec8433e4dd83347673459dcdfc@giza.us>


package org.codeswarm.lipsum;

class PrefixTemplateNames implements STGroupParagraphGenerator.TemplateNames {

  private final String prefix;
  private final int minIndex;
  private final int maxIndex;

  PrefixTemplateNames(String prefix, int minIndex, int maxIndex) {
    if (minIndex < 0) throw new IllegalArgumentException("minIndex must be >= 0");
    if (minIndex > maxIndex) throw new IllegalArgumentException("maxIndex >= minIndex");
    this.prefix = prefix;
    this.minIndex = minIndex;
    this.maxIndex = maxIndex;
  }

  @Override
  public int getMinIndex() {
    return minIndex;
  }

  @Override
  public int getMaxIndex() {
    return maxIndex;
  }

  @Override
  public String getTemplateName(int index) {
    return prefix + Integer.toString(index);
  }

}

package org.codeswarm.lipsum;

import com.google.common.base.Preconditions;

class PrefixTemplateNames implements STGroupParagraphGenerator.TemplateNames {

  private final String prefix;
  private final int minIndex;
  private final int maxIndex;

  PrefixTemplateNames(String prefix, int minIndex, int maxIndex) {
    Preconditions.checkArgument(minIndex >= 0);
    Preconditions.checkArgument(minIndex <= maxIndex);
    this.prefix = prefix;
    this.minIndex = minIndex;
    this.maxIndex = maxIndex;
  }

  @Override
  public int getMinIndex() {
    return minIndex;
  }

  @Override
  public int getMaxIndex() {
    return maxIndex;
  }

  @Override
  public String getTemplateName(int index) {
    return prefix + Integer.toString(index);
  }

}

Use guava Preconditions to check arguments.


package uk.gov.verifiablelog.merkletree;

import javax.xml.bind.DatatypeConverter;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

class MerkleTreeTestUnit {
    public MerkleTree merkleTree;
    public List<byte[]> leaves;

    public MerkleTreeTestUnit(MerkleTree merkleTree, List<byte[]> leaves) {
        this.merkleTree = merkleTree;
        this.leaves = leaves;
    }
}

public class TestUtil {
    public static MerkleTree makeMerkleTree(List<byte[]> entries) {
        return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
    }

    public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
        return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
    }

    public static MerkleTreeTestUnit makeMerkleTreeTestUnit(MemoizationStore memoizationStore) {
        List<byte[]> leafValues = new ArrayList<>();
        return new MerkleTreeTestUnit(makeMerkleTree(leafValues, memoizationStore), leafValues);
    }

    public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
        return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
    }

    public static String bytesToString(byte[] bytes) {
        return DatatypeConverter.printHexBinary(bytes).toLowerCase();
    }

    public static byte[] stringToBytes(String input) {
        return DatatypeConverter.parseHexBinary(input);
    }
}

package uk.gov.verifiablelog.merkletree;

import javax.xml.bind.DatatypeConverter;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class TestUtil {
    public static MerkleTree makeMerkleTree(List<byte[]> entries) {
        return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
    }

    public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
        return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
    }

    public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
        return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
    }

    public static String bytesToString(byte[] bytes) {
        return DatatypeConverter.printHexBinary(bytes).toLowerCase();
    }

    public static byte[] stringToBytes(String input) {
        return DatatypeConverter.parseHexBinary(input);
    }
}

Remove unused utils and legacy dto test item class


package com.mistraltech.smog.examples.utils;

import java.util.regex.Pattern;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;

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

public final class MatcherTestUtils
{
    private MatcherTestUtils()
    {
    }

    public static void assertMismatch(Object input, Matcher<?> matcher, String descriptionOfMismatch)
    {
        assertFalse(matcher.matches(input));

        Description actualDescriptionOfMismatch = new StringDescription();
        matcher.describeMismatch(input, actualDescriptionOfMismatch);
        assertEquals(singleToDoubleQuotes(descriptionOfMismatch), actualDescriptionOfMismatch.toString());
    }

    public static <T> void assertMismatch(Object input, Matcher<?> matcher, Pattern descriptionOfMismatch)
    {
        assertFalse(matcher.matches(input));

        Description actualDescriptionOfMismatch = new StringDescription();
        matcher.describeMismatch(input, actualDescriptionOfMismatch);
        String actualDescriptionText = actualDescriptionOfMismatch.toString();

        boolean result = descriptionOfMismatch.matcher(actualDescriptionText).matches();

        assertTrue("matching: " + descriptionOfMismatch.pattern() + " against: " + actualDescriptionText, result);
    }

    public static void assertDescription(Matcher<?> matcher, String descriptionOfExpected)
    {
        Description actualDescriptionOfExpected = new StringDescription().appendDescriptionOf(matcher);
        assertEquals(singleToDoubleQuotes(descriptionOfExpected), actualDescriptionOfExpected.toString());
    }

    private static String singleToDoubleQuotes(String text)
    {
        return text.replace('\'', '"');
    }
}

package com.mistraltech.smog.examples.utils;

import java.util.regex.Pattern;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;

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

public final class MatcherTestUtils
{
    private MatcherTestUtils()
    {
    }

    public static void assertMismatch(Object input, Matcher<?> matcher, String descriptionOfMismatch)
    {
        assertFalse(matcher.matches(input));

        Description actualDescriptionOfMismatch = new StringDescription();
        matcher.describeMismatch(input, actualDescriptionOfMismatch);
        assertEquals(singleToDoubleQuotes(descriptionOfMismatch), actualDescriptionOfMismatch.toString());
    }

    public static void assertMismatch(Object input, Matcher<?> matcher, Pattern descriptionOfMismatch)
    {
        assertFalse(matcher.matches(input));

        Description actualDescriptionOfMismatch = new StringDescription();
        matcher.describeMismatch(input, actualDescriptionOfMismatch);
        String actualDescriptionText = actualDescriptionOfMismatch.toString();

        boolean result = descriptionOfMismatch.matcher(actualDescriptionText).matches();

        assertTrue("matching: " + descriptionOfMismatch.pattern() + " against: " + actualDescriptionText, result);
    }

    public static void assertDescription(Matcher<?> matcher, String descriptionOfExpected)
    {
        Description actualDescriptionOfExpected = new StringDescription().appendDescriptionOf(matcher);
        assertEquals(singleToDoubleQuotes(descriptionOfExpected), actualDescriptionOfExpected.toString());
    }

    private static String singleToDoubleQuotes(String text)
    {
        return text.replace('\'', '"');
    }
}

Remove redundant type parameter from custom assertion assertMismatch.


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Wire class for node-repository representation of the history of a node
 *
 * @author smorgrav
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeHistory {
    @JsonProperty("at")
    public Long at;
    @JsonProperty("agent")
    public Agent agent;
    @JsonProperty("event")
    public String event;

    public Long getAt() {
        return at;
    }

    public Agent getAgent() {
        return agent;
    }

    public String getEvent() {
        return event;
    }

    public enum Agent {
        operator,
        application,
        system,
        NodeFailer,
        Rebalancer,
        DirtyExpirer,
        FailedExpirer,
        InactiveExpirer,
        ProvisionedExpirer,
        ReservationExpirer,
        DynamicProvisioningMaintainer
    }

}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Wire class for node-repository representation of the history of a node
 *
 * @author smorgrav
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeHistory {
    @JsonProperty("at")
    public Long at;
    @JsonProperty("agent")
    public Agent agent;
    @JsonProperty("event")
    public String event;

    public Long getAt() {
        return at;
    }

    public Agent getAgent() {
        return agent;
    }

    public String getEvent() {
        return event;
    }

    public enum Agent {
        operator,
        application,
        system,
        NodeFailer,
        Rebalancer,
        DirtyExpirer,
        FailedExpirer,
        InactiveExpirer,
        ProvisionedExpirer,
        ReservationExpirer,
        DynamicProvisioningMaintainer,
        RetiringUpgrader
    }

}

Add new agent to API type

Add new agent to API type


package uk.ac.ebi.spot.goci.curation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.curation.model.CurrentUser;
import uk.ac.ebi.spot.goci.model.SecureUser;
import uk.ac.ebi.spot.goci.repository.SecureUserRepository;

/**
 * Created by emma on 10/02/15.
 *
 * @author emma
 *         <p>
 *         Implementation of springs UserDetailsService
 */
@Service
public class CurrentUserDetailsService implements UserDetailsService {

    // Repository used to find users
    private SecureUserRepository secureUserRepository;

    @Autowired
    public CurrentUserDetailsService(SecureUserRepository secureUserRepository) {
        this.secureUserRepository = secureUserRepository;
    }

    @Override
    public CurrentUser loadUserByUsername(String email) throws UsernameNotFoundException {
        // Check user with email exists

        if (secureUserRepository.findByEmail(email) != null) {
            SecureUser secureUser = secureUserRepository.findByEmail(email);
            return new CurrentUser(secureUser);
        }
        else {
            throw new UsernameNotFoundException("User with email: " + email + " " +
                                                        "was not found");
        }
    }
}

package uk.ac.ebi.spot.goci.curation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.curation.model.CurrentUser;
import uk.ac.ebi.spot.goci.model.SecureUser;
import uk.ac.ebi.spot.goci.repository.SecureUserRepository;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * Created by emma on 10/02/15.
 *
 * @author emma
 *         <p>
 *         Implementation of springs UserDetailsService
 */
@Service
public class CurrentUserDetailsService implements UserDetailsService {

    // Repository used to find users
    private SecureUserRepository secureUserRepository;

    @Autowired
    public CurrentUserDetailsService(SecureUserRepository secureUserRepository) {
        this.secureUserRepository = secureUserRepository;
    }

    @Override
    public CurrentUser loadUserByUsername(String email) throws UsernameNotFoundException {
        // Check user with email exists

        if (secureUserRepository.findByEmail(email) != null) {
            SecureUser secureUser = secureUserRepository.findByEmail(email);
            return new CurrentUser(secureUser);
        }
        else {
            throw new UsernameNotFoundException("User with email: " + email + " " +
                                                        "was not found");
        }
    }

    /**
     * Update a study status
     *
     * @param request request from which to obtain current user
     * @return SecureUser that represents currently logged in user
     */
    public SecureUser getUserFromRequest(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        String name = principal.getName();
        return secureUserRepository.findByEmail(name);
    }
}

Add method to get currently logged in user from http request


package abra;

import htsjdk.samtools.DefaultSAMRecordFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;

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

public class ReadInputStreamRunnable implements Runnable {

	private static final int MAX_QUEUE_SIZE = 600000;

	private InputStream is;
	private Queue<SAMRecord> queue;

	public ReadInputStreamRunnable(InputStream is, Queue<SAMRecord> queue) {
		this.is = is;
		this.queue = queue;
	}

	public void run() {

		final SamReader reader =
		        SamReaderFactory.make()
		                .validationStringency(ValidationStringency.SILENT)
		                .samRecordFactory(DefaultSAMRecordFactory.getInstance())
		                .open(SamInputResource.of(is));

		for (SAMRecord read : reader) {
			while (queue.size() > MAX_QUEUE_SIZE) {
				System.out.println("Queue too big");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) { }
			}
			queue.add(read);
		}

		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}

package abra;

import htsjdk.samtools.DefaultSAMRecordFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;

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

public class ReadInputStreamRunnable implements Runnable {

	private static final int MAX_QUEUE_SIZE = 600000;

	private InputStream is;
	private Queue<SAMRecord> queue;

	public ReadInputStreamRunnable(InputStream is, Queue<SAMRecord> queue) {
		this.is = is;
		this.queue = queue;
	}

	public void run() {

		final SamReader reader =
		        SamReaderFactory.make()
		                .validationStringency(ValidationStringency.SILENT)
		                .samRecordFactory(DefaultSAMRecordFactory.getInstance())
		                .open(SamInputResource.of(is));

		for (SAMRecord read : reader) {
			while (queue.size() > MAX_QUEUE_SIZE) {
//				System.out.println("Queue too big");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) { }
			}
			queue.add(read);
		}

		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}

Remove queue too big logging.

Remove queue too big logging.


package org.traccar.protocol;

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

public class RoboTrackProtocolDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        RoboTrackProtocolDecoder decoder = new RoboTrackProtocolDecoder(new RoboTrackProtocol());

        verifyNull(decoder, binary(
                "00524f424f545241434b00000000000000383638323034303032323533343136313233343536373839303132312e313261000000312e353761000000312e3030000000003e"));

    }

}

package org.traccar.protocol;

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

import java.nio.ByteOrder;

public class RoboTrackProtocolDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        RoboTrackProtocolDecoder decoder = new RoboTrackProtocolDecoder(new RoboTrackProtocol());

        verifyNull(decoder, binary(ByteOrder.LITTLE_ENDIAN,
                "00524f424f545241434b00000000000000383638323034303032323533343136313233343536373839303132312e313261000000312e353761000000312e3030000000003e"));

        verifyPosition(decoder, binary(ByteOrder.LITTLE_ENDIAN,
                "03e020bb5a034409034862120210a9e105000000000000b9"));

        verifyPosition(decoder, binary(ByteOrder.LITTLE_ENDIAN,
                "03f120bb5a30460903426312021798e105000000000000cd"));

    }

}

Add RoboTrack location test cases

Add RoboTrack location test cases


package org.reldb.dbrowser.ui.content.rel.operator;

import org.eclipse.swt.graphics.Image;
import org.reldb.dbrowser.ui.content.rel.DbTreeAction;
import org.reldb.dbrowser.ui.content.rel.DbTreeItem;
import org.reldb.dbrowser.ui.content.rel.NaiveShowTab;
import org.reldb.dbrowser.ui.content.rel.RelPanel;
import org.reldb.rel.client.Tuple;
import org.reldb.rel.client.Tuples;

public class OperatorPlayer extends DbTreeAction {

	public OperatorPlayer(RelPanel relPanel) {
		super(relPanel);
	}

	@Override
	public void go(DbTreeItem item, Image image) {
		Tuples tuples = relPanel.getConnection().getTuples("(EXTEND (sys.Operators UNGROUP Implementations): {opName := Signature || IF ReturnsType <> '' THEN ' RETURNS ' || ReturnsType ELSE '' END IF} WHERE opName = '" + item.getName() + "') {Definition}");
		String definition = "???";
		if (tuples != null)
			for (Tuple tuple: tuples)
				definition = tuple.getAttributeValue("Definition").toString();
		NaiveShowTab typetab = new NaiveShowTab(relPanel, item, definition);
		typetab.setImage(image);
		relPanel.getTabFolder().setSelection(typetab);
	}

}

package org.reldb.dbrowser.ui.content.rel.operator;

import org.eclipse.swt.graphics.Image;
import org.reldb.dbrowser.ui.content.rel.DbTreeAction;
import org.reldb.dbrowser.ui.content.rel.DbTreeItem;
import org.reldb.dbrowser.ui.content.rel.NaiveShowTab;
import org.reldb.dbrowser.ui.content.rel.RelPanel;
import org.reldb.rel.client.Tuple;
import org.reldb.rel.client.Tuples;

public class OperatorPlayer extends DbTreeAction {

	public OperatorPlayer(RelPanel relPanel) {
		super(relPanel);
	}

	@Override
	public void go(DbTreeItem item, Image image) {
		Tuples tuples = relPanel.getConnection().getTuples("(EXTEND (sys.Operators UNGROUP Implementations): {opName := Signature || IF ReturnsType <> '' THEN ' RETURNS ' || ReturnsType ELSE '' END IF} WHERE opName = '" + item.getName() + "') {Definition}");
		String definition = "???";
		if (tuples != null)
			for (Tuple tuple: tuples)
				definition = tuple.getAttributeValue("Definition").toString();
		if (definition.trim().length() == 0)
			definition = "<System-generated definition is unavailable.>";
		NaiveShowTab typetab = new NaiveShowTab(relPanel, item, definition);
		typetab.setImage(image);
		relPanel.getTabFolder().setSelection(typetab);
	}

}

Add message for system-generated definitions.


package com.syntactec.subreddify.resources;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

import java.util.List;

/**
 * This class models the Reddit resources the application uses.
 */
public interface RedditResource {
    @GET("r/{subreddit}/new.json?count=3")
    Call<List<RedditPost>> getPostsNewerThan(@Path("subreddit") String subreddit, @Query("before") String postName);
}

package com.syntactec.subreddify.resources;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

import java.util.List;

/**
 * This class models the Reddit resources the application uses.
 */
public interface RedditResource {
    @GET("r/{subredditQuery}/new.json?limit=3")
    Call<List<RedditPost>> getPostsNewerThan(@Path("subredditQuery") String subredditQuery, @Query("before") String postName);
}

Correct the Reddit API request.

GH-3: Correct the Reddit API request.


package org.twig.extension;

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

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

public class CoreTests {
    @Test
    public void canEnsureIterableOnIterable() {
        Iterable<String> list = new ArrayList<>();
        Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(list);

        Assert.assertSame("Returned list should be the same as the provided list", list, ensuredList);
    }

    @Test
    public void canEnsureIterableOnNonIterable() {
        String notAList = null;
        Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(notAList);

        Assert.assertTrue("Returned list should be a list even though null and another type was provided", ensuredList instanceof Iterable);
    }

    @Test
    public void canCheckInOnString() {
        String haystack = "bar foo baz";

        Assert.assertTrue("Should find foo", Core.inFilter("foo", haystack));
        Assert.assertFalse("Should not find something that's not in the string", Core.inFilter("not in string", haystack));
    }

    @Test
    public void canCheckInOnList() {
        List<String> haystack = Arrays.asList("foo", "bar", "baz");

        Assert.assertTrue("Should find object that's present in array", Core.inFilter("foo", haystack));
        Assert.assertFalse("Should not find object that's not present in array", Core.inFilter("not in the list", haystack));
    }
}

package org.twig.extension;

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

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

public class CoreTests {
    @Test
    public void canEnsureIterableOnIterable() {
        Iterable<String> list = new ArrayList<>();
        Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(list);

        Assert.assertSame("Returned list should be the same as the provided list", list, ensuredList);
    }

    @Test
    public void canEnsureIterableOnNonIterable() {
        String notAList = null;
        Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(notAList);

        Assert.assertTrue("Returned list should be a list even though null and another type was provided", ensuredList instanceof Iterable);
    }

    // TODO test ensureIterable(Map<?>)

    @Test
    public void canCheckInOnString() {
        String haystack = "bar foo baz";

        Assert.assertTrue("Should find foo", Core.inFilter("foo", haystack));
        Assert.assertFalse("Should not find something that's not in the string", Core.inFilter("not in string", haystack));
    }

    @Test
    public void canCheckInOnList() {
        List<String> haystack = Arrays.asList("foo", "bar", "baz");

        Assert.assertTrue("Should find object that's present in array", Core.inFilter("foo", haystack));
        Assert.assertFalse("Should not find object that's not present in array", Core.inFilter("not in the list", haystack));
    }
}

Add a todo in a test

Add a todo in a test


/*
 * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services
 *
 *    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.crimsoncricket.asserts;

public class Assert {

    public static void assertStateNotNull(Object anObject, String message) {
        if (anObject == null)
            throw new IllegalStateException(message);
    }

    public static void assertArgumentNotNull(Object anArgument, String message) {
        if (anArgument == null)
            throw new IllegalArgumentException(message);
    }

    public static void assertStringArgumentNotEmpty(String anArgument, String message) {
        if (anArgument.isEmpty())
            throw new IllegalArgumentException(message);
    }

}

/*
 * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services
 *
 *    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.crimsoncricket.asserts;

import java.util.Collection;

public class Assert {

    public static void assertStateNotNull(Object anObject, String message) {
        if (anObject == null)
            throw new IllegalStateException(message);
    }

    public static void assertArgumentNotNull(Object anArgument, String message) {
        if (anArgument == null)
            throw new IllegalArgumentException(message);
    }

    public static void assertStringArgumentNotEmpty(String anArgument, String message) {
        if (anArgument.isEmpty())
            throw new IllegalArgumentException(message);
    }

    public static void assertArgumentCollectionNotContainsNull(Collection<?> anArgument, String message) {
        if (anArgument.stream().anyMatch(element -> element == null))
            throw new IllegalArgumentException(message);

    }

}

Add method for ensuring that no null values are contained in a collection. passed as an argument.


package com.momnop.furniture.info;

public class ModInfo
{
    public static final String MODID = "furniture";
    public static final String VERSION = "1.0.4";
    public static final String NAME = "How 'Bout That Furniture";
}

package com.momnop.furniture.info;

public class ModInfo
{
    public static final String MODID = "furniture";
    public static final String VERSION = "1.1.0";
    public static final String NAME = "How 'Bout That Furniture";
}

Bump mod version to 1.1.0

Bump mod version to 1.1.0


package github.com.ricallinson.jmmexample;

class Helloworld {
    public static void main(String args[]) {
        System.out.println("Congratulations on your first Java-- application.");
    }
}

package github.com.javaminusminus.jmmexample;

class Helloworld {
    public static void main(String args[]) {
        System.out.println("Congratulations on your first Java-- application.");
    }
}

Change for move to org repo

Change for move to org repo


package alien4cloud.paas.cloudify3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import alien4cloud.paas.cloudify3.service.OrchestratorDeploymentPropertiesService;

@Configuration
public class PluginFactoryConfiguration {

    @Bean(name = "cloudify-orchestrator")
    public CloudifyOrchestratorFactory cloudifyOrchestratorFactory() {
        return new CloudifyOrchestratorFactory();
    }

    @Bean(name = "deployment-properties-service")
    public OrchestratorDeploymentPropertiesService deploymentPropertiesService() {
        return new OrchestratorDeploymentPropertiesService();
    }
}

package alien4cloud.paas.cloudify3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import alien4cloud.paas.cloudify3.service.ArtifactRegistryService;
import alien4cloud.paas.cloudify3.service.OrchestratorDeploymentPropertiesService;

@Configuration
public class PluginFactoryConfiguration {

    @Bean(name = "artifact-registry-service")
    public ArtifactRegistryService artifactRegistryService() {
        return new ArtifactRegistryService();
    }

    @Bean(name = "cloudify-orchestrator")
    public CloudifyOrchestratorFactory cloudifyOrchestratorFactory() {
        return new CloudifyOrchestratorFactory();
    }

    @Bean(name = "deployment-properties-service")
    public OrchestratorDeploymentPropertiesService deploymentPropertiesService() {
        return new OrchestratorDeploymentPropertiesService();
    }
}

Fix bug cloudify 3 provider opensource, context not initialized


package ${package};

import java.util.logging.Level;
import java.util.logging.Logger;

import org.bukkit.plugin.java.JavaPlugin;

public class ${name}Plugin extends JavaPlugin {

	@Override
	public void onEnable() {
		log("Hello world!");
	}

	@Override
	public void onDisable() {
		// Do nothing
	}

	protected Logger getLogger() {
		return getServer().getLogger();
	}

	public void log(Level level, String message) {
		message = "[${name}] " + message;
		getLogger().log(level, message);
	}

	public void log(String message) {
		log(Level.INFO, message);
	}

}

package ${package};

import java.util.logging.Level;
import java.util.logging.Logger;

import org.bukkit.plugin.java.JavaPlugin;

public class ${name}Plugin extends JavaPlugin {

	public void onEnable() {
		log("Hello world!");
	}

	public void onDisable() {
		// Do nothing
	}

	protected Logger getLogger() {
		return getServer().getLogger();
	}

	public void log(Level level, String message) {
		message = "[${name}] " + message;
		getLogger().log(level, message);
	}

	public void log(String message) {
		log(Level.INFO, message);
	}

}

Remove invalid @Override annotations from plugin class


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

import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.initializer.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Base class for integration tests. Mimics the behavior of
 * {@link SpringApplication#run(String...)}.
 *
 * @author Oliver Gierke
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = SampleDataJpaApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
public abstract class AbstractIntegrationTests {

}

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

import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.initializer.ConfigFileApplicationContextInitializer;
import org.springframework.boot.context.initializer.LoggingApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Base class for integration tests. Mimics the behaviour of
 * {@link SpringApplication#run(String...)}.
 *
 * @author Oliver Gierke
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = SampleDataJpaApplication.class, initializers = {
		ConfigFileApplicationContextInitializer.class,
		LoggingApplicationContextInitializer.class })
public abstract class AbstractIntegrationTests {

}

Add logging initializer to tests

Add logging initializer to tests


/*
 *  Copyright (c) 2012-2013 Malhar, Inc.
 *  All Rights Reserved.
 */
package com.malhartech.lib.stream;

import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.Unifier;

/**
 * Counter counts the number of tuples delivered to it in each window and emits the count.
 *
 * @author Chetan Narsude <chetan@malhar-inc.com>
 */
public class Counter implements Operator, Unifier<Integer>
{
  public final transient DefaultInputPort<Object> input = new DefaultInputPort<Object>(this)
  {
    @Override
    public void process(Object tuple)
    {
      count++;
    }

  };
  public final transient DefaultOutputPort<Integer> output = new DefaultOutputPort<Integer>(this)
  {
    @Override
    public Unifier<Integer> getUnifier()
    {
      return Counter.this;
    }

  };

  @Override
  public void beginWindow(long windowId)
  {
    count = 0;
  }

  @Override
  public void merge(Integer tuple)
  {
    count += tuple;
  }

  @Override
  public void endWindow()
  {
    output.emit(count);
  }

  @Override
  public void setup(OperatorContext context)
  {
  }

  @Override
  public void teardown()
  {
  }

  private transient int count;
}

/*
 *  Copyright (c) 2012-2013 Malhar, Inc.
 *  All Rights Reserved.
 */
package com.malhartech.lib.stream;

import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.Unifier;

/**
 * Counter counts the number of tuples delivered to it in each window and emits the count.
 *
 * @author Chetan Narsude <chetan@malhar-inc.com>
 */
public class Counter implements Operator//, Unifier<Integer>
{
  public final transient DefaultInputPort<Object> input = new DefaultInputPort<Object>(this)
  {
    @Override
    public void process(Object tuple)
    {
      count++;
    }

  };
  public final transient DefaultOutputPort<Integer> output = new DefaultOutputPort<Integer>(this)
  {
//    @Override
//    public Unifier<Integer> getUnifier()
//    {
//      return Counter.this;
//    }

  };

  @Override
  public void beginWindow(long windowId)
  {
    count = 0;
  }

//  @Override
  public void merge(Integer tuple)
  {
    count += tuple;
  }

  @Override
  public void endWindow()
  {
    output.emit(count);
  }

  @Override
  public void setup(OperatorContext context)
  {
  }

  @Override
  public void teardown()
  {
  }

  private transient int count;
}

Disable the unifier until the hint is passed to the StramChild about the type of the unifier.


package org.innovateuk.ifs.project.grantofferletter.viewmodel;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static java.util.Collections.singletonList;

/*
 * Holder of values for the other costs rows on GOL finance tables, which are handled differently
 */
public class OtherCostsRowModel {

    private final String otherCostName;
    private Map<String, List<BigDecimal>> otherCostValues;

    public OtherCostsRowModel(String otherCostName,
                              Map<String, List<BigDecimal>> otherCostValues) {
        this.otherCostName = otherCostName;
        this.otherCostValues = otherCostValues;
    }

    public String getOtherCostName() {
        return otherCostName;
    }

    public Map<String, List<BigDecimal>> getOtherCostValues() {
        return otherCostValues;
    }

    public void addToCostValues(String orgName, BigDecimal cost) {
        if(otherCostValues.keySet().contains(orgName)) {
            otherCostValues.get(orgName).add(cost);
        } else {
            otherCostValues.put(orgName, singletonList(cost));
        }
    }
}

package org.innovateuk.ifs.project.grantofferletter.viewmodel;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static java.util.Collections.singletonList;

/*
 * Holder of values for the other costs rows on GOL finance tables, which are handled differently
 */
public class OtherCostsRowModel {

    private final String otherCostName;
    private Map<String, List<BigDecimal>> otherCostValues;

    public OtherCostsRowModel(String otherCostName,
                              Map<String, List<BigDecimal>> otherCostValues) {
        this.otherCostName = otherCostName;
        this.otherCostValues = otherCostValues;
    }

    public String getOtherCostName() {
        return otherCostName;
    }

    public Map<String, List<BigDecimal>> getOtherCostValues() {
        return otherCostValues;
    }

    public void addToCostValues(String orgName, BigDecimal cost) {
        if(otherCostValues.keySet().contains(orgName)) {
            otherCostValues.get(orgName).add(cost);
        } else {
            otherCostValues.put(orgName, singletonList(cost));
        }
    }

    public Collection<String> getOrganisations() {
        return otherCostValues.keySet();
    }

    public BigDecimal getCostValuesForOrg(String organisation) {
        return otherCostValues.get(organisation)
                .stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

Add helper methods to other costs rows

IFS-5895: Add helper methods to other costs rows


package hex.schemas;

import hex.pca.PCAModel;
import water.api.*;

public class PCAModelV3 extends ModelSchema<PCAModel, PCAModelV3, PCAModel.PCAParameters, PCAV3.PCAParametersV3, PCAModel.PCAOutput, PCAModelV3.PCAModelOutputV3> {
  public static final class PCAModelOutputV3 extends ModelOutputSchema<PCAModel.PCAOutput, PCAModelOutputV3> {
    // Output fields; input fields are in the parameters list
    @API(help = "Importance of each principal component")
    public TwoDimTableBase pc_importance;

    @API(help = "Principal components matrix")
    public TwoDimTableBase eigenvectors;

    @API(help = "Frame key for loading matrix")
    public KeyV3.FrameKeyV3 loading_key;
  }

  // TODO: I think we can implement the following two in ModelSchema, using reflection on the type parameters.
  public PCAV3.PCAParametersV3 createParametersSchema() { return new PCAV3.PCAParametersV3(); }
  public PCAModelOutputV3 createOutputSchema() { return new PCAModelOutputV3(); }

  // Version&Schema-specific filling into the impl
  @Override public PCAModel createImpl() {
    PCAModel.PCAParameters parms = parameters.createImpl();
    return new PCAModel( model_id.key(), parms, null );
  }
}

package hex.schemas;

import hex.pca.PCAModel;
import water.api.*;

public class PCAModelV3 extends ModelSchema<PCAModel, PCAModelV3, PCAModel.PCAParameters, PCAV3.PCAParametersV3, PCAModel.PCAOutput, PCAModelV3.PCAModelOutputV3> {
  public static final class PCAModelOutputV3 extends ModelOutputSchema<PCAModel.PCAOutput, PCAModelOutputV3> {
    // Output fields; input fields are in the parameters list
    // TODO: This field is redundant. Remove in next API change.
    @API(help = "Standard deviations")
    public double[] std_deviation;

    @API(help = "Importance of each principal component")
    public TwoDimTableBase pc_importance;

    @API(help = "Principal components matrix")
    public TwoDimTableBase eigenvectors;

    @API(help = "Frame key for loading matrix")
    public KeyV3.FrameKeyV3 loading_key;
  }

  // TODO: I think we can implement the following two in ModelSchema, using reflection on the type parameters.
  public PCAV3.PCAParametersV3 createParametersSchema() { return new PCAV3.PCAParametersV3(); }
  public PCAModelOutputV3 createOutputSchema() { return new PCAModelOutputV3(); }

  // Version&Schema-specific filling into the impl
  @Override public PCAModel createImpl() {
    PCAModel.PCAParameters parms = parameters.createImpl();
    return new PCAModel( model_id.key(), parms, null );
  }
}

Put back redundant std_deviation output

Put back redundant std_deviation output


package org.webdsl.logging;

public class Logger {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(org.webdsl.logging.Logger.class);

    public static final void info(Object message){
        logger.info(message);
    }

    public static final void warn(Object message){
        logger.warn("WARN  " + message);
    }

    public static final void debug(Object message){
        logger.debug(message);
    }

    public static final void error(Object message, Throwable t){
        logger.error("ERROR " + message, t);
    }

    public static final void error(Object message){
        logger.error("ERROR " + message);
    }

    public static final void error(Throwable t){
        logger.error("ERROR ", t);
    }

    public static final void trace(Object message){
        logger.trace(message);
    }

    public static final void fatal(Object message){
        logger.fatal(message);
    }

    public static final void fatal(Object message, Throwable t){
        logger.error("FATAL " + message, t);
    }

    public static final void fatal(Throwable t){
        logger.error("FATAL ", t);
    }
}

package org.webdsl.logging;

import javax.servlet.http.HttpServletRequest;

import utils.AbstractDispatchServletHelper;
import utils.ThreadLocalServlet;

public class Logger {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(org.webdsl.logging.Logger.class);

    public static final void info(Object message){
        logger.info(message);
    }

    public static final void warn(Object message){
        logger.warn("WARN  " + message);
    }

    public static final void debug(Object message){
        logger.debug(message);
    }

    public static final void error(Object message, Throwable t){
        logger.error( addURLSuffix("ERROR " + message), t);
    }

    public static final void error(Object message){
        logger.error( addURLSuffix("ERROR " + message) );
    }

    public static final void error(Throwable t){
        logger.error( addURLSuffix("ERROR "), t);
    }

    public static final void trace(Object message){
        logger.trace(message);
    }

    public static final void fatal(Object message){
        logger.fatal( addURLSuffix( message.toString() ) );
    }

    public static final void fatal(Object message, Throwable t){
        logger.error( addURLSuffix("FATAL " + message), t);
    }

    public static final void fatal(Throwable t){
        logger.error( addURLSuffix("FATAL "), t);
    }

    private static String addURLSuffix( String msg ) {
      AbstractDispatchServletHelper dsh = ThreadLocalServlet.get();
      if(dsh != null) {
        HttpServletRequest req = dsh.getRequest();
        if(req != null) {
          return msg + " [" + req.getRequestURL().toString() + "]";
        }
      }
      //else
      return msg;
    }
}

Add URL to log messages of type ERROR and FATAL


package longcat;

public class Longcat {

    // Source: http://encyclopediadramatica.com/Longcat

    public static final String HEAD_ROW = "" +
            "    /\\___/\\         \n" +
            "   /       \\         \n" +
            "  |  #    # |         \n" +
            "  \\     @   |        \n" +
            "   \\   _|_ /         \n" +
            "   /       \\______   \n" +
            "  / _______ ___   \\  \n" +
            "  |_____   \\   \\__/ \n" +
            "   |    \\__/         \n";
    public static final String BODY_ROW = "" +
            "   |       |          \n";
    public static final String FEET_ROW = "" +
            "   /        \\        \n" +
            "  /   ____   \\       \n" +
            "  |  /    \\  |       \n" +
            "  | |      | |        \n" +
            " /  |      |  \\      \n" +
            " \\__/      \\__/     \n";

    private final int bodySize;

    public Longcat(int bodySize) {
        this.bodySize = bodySize;
    }

    public String getBody() {
        String body = "";
        for (int i = 0; i < bodySize; i++) {
            body += BODY_ROW;
        }
        return body;
    }

    public String toString() {
        return HEAD_ROW + getBody() + FEET_ROW;
    }
}

package longcat;

public class Longcat {

    // Source: http://encyclopediadramatica.com/Longcat

    public static final String HEAD_ROW = "" +
            "    /\\___/\\         \n" +
            "   /       \\         \n" +
            "  |  #    # |         \n" +
            "  \\     @   |        \n" +
            "   \\   _|_ /         \n" +
            "   /       \\______   \n" +
            "  / _______ ___   \\  \n" +
            "  |_____   \\   \\__/ \n" +
            "   |    \\__/         \n";
    public static final String BODY_ROW = "" +
            "   |       |          \n";
    public static final String FEET_ROW = "" +
            "   /        \\        \n" +
            "  /   ____   \\       \n" +
            "  |  /    \\  |       \n" +
            "  | |      | |        \n" +
            " /  |      |  \\      \n" +
            " \\__/      \\__/     \n";

    private final int bodySize;

    public Longcat(int bodySize) {
        this.bodySize = bodySize;
    }

    public String getBody() {
        StringBuilder body = new StringBuilder();
        for (int i = 0; i < bodySize; i++) {
            body.append(BODY_ROW);
        }
        return body.toString();
    }

    public String toString() {
        return HEAD_ROW + getBody() + FEET_ROW;
    }
}

Use StringBuilder to constructo the longcat body, as it can be very loooooooooong


package org.vietabroader.controller;

import org.vietabroader.model.GlobalState;
import org.vietabroader.model.VASpreadsheet;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class SpreadsheetConnectController implements Controller {

    private JButton btnConnect;
    private JTextField txtConnect;
    private static final Logger logger = LoggerFactory.getLogger(SpreadsheetConnectController.class);

    public SpreadsheetConnectController setConnectButton(JButton btn) {
        btnConnect = btn;
        return this;
    }

    public SpreadsheetConnectController setTextSpreadsheetID(JTextField txt) {
        txtConnect = txt;
        return this;
    }

    @Override
    public void control() {
        btnConnect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GlobalState currentState = GlobalState.getInstance();
                try {
                    VASpreadsheet spreadsheet = new VASpreadsheet(txtConnect.getText());
                    spreadsheet.connect();

                    currentState.setStatus(GlobalState.Status.CONNECTED);
                    currentState.setSpreadsheet(spreadsheet);

                    logger.info("Sheet " + spreadsheet.getSpreadsheetTitle() + "connected");
                } catch (Exception ex) {
                    currentState.setStatus(GlobalState.Status.SIGNED_IN);
                    ex.printStackTrace();
                }
            }
        });
    }
}

package org.vietabroader.controller;

import org.vietabroader.model.GlobalState;
import org.vietabroader.model.VASpreadsheet;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class SpreadsheetConnectController implements Controller {

    private JButton btnConnect;
    private JTextField txtConnect;
    private static final Logger logger = LoggerFactory.getLogger(SpreadsheetConnectController.class);

    public SpreadsheetConnectController setConnectButton(JButton btn) {
        btnConnect = btn;
        return this;
    }

    public SpreadsheetConnectController setTextSpreadsheetID(JTextField txt) {
        txtConnect = txt;
        return this;
    }

    @Override
    public void control() {
        btnConnect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GlobalState currentState = GlobalState.getInstance();
                if (currentState.getStatus() == GlobalState.Status.SIGNED_IN || currentState.getStatus() == GlobalState.Status.CONNECTED) {
                    try {
                        VASpreadsheet spreadsheet = new VASpreadsheet(txtConnect.getText());
                        spreadsheet.connect();

                        currentState.setStatus(GlobalState.Status.CONNECTED);
                        currentState.setSpreadsheet(spreadsheet);

                        logger.info("Sheet " + spreadsheet.getSpreadsheetTitle() + "connected");
                    } catch (Exception ex) {
                        currentState.setStatus(GlobalState.Status.SIGNED_IN);
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
}

Add the check for status

Add the check for status


package com.mygdx.states;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.mygdx.handlers.GameStateManager;

/**
 * Created by James on 2/1/2015.
 */
public class Play extends GameState {
    private Texture img;

    public Play(GameStateManager gsm){
        super(gsm);
        img = new Texture("badlogic.jpg");
    }

    public void handleInput(){};
    public void update(float dt){};
    public void render(){
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sb.begin();
        sb.draw(img, 0, 0);
        sb.end();
    };
    public void dispose(){};
}

package com.mygdx.states;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.mygdx.handlers.GameStateManager;

/**
 * Created by James on 2/1/2015.
 */
public class Play extends GameState {
    private Texture img;

    public Play(GameStateManager gsm){
        super(gsm);
        img = new Texture("badlogic.jpg");
    }

    public void handleInput(){};
    public void update(float dt){};
    public void render(){
        Gdx.gl.glClearColor(1, 0, 0, 2);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sb.begin();
        sb.draw(img, 0, 0);
        sb.end();
    };
    public void dispose(){};
}

Change background color from 1 0 0 1 to 1 0 0 2


package jcrib;

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

public class Player {
    private String name;
    private int points;
    private Hand hand;
    private Card cut;
    private List<List<Score>> scores = new ArrayList<>();

    public Player(String name) {
        this.name = name;
        this.hand = new Hand();
    }

    public void addScores(List<Score> scores) {
        this.scores.add(scores);
    }

    public String getName() {
        return name;
    }

    public Hand getHand() {
        return hand;
    }

    public Card getCutCard() {
        return cut;
    }

    public void setCutCard(Card cut) {
        this.cut = cut;
    }

    public int getPoints() {
        return points;
    }

    @Override
    public String toString() {
        return name + ": " + points + " pts; " + hand.toString();
    }
}

package jcrib;

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

import jcrib.cards.Card;
import jcrib.cards.Hand;

public class Player {
    private String name;
    private int points;
    private Hand hand;
    private Card cut;
    private List<List<Score>> scores = new ArrayList<>();

    public Player(String name) {
        this.name = name;
        this.hand = new Hand();
    }

    public void addScores(List<Score> scores) {
        this.scores.add(scores);
    }

    public String getName() {
        return name;
    }

    public Hand getHand() {
        return hand;
    }

    public Card getCutCard() {
        return cut;
    }

    public void setCutCard(Card cut) {
        this.cut = cut;
    }

    public int getPoints() {
        return points;
    }

    @Override
    public String toString() {
        return name + ": " + getPoints() + " pts; " + hand.toString();
    }
}

Update for cards package refactoring

Update for cards package refactoring


package io.elssa.net;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

public class MessageDecoder extends ReplayingDecoder<DecoderState> {

    private int length;

    public MessageDecoder() {
        super(DecoderState.READ_LENGTH);
    }

    @Override
    protected void decode(
            ChannelHandlerContext ctx, ByteBuf buf, List<Object> out)
    throws Exception {

    switch (state()) {
        case READ_LENGTH:
            length = buf.readInt();
            checkpoint(DecoderState.READ_CONTENT);
            /* Fall through to the next state; the entire message may be
             * available */

        case READ_CONTENT:
            ByteBuf frame = buf.readBytes(length);
            checkpoint(DecoderState.READ_LENGTH);

            byte[] payload = new byte[frame.readableBytes()];
            frame.readBytes(payload);
            ElssaMessage msg = new ElssaMessage(payload);
            out.add(msg);
            break;

        default:
            throw new Error("Unknown decoder state");
    }
    }
}

package io.elssa.net;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

public class MessageDecoder extends ReplayingDecoder<DecoderState> {

    private int length;

    public MessageDecoder() {
        super(DecoderState.READ_LENGTH);
    }

    @Override
    protected void decode(
            ChannelHandlerContext ctx, ByteBuf buf, List<Object> out)
    throws Exception {

    switch (state()) {
        case READ_LENGTH:
            length = buf.readInt();
            checkpoint(DecoderState.READ_CONTENT);
            /* Fall through to the next state; the entire message may be
             * available */

        case READ_CONTENT:
            ByteBuf frame = buf.readBytes(length);
            checkpoint(DecoderState.READ_LENGTH);

            byte[] payload = new byte[frame.readableBytes()];
            frame.readBytes(payload);
            MessageContext context = new MessageContext(ctx);
            ElssaMessage msg = new ElssaMessage(payload, context);
            out.add(msg);
            break;

        default:
            throw new Error("Unknown decoder state");
    }
    }
}

Add context to decoded messages

Add context to decoded messages


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

import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

/**
 * Utility class for Renderers
 */
public class RendererUtils {
    private RendererUtils(){
        // uninstantiable
    }
    public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){
        final TableColumnModel columnModel = table.getColumnModel();
        for(int i = 0; i < renderers.length; i++){
            final TableCellRenderer rend = renderers[i];
            if (rend != null) {
                columnModel.getColumn(i).setCellRenderer(rend);
            }
        }
}
}

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

import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

/**
 * Utility class for Renderers
 */
public final class RendererUtils {
    private RendererUtils(){
        // uninstantiable
    }
    public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){
        final TableColumnModel columnModel = table.getColumnModel();
        for(int i = 0; i < renderers.length; i++){
            final TableCellRenderer rend = renderers[i];
            if (rend != null) {
                columnModel.getColumn(i).setCellRenderer(rend);
            }
        }
}
}

Make class final if private constructor

Make class final if private constructor

git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1379860 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 3f465bf45bb0be0db7dd847ad468f1bff0cc6eb0


/*
 * Copyright Myrrix Ltd
 *
 * 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 net.myrrix.client.translating;

public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem {

  private final String itemID;
  private final float value;

  public GenericTranslatedRecommendedItem(String itemID, float value) {
    this.itemID = itemID;
    this.value = value;
  }

  @Override
  public String getItemID() {
    return itemID;
  }

  @Override
  public float getValue() {
    return value;
  }

}

/*
 * Copyright Myrrix Ltd
 *
 * 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 net.myrrix.client.translating;

import java.io.Serializable;

import com.google.common.base.Preconditions;
import org.apache.mahout.common.RandomUtils;

/**
 *
A simple implementation of {@link TranslatedRecommendedItem}.

 *
 * @author Sean Owen
 */
public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem, Serializable {

  private final String itemID;
  private final float value;

  /**
   * @throws IllegalArgumentException if item is null or value is NaN or infinite
   */
  public GenericTranslatedRecommendedItem(String itemID, float value) {
    Preconditions.checkNotNull(itemID);
    Preconditions.checkArgument(!Float.isNaN(value) && !Float.isInfinite(value));
    this.itemID = itemID;
    this.value = value;
  }

  @Override
  public String getItemID() {
    return itemID;
  }

  @Override
  public float getValue() {
    return value;
  }

  @Override
  public String toString() {
    return "GenericTranslatedRecommendedItem[item:" + itemID + ", value:" + value + ']';
  }

  @Override
  public int hashCode() {
    return itemID.hashCode() ^ RandomUtils.hashFloat(value);
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof GenericTranslatedRecommendedItem)) {
      return false;
    }
    GenericTranslatedRecommendedItem other = (GenericTranslatedRecommendedItem) o;
    return itemID.equals(other.getItemID()) && value == other.getValue();
  }

}

Add a few more changes to be consistent with GenericRecommendedItem, like toString()


package app.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.headers().defaultsDisabled().cacheControl();

        http.logout()
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    }
}

package app.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.headers().defaultsDisabled().cacheControl();

        http.logout()
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .logoutSuccessHandler(logoutHandler())
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    }

    private LogoutSuccessHandler logoutHandler() {
        final SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
        final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

        redirectStrategy.setContextRelative(false);
        logoutSuccessHandler.setRedirectStrategy(redirectStrategy);

        return logoutSuccessHandler;
    }
}

Add a LogoutSuccessHandler to show usage of a RedirectStrategy that's not context-relative


/*
 * Copyright 2019 Immutables Authors and Contributors
 *
 * 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.immutables.criteria.expression;

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

/**
 * List of operator for {@link Comparable}
 */
public enum ComparableOperators implements Operator {

  GREATER_THAN(Arity.BINARY),

  GREATER_THAN_OR_EQUAL(Arity.BINARY),

  LESS_THAN(Arity.BINARY),

  LESS_THAN_OR_EQUAL(Arity.BINARY);

  private final Arity arity;

  ComparableOperators(Arity arity) {
    this.arity = arity;
  }

  @Override
  public Arity arity() {
    return arity;
  }

  public static boolean isComparable(Operator operator) {
    Objects.requireNonNull(operator, "operator");
    return Arrays.stream(values()).anyMatch(v -> v.name().equals(operator.name()));
  }

}

/*
 * Copyright 2019 Immutables Authors and Contributors
 *
 * 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.immutables.criteria.expression;

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

/**
 * List of operator for {@link Comparable}
 */
public enum ComparableOperators implements Operator {

  GREATER_THAN(Arity.BINARY),

  GREATER_THAN_OR_EQUAL(Arity.BINARY),

  LESS_THAN(Arity.BINARY),

  LESS_THAN_OR_EQUAL(Arity.BINARY);

  private final Arity arity;

  ComparableOperators(Arity arity) {
    this.arity = arity;
  }

  @Override
  public Arity arity() {
    return arity;
  }

  public static boolean isComparable(Operator operator) {
    if (!(operator instanceof ComparableOperators)) {
      return false;
    }
    return Arrays.asList(values()).contains(operator);
  }

}

Correct enum equality for ComprableOperatos (see isComparable() method)


package com.google.sps.servlets;

import com.google.sps.data.VolunteeringOpportunity;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.DatabaseConstants;
import com.google.sps.utilities.SpannerTasks;
import java.io.IOException;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet to get all volunteering data for a given event */
@WebServlet("/event-volunteering-data")
public class EventVolunteeringDataServlet extends HttpServlet {
  private static final String HARDCODED_EVENT_ID = "0883de79-17d7-49a3-a866-dbd5135062a8";

  /**
   * Queries database for all opportunities with event ID given in the request parameter and writes
   * opportunities to the response.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws IOException if Input/Output error occurs
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TO DO: change eventId to parameter value
    Set<VolunteeringOpportunity> opportunities =
        SpannerTasks.getVolunteeringOpportunitiesByEventId(HARDCODED_EVENT_ID);

    response.setContentType("application/json;");
    response.getWriter().println(CommonUtils.convertToJson(opportunities));
  }
}

package com.google.sps.servlets;

import com.google.sps.data.VolunteeringOpportunity;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.DatabaseConstants;
import com.google.sps.utilities.SpannerTasks;
import java.io.IOException;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet to get all volunteering data for a given event */
@WebServlet("/event-volunteering-data")
public class EventVolunteeringDataServlet extends HttpServlet {
  private static final String EVENT_ID = "event-id";

  /**
   * Queries database for all opportunities with event ID given in the request parameter and writes
   * opportunities to the response.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws IOException if Input/Output error occurs
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String eventId = request.getParameter(EVENT_ID);
    if (eventId == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("No event specified."));
      return;
    }

    Set<VolunteeringOpportunity> opportunities =
        SpannerTasks.getVolunteeringOpportunitiesByEventId(eventId);
    response.setContentType("application/json;");
    response.getWriter().println(CommonUtils.convertToJson(opportunities));
  }
}

Add error checking in servlet and remove hardcoded event id.